Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
CHAPTER 1 INTRODUCTION
Cross site request forgery (abbreviated XSRF or CSRF, sometimes also called Session Riding), denotes a relatively new class of attack against web application users. By launching a successful XSRF attack against a user, an adversary is able to initiate arbitrary HTTP requests from that user to the vulnerable web application. Thus, if the victim is authenticated, a successful XSRF attack effectively bypasses the underlying authentication mechanism. Depending on the web application, the attacker could, for instance, post messages or send mails in the name of the victim, or even change the victims login name and password. Furthermore, the damage caused by such attacks can be severe. In contrast to the well-known web security problems such as SQL injection and XSS, cross site request forgery (XSRF) appears to be a problem that is little known by web application developers and the academic community. As a result, only few mitigation solutions exist. Unfortunately, these solutions do not offer complete protection against XSRF or require significant modifications to each individual web application that should be protected. In this paper, we present a solution that provides protection from XSRF attacks. More precisely, our approach is based on a server-side proxy that detects and prevents XSRF attacks in a way that is transparent to users as well as to the web application itself. One important advantage of our solution is that there is only minimal manual effort required to protect existing applications. Our experimental results demonstrate that we can use our prototype to secure a number of popular open-source web applications against XSRF attacks, without negatively affecting
the applications behavior. An expanded version of this paper containing additional details can be found on our web site.
Users can unknowingly execute malicious scripts when viewing dynamically generated pages based on content provided by an attacker.
An attacker can take over the user session before the user's session cookie expires. An attacker can connect users to a malicious server of the attacker's choice.
An attacker who can convince a user to access a URL supplied by the attacker could cause script or HTML of the attacker's choice to be executed in the user's browser.
considered as a layer of defense in depth. In this system we propose the detection of CSRF attacks with the notion of visibility and content checking of suspected requests. The idea is to intercept a suspected request containing parameters and values and relate them with one of the visible forms present in an open window. If there is an exact match, we modify the suspected request to make it benign, launch it to the remote website, and identify the content type, and match with the expected content type. Any mismatch between request attribute values or content type results in a warning. Our proposed approach does not rely on cross-origin policy or server side program states. Moreover, it does not require storing URLs or tokens to be matched at a later stage for attack detection. The proposed approach is implemented as a Fire fox plugin and evaluated for three real world programs vulnerable to both CSRF and XSS.
2.)faster than programs written in other interpreter languages, such as BASIC 3.)faster than C, C++.
Development time: 1.)java is simple 2.)in java programmers do not need to manipulate memory
Each of the preceding buzzwords is explained in The Java Language Environment, a white paper written by James Gosling and Henry McGilton. In the Java programming language, all source code is first written in plain text files ending with the .java extension. Those source files are then compiled into .class files by the javac compiler. A .class file does not contain code that is native to your processor; it instead contains bytecodes the machine language of the Java Virtual
Machine1 (Java VM). The java launcher tool then runs your application with an instance of the Java Virtual Machine.
Operating System (Solaris OS), Linux, or Mac OS. Some virtual machines, such as the Java HotSpot virtual machine, perform additional steps at runtime to give your application a performance boost. This include various tasks such as finding performance bottlenecks and recompiling (to native code) frequently used sections of code.
Defence mechanism and prevention of attack for cross-site scripting forgery________ Through the Java VM, the same application is capable of running on multiple platforms. The Java Platform
A platform is the hardware or software environment in which a program runs. We've already mentioned some of the most popular platforms like Microsoft Windows, Linux, Solaris OS, and Mac OS. Most platforms can be described as a combination of the operating system and underlying hardware. The Java platform differs from most other platforms in that it's a software-only platform that runs on top of other hardware-based platforms. The Java platform has two components:
The Java Virtual Machine The Java Application Programming Interface (API)
You've already been introduced to the Java Virtual Machine; it's the base for the Java platform and is ported onto various hardware-based platforms. The API is a large collection of ready-made software components that provide many useful capabilities. It is grouped into libraries of related classes and interfaces; these libraries are known as packages. The next section, What Can Java Technology Do? highlights some of the functionality provided by the API.
The API and Java Virtual Machine insulate the program from the underlying hardware. As a platform-independent environment, the Java platform can be a bit slower than native code. However, advances in compiler and virtual machine technologies are bringing performance close to that of native code without threatening portability.
3.3.4. COMPONENTS
Visual controls such as textboxes, checkboxes, listboxes, buttons & combo boxes are called components. container such as font & color. Each component inherits the properties of its parent
Containers: Top level windows that hold these components are called containers. The container also controls the position of components placed in it
Defence mechanism and prevention of attack for cross-site scripting forgery________ 11 Frame Window:
Containers are contained within the frame window, which is another type of a container The framewindow is the top level window & as such it does not have a parent container.
AWT(abstract window toolkit): In java 1.0 user interfaces are created using AWT. The front end applications created using AWT is different on different platforms.
Java Foundation Classes(JFC): JFC is an extension of the original AWT. JFC is an extension of AWT. JFC is first delivered as a part of the java platform It has a rich set of components that are completely cross platform independent & offer improved performance We can create large scale internet & intranet applications using Jfc. This lesson gives you a brief introduction to using the Java Foundation Classes (JFC) Swing packages. After telling you about JFC and Swing, it helps you get the necessary software and walks you through how to compile and run a program that uses the Swing packages. Next, it shows you how to run programs using Java Web Start. The next lesson, learning swing by example, will build on these first steps to help you create several increasingly more complex examples. For now, let's start with the basics.
Defence mechanism and prevention of attack for cross-site scripting forgery________ 12 Compiling and running of swing process This section gives you detailed instructions on how to install, create, compile and run a program that uses Swing components. About JFC and swing JFC is short for Java Foundation Classes, which encompass a group of features for building graphical user interfaces (GUIs) and adding rich graphics functionality and interactivity to Java applications. It is defined as containing the features shown in the table below. Feature Swing GUI Components Features of the Java Foundation Classes Description Includes everything from buttons to split panes to tables. Gives any program that uses Swing components a choice of look and feel. For example, the same program can use either the Java or the Pluggable Look-and- Windows look and feel. Many more look-and-feel packages are Feel Support available from various sources. As of v1.4.2, the Java platform supports the GTK+ look and feel, which makes hundreds of existing look and feels available to Swing programs. Enables assistive technologies, such as screen readers and Braille displays, to get information from the user interface. Enables developers to easily incorporate high-quality 2D graphics, text, and images in applications and applets. Java 2D includes extensive APIs for generating and sending high-quality output to printing devices. Provides the ability to drag and drop between Java applications and native applications. Allows developers to build applications that can interact with users worldwide in their own languages and cultural conventions. With the Internationalization input method framework developers can build applications that accept text in languages that use thousands of different characters, such as Japanese, Chinese, or Korean.
Accessibility API
Java 2D API
Drag-and-Drop Support
Defence mechanism and prevention of attack for cross-site scripting forgery________ 13 This trail concentrates on the Swing components. We help you choose the appropriate components for your GUI, tell you how to use them, and give you the background information you need to use them effectively. We also discuss other JFC features as they apply to Swing components. Version Note: "Swing" was the code name of the project that developed the new components. Although unofficial, it's frequently used to refer to the new components and related API. "Swing" is immortalized in the package names for the Swing API, which begin with javax.swing.
JSP ARCHITECTURE
Defence mechanism and prevention of attack for cross-site scripting forgery________ 14 JSP pages are high level extension of servlet and it enable the developers to embed java code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests. javax.servlet.jsp package defines two interfaces: JSPPage HttpJspPage These interfaces defines the three methods for the compiled JSP page. These methods are: jspInit() jspDestroy() _jspService(HttpServletRequest request,HttpServletResponse response)
In the compiled JSP file these methods are present. Programmer can define jspInit() and jspDestroy() methods, but the _jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine.
Application Programming Interface (API): The API provides the core functionality of the Java programming language. It offers a wide array of useful classes ready for use in your own applications. It spans everything from basic objects, to networking and security, to XML generation and database access, and
Defence mechanism and prevention of attack for cross-site scripting forgery________ 15 more. The core API is very large; to get an overview of what it contains, consult the Java SE Development Kit 6 (JDKTM 6) documentation. Deployment Technologies: The JDK software provides standard mechanisms such as the Java Web Start software and Java Plug-In software for deploying your applications to end users. User Interface Toolkits: The Swing and Java 2D toolkits make it possible to create sophisticated Graphical User Interfaces (GUIs). Integration Libraries: Integration libraries such as the Java IDL API, JDBCTM API, Java Naming and Directory InterfaceTM ("J.N.D.I.") API, Java RMI, and Java Remote Method Invocation over Internet Inter-ORB Protocol Technology (Java RMI-IIOP Technology) enable database access and manipulation of remote objects.
How Will Java Technology Change My Life? We can't promise you fame, fortune, or even a job if you learn the Java programming language. Still, it is likely to make your programs better and requires less effort than other languages. We believe that Java technology will help you do the following:
Defence mechanism and prevention of attack for cross-site scripting forgery________ 16 Get started quickly: Although the Java programming language is a powerful object-oriented language, it's easy to learn, especially for programmers already familiar with C or C++. Write less code: Comparisons of program metrics (class counts, method counts, and so on) suggest that a program written in the Java programming language can be four times smaller than the same program written in C++. Write better code: The Java programming language encourages good coding practices, and automatic garbage collection helps you avoid memory leaks. Its object orientation, its JavaBeansTM component architecture, and its wide-ranging, easily extendible API let you reuse existing, tested code and introduce fewer bugs. Develop programs more quickly: The Java programming language is simpler than C++, and as such, your development time could be up to twice as fast when writing in it. Your programs will also require fewer lines of code. Avoid platform dependencies: You can keep your program portable by avoiding the use of libraries written in other languages. Write once, run anywhere: Because applications written in the Java programming language are compiled into machine-independent bytecodes, they run consistently on any Java platform. Distribute software more easily: With Java Web Start software, users will be able to launch your applications with a single click of the mouse. An automatic version check at startup ensures that users are always up to date with the latest version of your software. If an update is available, the Java Web Start software will automatically update their installation.
3.4.2 ENCAPSULATION
A class is a blueprint or prototype from which objects are created. Objects are key to understanding object-oriented technology. Objects consist of state and related behavior. An object stores its state in fields (variables in some programming languages) and exposes its behavior through methods (functions in some programming languages). Methods operate on an object's internal state and serve as the primary mechanism for object-to-object communication. Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation a fundamental principle of object-oriented programming.
3.4.3 INHERITANCE
Object-oriented programming allows classes to inherit commonly used state and behavior from other classes. In the Java programming language, each class is allowed to have one direct superclass, and each superclass has the potential for an unlimited number of subclasses. Syntax: At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from
3.4.4 INTERFACE
An interface is a contract between a class and the outside world, and this contract is enforced at build time by the compiler. When a class implements an interface, it promises to provide the behavior published by that interface. Implementing an interface allows a class to become more formal about the behavior it promises to provide
3.4.5 PACKAGES.
Using import statement we can use java packages in a program (its similar to include statement in C++) Package contains only classes, whereas a header file can contain independent methods. They have hierarchical structure If the package name is not specified class becomes the member of the default package
public class Swing Application implements ActionListener { ... JButton button = new JButton("I'm a Swing button!"); button.addActionListener(this); .... public void actionPerformed(ActionEvent e) { numClicks++; label.setText(labelPrefix + numClicks); } } Every event handler requires three pieces of code: In the declaration for the event handler class, one line of code specifies that the class either implements a listener interface or extends a class that implements a listener interface. For example: public class MyClass implements ActionListener { Another line of code registers an instance of the event handler class as a listener on one or more components. For example: someComponent.addActionListener(instanceOfMyClass); The event handler class has code that implements the methods in the listener interface. For example: public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }
Defence mechanism and prevention of attack for cross-site scripting forgery________ 20 In general, to detect when the user clicks an onscreen button (or does the keyboard equivalent), a program must have an object that implements the ActionListener interface. The program must register this object as an action listener on the button (the event source), using the addActionListener method. When the user clicks the onscreen button, the button fires an action event. This results in the invocation of the action listener's actionPerformed method (the only method in the ActionListener interface). The single argument to the method is an ActionEvent object that gives information about the event and its source.
Swing components can generate many kinds of events. The following table lists a few examples. Some Events and Their Associated Event Listeners Act that Results in the Event Listener Type User clicks a button, presses Enter while typing
in a text field, or chooses a menu item WindowListener User closes a frame (main window) User presses a mouse button while the cursor is over a component User moves the mouse over a component Component becomes visible Component gets the keyboard focus Table or list selection changes Any property in a component changes such as the text on a label
MouseListener MouseMotionListener ComponentListener FocusListener ListSelectionListener PropertyChangeListener
ActionListener
To learn more about how to detect events from a particular component, refer to each component's how-to section in Using Swing Components.
Defence mechanism and prevention of attack for cross-site scripting forgery________ 21 Client/Server computing is an environment that distributes processing accross many computers. Client/Server system is used to access different databases or services via a network though two-tier or architecture. Figure 1: Two-tier Architecture for Data Access. three-tier
"The job of a client is to request for a service and the job of the server is to serve the request." Basically there are two types of clients. 1. Dependent Clients. 2. Independent Client. Dependent clients are such clients who can connect only to a single database while independent clients connect to various databases through some specific
4.1
ARCHITECTURE DIAGRAM
Data Send to the AttakServer Attacker File a page with Malicious script Attacker's Server
User browser
Malicious script
Attacker's server
Legitimate server
2: Email the Url to user and conviince user to click on it 3: Request the page
5: Run
6: Authorzed Request
5.2 .MODULE DESCRIPTION 1. Client 2. Legitimate server 3. Malicious script 4. Filtering 5. Attackers server 6. Cross-site detection and alert system
1. Clients browser Client can access any website via any browser. The browser which is used by the client currently to access any site is known as clients browser. It may be any browser. Client can access any sites it may be cross site or trusted website. 2. Legitimate server Legitimate server is nothing but it is a trusted website which holds all the services which are needed by many clients. Based on the user request it provides the service. Some times the hackers may write some unwanted malicious code in a trusted site also. Whenever client access the legitimate server the malicious code also started to run. 3. Malicious script When the user unknowingly executes scripts written by an attacker they follow a malicious link in a mail message. Because the malicious scripts are executed in a context that appears to have originated from the legitimate server, the attacker has full access to the document retrieved and may send data contained in the page back to their site. If the embedded script code has additional interactions capability with the legitimate server without alerting the victim, the attacker could develop and exploit that posted data to a different page on the legitimate Web server.
4. Filtering
Defence mechanism and prevention of attack for cross-site scripting forgery________ 28 The basis of this approach is never trust user input and always filters Meta characters ("special" characters) that are defined in the HTML specification. Each input field, including link parameters will be validated for script tags. When found and dependent on the context, the input will be rejected and thus prevent the malicious HTML from being presented to the user. Filtering is performed based on the following sub modules Request checker If a request is a GET type, the destination URL is identified, and the query string is tokenized to obtain request parameters and values. If a request is a POST type, the header is examined to obtain the posted parameters and values as a string, which is tokenized further. If a GET or POST request contains parameters and values, then it is considered as suspected and forwarded to the window and form checker module. Otherwise, it is forwarded to the destination website. Window and form checker In the response page, if no window relates the destination domain, we consider the request as an attack and move program control to attack handler module.
Visibility checking If the displayed page contains no form, we can conclude that the request is
Defence mechanism and prevention of attack for cross-site scripting forgery________ 29 Content checking relies on the matching of the response of a suspected request with the expected response. 5. Attackers server The sensitive data which is hacked from the clients browser is stored in the attackers server. They can miss-use the data in future for hacking the whole system. Cross-site scripting is achieved when an attacker is able to cause a legitimate Web server to send a page to a victim user's Web browser that contains a malicious script of the attacker's choosing. The attacker then has the malicious script run with the privileges of a legitimate script originating from the legitimate Web server. In this scenario, the attacker files a page with malicious script to the part of the site that is vulnerable. When the page is displayed, the malicious script runs, collects the users' cookies, and sends a request to the attacker's Web site with the cookies gathered. Using this technique, the attacker can gain sensitive data such as passwords, credit card numbers, and any arbitrary information the user inputs. 6. Cross-site detection and alert system If malicious code is detected, that code is forwarded to the attack handler module. It stops a suspected request and generates a warning to the browser to aware a user of the deviation identified such as mismatch between the supplied parameters of a request and the actual parameters present in a form. Moreover, it also reports expected and actual content type mismatch. A user can allow or disallow a request
CHAPTER 6 TESTING
TESTING:
Testing is a set of activities that can be planned in advance and conducted systematically. For this reason a template for software testing, a set of steps into which we can place specific test case design techniques and testing methods should be defined for software process. Testing often accounts for more effort than any other software engineering activity. If it is conducted haphazardly, time is wasted, unnecessary effort is expanded, and even worse, errors sneak through undetected. It would therefore seem reasonable to establish a systematic strategy for testing software
Type Of Testing
There are two type of testing according their behaviors I. II. Unconventional Testing Conventional Testing
Unconventional Testing
Defence mechanism and prevention of attack for cross-site scripting forgery________ 31 Unconventional testing is a process of verification which is doing by SQA (Software Quality Assurance) team. It is a prevention technique which is performing from beginning to ending of the project development. In this process SQA team verifying the project development activities and insuring that the developing project is fulfilling the requirement of the client or not.
In this testing the SQA team follows these methods: 1. Peer review 2. Code walk and throw 3. Inspection 4. Document Verification
Conventional Testing
Conventional Testing is a process of finding the bugs and validating the project. Testing team involves in this testing process and validating that developed project is according to client requirement or not. This process is a correction technique where testing team find bugs and reporting to the development team for correction on developed project built.
For these testing the testing team using the following methodologies :
Unit Testing:
The procedure level testing is made first. By giving improper inputs, the errors occurred are noted and eliminated. Then the web form level testing is made. For example storage of data to the table in the correct manner.
In the company as well as seeker registration form, the zero length username and password are given and checked. Also the duplicate username is given and checked. In the job and question entry, the button will send data to the server only if the client side validations are made.
The dates are entered in wrong manner and checked. Wrong email-id and web site URL (Universal Resource Locator) is given and checked.
Integration Testing:
Testing is done for each module. After testing all the modules, the modules are integrated and testing of the final system is done with the test data, specially designed to show that the system will operate successfully in all its aspects conditions. Thus the system testing is a confirmation that all is correct and an opportunity to show the user that the system works.
Module Test:
Defence mechanism and prevention of attack for cross-site scripting forgery________ 33 Module Testing is a process of testing the system, module by module. It includes the various inputs given, outputs produced and their correctness. By testing in this method we would be very clear of all the bugs that have occurred.
Interface Testing:
The Interface Testing is performed to verify the interfaces between sub modules while performing integration of sub modules aiding master module recursively.
Validation Testing:
The final step involves Validation testing, which determines whether the software function as the user expected. The end-user rather than the system developer conduct this test most software developers as a process called Alpha and Beta Testing to uncover that only the end user seems able to find. The compilation of the entire project is based on the full satisfaction of the end users. In the project, validation testing is made in various forms.
successful system and giving the users confidence that the new system is workable and effective. Implementation of a modified application to replace an existing one. This type of conversation is relatively easy to handle, provide there are no major changes in the system. Each program is tested individually at the time of development using the data and has verified that this program linked together in the way specified in the programs specification, the computer system and its environment is tested to the satisfaction of the user. The system that has been developed is accepted and proved to be satisfactory for the user. And so the system is going to be implemented very soon. A simple operating procedure is included so that the user can understand the different functions clearly and quickly. Initially as a first step the executable form of the application is to be created and loaded in the common server machine which is accessible to the entire user and the server is to be connected to a network. The final stage is to document the entire system which provides components and the operating procedures of the system. Implementation is the stage of the project when the theoretical design is turned out into a working system. Thus it can be considered to be the most critical stage
Defence mechanism and prevention of attack for cross-site scripting forgery________ 35 in achieving a successful new system and in giving the user, confidence that the new system will work and be effective. The implementation stage involves careful planning, investigation of the existing system and its constraints on implementation, designing of methods to achieve changeover and evaluation of changeover methods. Implementation is the process of converting a new system design into operation. It is the phase that focuses on user training, site preparation and file conversion for installing a candidate system. The important factor that should be considered here is that the conversion should not disrupt the functioning of the organization.
7.2 MAINTENANCE
The objectives of this maintenance work are to make sure that the system gets into work all time without any bug. Provision must be for environmental changes which may affect the computer or software system. This is called the maintenance of the system. Nowadays there is the rapid change in the software world. Due to this rapid change, the system should be capable of adapting these changes. In our project the process can be added without affecting other parts of the system. Maintenance plays a vital role. The system liable to accept any modification after its implementation. This system has been designed to favour all new changes. Doing this will not affect the systems performance or its accuracy.
9.2.1Testing Strategies:
Defence mechanism and prevention of attack for cross-site scripting forgery________ 36 A number of software testing strategies have been proposed in the literature. All provide the software developer with a template for testing and all have the following generic characteristics: Testing begins at the component level and works outward toward the integration of the entire computer-based system. Different testing techniques are appropriate at different points in time. The developer of the software conducts testing and for large projects, independent test group. Testing and debugging are different activities, but debugging must be accommodated in any testing strategy.
8.1 CONCLUSION
In a cross site request forgery (XSRF) attack, the trust of a web application in its authenticated users is exploited, allowing an attacker to make arbitrary HTTP requests in the victims name. Unfortunately, current XSRF mitigation techniques have shortcomings that limit their general applicability. To address this problem, this paper presents a solution that provides a completely automatic protection from XSRF attacks. Our approach is based on a server-side proxy that detects and prevents XSRF attacks in a way that is transparent to users as well as to the web application itself. We have successfully used our prototype to secure a number of popular open-source web applications that were vulnerable to XSRF. Our experimental results demonstrate that the solution is viable, and that we can secure existing web applications without adversely affecting their behavior. Currently, XSRF attacks are relatively unknown to both web developers and attackers that are on the hunt for easy targets. However, we expect the attention paid to this class of attacks to soon reach that of more traditional web security problems (such as XSS or SQL injections), and we hope that our solution will prove useful in protecting vulnerable web applications.
CHAPTER 9 APPENDICES
9.1 SAMPLE SOURCE CODE
import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Enumeration; import javax.swing.text.AttributeSet; import javax.swing.text.MutableAttributeSet; import javax.swing.text.html.HTML; import javax.swing.text.html.HTMLEditorKit; import javax.swing.*; public class MainClass { static ReportAttributes ra=null; //static String filename="http://localhost:8080/SEARCH/search.html"; // public static void main(String[] args) { public void check(String filename) { ParserGetter kit = new ParserGetter(); HTMLEditorKit.Parser parser = kit.getParser();
Defence mechanism and prevention of attack for cross-site scripting forgery________ 40 HTMLEditorKit.ParserCallback callback = new ReportAttributes(); ra=new ReportAttributes(); System.out.println("kkk");
try { URL u = new URL(filename); InputStream in = u.openStream(); InputStreamReader r = new InputStreamReader(in); parser.parse(r, callback, false); } catch (IOException e) { System.err.println(e); } } } class ReportAttributes extends HTMLEditorKit.ParserCallback { public String heightstr="",widthstr=""; public void handleStartTag(HTML.Tag tag, MutableAttributeSet attributes, int position) { this.listAttributes(attributes); } private void listAttributes(AttributeSet attributes) { Enumeration e = attributes.getAttributeNames(); while (e.hasMoreElements()) { Object name = e.nextElement();
Defence mechanism and prevention of attack for cross-site scripting forgery________ 41 Object value = attributes.getAttribute(name); if (!attributes.containsAttribute(name.toString(), value)) { //System.out.println("containsAttribute() fails"); } if (!attributes.isDefined(name.toString())) { //System.out.println("isDefined() fails"); } //System.out.println("kkkk"+name + "=" +"kkooo"+value); if((name.toString()).equals("height")) { if(value.equals("0")) { JOptionPane.showMessageDialog(null,"Malicious Webpage"); }
} } }
Defence mechanism and prevention of attack for cross-site scripting forgery________ 42 public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet attributes, int position) { this.listAttributes(attributes); }
} class ParserGetter extends HTMLEditorKit { public HTMLEditorKit.Parser getParser() { return super.getParser(); } } import javax.swing.text.html.*; public class HTMLParse extends HTMLEditorKit { public HTMLEditorKit.Parser getParser() { return super.getParser(); } }
Defence mechanism and prevention of attack for cross-site scripting forgery________ 43 public class CheckLinks extends javax.swing.JFrame implements Runnable,ISpiderReportable {
public CheckLinks() { try { setTitle("Cross-Site Scripting"); System.out.println("kkkk"); getContentPane().setLayout(null); setSize(405,288); setVisible(false); label1.setText("Enter a URL:"); getContentPane().add(label1); label1.setBounds(12,12,84,12); begin.setText("Enter"); begin.setActionCommand("Begin"); getContentPane().add(begin); begin.setBounds(12,36,84,24); getContentPane().add(url); url.setBounds(108,36,288,24); errorScroll.setAutoscrolls(true); errorScroll.setHorizontalScrollBarPolicy(javax.swing. ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS); errorScroll.setVerticalScrollBarPolicy(javax.swing. ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); errorScroll.setOpaque(true); getContentPane().add(errorScroll); errorScroll.setBounds(12,120,384,156);
Defence mechanism and prevention of attack for cross-site scripting forgery________ 44 errors.setEditable(false); errorScroll.getViewport().add(errors); errors.setBounds(0,0,366,138); current.setText("Current Page: "); getContentPane().add(current); current.setBounds(12,72,400,12); goodLinksLabel.setText("Status : "); getContentPane().add(goodLinksLabel); goodLinksLabel.setBounds(12,96,192,12); // badLinksLabel.setText("Bad Links: 0"); //getContentPane().add(badLinksLabel); badLinksLabel.setBounds(216,96,96,12); setDefaultCloseOperation(EXIT_ON_CLOSE); SymAction lSymAction = new SymAction(); begin.addActionListener(lSymAction); } catch(Exception ex) { ex.printStackTrace(); System.out.println(ex); } } public void addNotify(){ Dimension size = getSize(); super.addNotify(); if ( frameSizeAdjusted )
Defence mechanism and prevention of attack for cross-site scripting forgery________ 45 return; frameSizeAdjusted = true;
Insets insets = getInsets(); javax.swing.JMenuBar menuBar = getRootPane().getJMenuBar(); int menuBarHeight = 0; if ( menuBar != null ) menuBarHeight = menuBar.getPreferredSize().height; setSize(insets.left + insets.right + size.width, insets.top + insets.bottom + size.height + menuBarHeight); }
Defence mechanism and prevention of attack for cross-site scripting forgery________ 46 javax.swing.JLabel current = new javax.swing.JLabel(); static javax.swing.JLabel goodLinksLabel = new javax.swing.JLabel(); javax.swing.JLabel badLinksLabel = new javax.swing.JLabel(); protected Thread backgroundThread;
class SymAction implements java.awt.event.ActionListener { public void actionPerformed(java.awt.event.ActionEvent event) { Object object = event.getSource(); if ( object == begin ) begin_actionPerformed(event); } }
Defence mechanism and prevention of attack for cross-site scripting forgery________ 47 { if ( backgroundThread==null ) { begin.setLabel("Cancel"); backgroundThread = new Thread(this); backgroundThread.start(); goodLinksCount=0; badLinksCount=0; current.setText("Current Page: " + url.getText()); //goodLinksLabel.setText("Good Links: " + goodLinksCount); } else { spider.cancel(); } }
public void run() { try { errors.setText(""); spider = new Spider(this); spider.clear(); base = new URL(url.getText()); spider.addURL(base); spider.begin(); Runnable doLater = new Runnable() { public void run() { begin.setText("Enter"); }
Defence mechanism and prevention of attack for cross-site scripting forgery________ 48 }; SwingUtilities.invokeLater(doLater); backgroundThread=null; } catch ( MalformedURLException e ) { UpdateErrors err = new UpdateErrors(); err.msg = "Bad address."; SwingUtilities.invokeLater(err); } }
public boolean spiderFoundURL(URL base,URL url) { UpdateCurrentStats cs = new UpdateCurrentStats(); cs.msg = url.toString(); SwingUtilities.invokeLater(cs); if ( !checkLink(url) ) { UpdateErrors err = new UpdateErrors(); err.msg = url+"(on page " + base + ")\n"; SwingUtilities.invokeLater(err); badLinksCount++; return false; } goodLinksCount++; if ( !url.getHost().equalsIgnoreCase(base.getHost()) ) return false; else
Defence mechanism and prevention of attack for cross-site scripting forgery________ 49 return true; }
protected boolean checkLink(URL url) { try { URLConnection connection = url.openConnection(); connection.connect(); return true; } catch ( IOException e ) { return false; } } public static void setErrorStatus(String error) { //if(loc == 0) errors.append(error+"\n"); /*else errors.insert(error, loc);*/ } public static void setStatusLabel(String sts) { goodLinksLabel.setText(sts);
class UpdateErrors implements Runnable { public String msg; public void run() { errors.append(msg); } }
class UpdateCurrentStats implements Runnable { public String msg; public void run() { current.setText("Current Page: " + url.getText()); goodLinksLabel.setText("Good Links: " + goodLinksCount); badLinksLabel.setText("Bad Links: " + badLinksCount); } } }
Defence mechanism and prevention of attack for cross-site scripting forgery________ 51 import java.util.*; import java.net.*; import java.io.*; import javax.swing.text.*; import javax.swing.text.html.*;
public class Spider { String pageCnt = ""; protected Collection workloadError = new ArrayList(3);
public void addURL(URL url) { if ( getWorkloadWaiting().contains(url) ) return; if ( getWorkloadError().contains(url) ) return; if ( getWorkloadProcessed().contains(url) ) return; log("Adding to workload: " + url ); getWorkloadWaiting().add(url); }
public void processURL(URL url) { try { log("Processing: " + url ); URLConnection connection = url.openConnection(); if ( (connection.getContentType()!=null) && !connection.getContentType().toLowerCase().startsWith("text/") ) { getWorkloadWaiting().remove(url); getWorkloadProcessed().add(url); log("Not processing because content type is: " + connection.getContentType() ); return; }
Defence mechanism and prevention of attack for cross-site scripting forgery________ 54 InputStream is = connection.getInputStream(); Reader r = new InputStreamReader(is); int i = 0; while((i = is.read()) != -1) pageCnt += (char)i; HTMLEditorKit.Parser parse = new HTMLParse().getParser(); parse.parse(r,new Parser(url),true); } catch ( IOException e ) { getWorkloadWaiting().remove(url); getWorkloadError().add(url); log("Error: " + url ); report.spiderURLError(url); return; } getWorkloadWaiting().remove(url); getWorkloadProcessed().add(url); log("Complete: " + url ); MainClass m=new MainClass(); CheckLinks.setErrorStatus("Removing Comments\n"); String cntwocomment = removeComments(pageCnt); CheckLinks.setErrorStatus("Processing Script Contents\n"); int len = 6, i = 0; boolean find1 = false, find2 = false, find3 = false, find4 = false; int start = 0, end = 0, start1 = 0, end1 = 0; String scriptCnt = ""; boolean scriptstatus = true, iframestatus = true;
Defence mechanism and prevention of attack for cross-site scripting forgery________ 55 String scriptContent = ""; while(i < cntwocomment.length()-8) { if(find1) { String temp = cntwocomment.substring(i, i+7); if(temp.equalsIgnoreCase("/script")) { find2 = true; end = i+8; } } else { String temp = cntwocomment.substring(i, i+7); if(temp.equalsIgnoreCase("<script")) { find1 = true; start = i; } }
if(find3) { String temp = cntwocomment.substring(i, i+7); if(temp.equalsIgnoreCase("/iframe")) { find4 = true; end1 = i+8; System.out.println(temp); } } else { String temp = cntwocomment.substring(i, i+7); System.out.println(temp); if(temp.equalsIgnoreCase("<iframe")) { find3 = true;
Defence mechanism and prevention of attack for cross-site scripting forgery________ 56 start1 = i; System.out.println(temp); } }
if(find1 && find2) { scriptContent = cntwocomment.substring(start, end); //System.out.println("script : "+scriptContent); find1 = false; find2 = false; scriptstatus = new ScriptReader(scriptContent).scanScript(); if(!scriptstatus) break; } if(find3 && find4) { String iframeContent = cntwocomment.substring(start1, end1); find3 = false; find4 = false; iframestatus = new ScriptReader(iframeContent).scanIframe(); if(!scriptstatus) break; } i++; } CheckLinks.setErrorStatus("Processing completed"); if(scriptstatus && iframestatus) {
Defence mechanism and prevention of attack for cross-site scripting forgery________ 57 CheckLinks.setStatusLabel("Status : Verified"); try { Runtime r=Runtime.getRuntime(); r.exec("cmd /c start "+url); } catch(Exception ex) { System.out.println(ex); } } else { CheckLinks.setStatusLabel("Status : Cross-site Scripting"); System.out.println("Cross-site Scripting"); } }
public void begin() { cancel = false; while ( !getWorkloadWaiting().isEmpty() && !cancel ) { Object list[] = getWorkloadWaiting().toArray(); for ( int i=0;(i<list.length)&&!cancel;i++ ) processURL((URL)list[i]); } }
Defence mechanism and prevention of attack for cross-site scripting forgery________ 58 protected URL base; public Parser(URL base) { this.base = base; } public void handleSimpleTag(HTML.Tag t, MutableAttributeSet a,int pos) { String href = (String)a.getAttribute(HTML.Attribute.HREF); if( (href==null) && (t==HTML.Tag.FRAME) ) href = (String)a.getAttribute(HTML.Attribute.SRC); if ( href==null ) return; int i = href.indexOf('#'); if ( i!=-1 ) href = href.substring(0,i); if ( href.toLowerCase().startsWith("mailto:") ) { report.spiderFoundEMail(href); return; } handleLink(base,href); } public void handleStartTag(HTML.Tag t,
Defence mechanism and prevention of attack for cross-site scripting forgery________ 59 MutableAttributeSet a,int pos) { handleSimpleTag(t,a,pos); } protected void handleLink(URL base,String str) { try { URL url = new URL(base,str); if ( report.spiderFoundURL(base,url) ) addURL(url); } catch ( MalformedURLException e ) { log("Found malformed URL: " + str ); } } }
public String removeComments(String content) { int i = 0; boolean find1 = false, find2 = false; int start = 0, end = 0; String Cntwocomment = ""; while(i < content.length()-4) { if(find1) { String temp = content.substring(i, i+3);
Defence mechanism and prevention of attack for cross-site scripting forgery________ 60 if(temp.equalsIgnoreCase("-->") temp.equalsIgnoreCase("--%>")) { find2 = true; end = i+3; i += 3; } } else { String temp = content.substring(i, i+4); if(temp.equalsIgnoreCase("<!--") temp.equalsIgnoreCase("<%--")) { find1 = true; start = i; } else { Cntwocomment += content.charAt(i); } } if(find1 && find2) { System.out.println("commant : "+content.substring(start, end)); find1 = false; find2 = false; } i++; } return Cntwocomment; } || ||
Defence mechanism and prevention of attack for cross-site scripting forgery________ 61 { System.out.println( (new Date()) + ":" + entry ); } }
import java.net.*; interface ISpiderReportable { public boolean spiderFoundURL(URL base,URL url); public void spiderURLError(URL url); public void spiderFoundEMail(String email); }
import java.util.regex.*; public class ScriptReader { Pattern p1, p2, p3, p4, p5, p6, p7, p8, p9,p10, p11, p12, p13, p14,p15,p16,p17; String script = "", encScript = ""; boolean showStatus = true, enc = false; public ScriptReader(String script) { this.script = script; p1 = Pattern.compile("script"); p2 = Pattern.compile("iframe"); p3 = Pattern.compile("width"); p4 = Pattern.compile("height"); p5 = Pattern.compile("style"); p6 = Pattern.compile("width=0"); p7 = Pattern.compile("height=0");
Defence mechanism and prevention of attack for cross-site scripting forgery________ 62 p8 = Pattern.compile("display:none;"); p9 = Pattern.compile("width=\"0\""); p10 = Pattern.compile("height=\"0\""); p11 = Pattern.compile("\"display:none\""); //p12 = Pattern.compile("@&%mkmd#@~ZQAA"); //p13 = Pattern.compile("#@ZQAAKmsYRSDb"); //p14 = Pattern.compile("language=\"JScript\""); //p15 = Pattern.compile("language=\"JavaScript\""); p14 = Pattern.compile("language=\"jscript.encode\""); p15 = Pattern.compile("language=\"javascript.encode\""); } public boolean scanScript() { boolean status = true; //CheckLinks.setErrorStatus("Processing Script Content\n"); Matcher m1 = p1.matcher(script); int loc = 0; if(m1.find()) { String lower = script.toLowerCase(); Matcher m14 = p14.matcher(lower); Matcher m15 = p15.matcher(lower); String temp = script.substring(script.indexOf(">")+1); encScript = temp.substring(0, temp.lastIndexOf("<")); System.out.println("DC : "+encScript); System.out.println("DC L : "+encScript.length()); if(m14.find() || m15.find()) {
Defence mechanism and prevention of attack for cross-site scripting forgery________ 63 script ScriptDecoder.decodeString(encScript.replace("\n", "").trim()); enc = true; } System.out.println("Script "+script); script = script.toLowerCase(); System.out.println("Processing Script"); Matcher m2 = p2.matcher(script); if(m2.find()) { System.out.println("Processing IFrame"); Matcher m3 = p3.matcher(script); if(m3.find()) { Matcher m6 = p6.matcher(script); Matcher m9 = p9.matcher(script); if(m6.find() || m9.find()) { System.out.println("Width Zero"); status = false; if(showStatus) { if(enc) showScript("Encoded Content : \n"+encScript+"\n"); showScript("Script \n"+script+"\n"); showStatus = false; } CheckLinks.setErrorStatus("Width Property is Zero"); } } else { Scource : Property is =
Defence mechanism and prevention of attack for cross-site scripting forgery________ 64 System.out.println("There is No Width Property"); } Matcher m4 = p4.matcher(script); if(m4.find()) { Matcher m7 = p7.matcher(script); Matcher m10 = p10.matcher(script); if(m7.find() || m10.find()) { System.out.println("Height Zero"); status = false; if(showStatus) { if(enc) showScript("Encoded Content : \n"+encScript+"\n"); showScript("Script \n"+script+"\n"); showStatus = false; } CheckLinks.setErrorStatus("Hight Property is Zero"); } } else { System.out.println("There is No Height Property"); } Matcher m5 = p5.matcher(script); if(m5.find()) { Matcher m8 = p8.matcher(script); Matcher m11 = p11.matcher(script); if(m8.find() || m11.find()) { Scource : Property is
Defence mechanism and prevention of attack for cross-site scripting forgery________ 65 System.out.println("Display None"); status = false; if(showStatus) { if(enc) showScript("Encoded Content : \n"+encScript+"\n"); showScript("Script \n"+script+"\n"); showStatus = false; } CheckLinks.setErrorStatus("Display Property is None"); } } else { System.out.println("There is No Display Property"); } } } else { System.out.println("No Script"); } return status; } Scource : Property is
Defence mechanism and prevention of attack for cross-site scripting forgery________ 66 public boolean scanIframe() { boolean status = true; System.out.println("IFrame "+script); script = script.toLowerCase(); System.out.println("Processing Script"); Matcher m2 = p2.matcher(script); if(m2.find()) { System.out.println("Processing IFrame"); Matcher m3 = p3.matcher(script); if(m3.find()) { Matcher m6 = p6.matcher(script); Matcher m9 = p9.matcher(script); if(m6.find() || m9.find()) { System.out.println("Width Property is Zero"); status = false; if(showStatus) { showScript("IFrame \n"+script+"\n"); showStatus = false; } CheckLinks.setErrorStatus("Width Zero"); } } else { System.out.println("There is No Width Property"); } Matcher m4 = p4.matcher(script); if(m4.find()) { Property is Scource :
Defence mechanism and prevention of attack for cross-site scripting forgery________ 67 Matcher m7 = p7.matcher(script); Matcher m10 = p10.matcher(script); if(m7.find() || m10.find()) { System.out.println("Height Property is Zero"); status = false; if(showStatus) { showScript("IFrame \n"+script+"\n"); showStatus = false; } CheckLinks.setErrorStatus("Hight Zero"); } } else { System.out.println("There is No Height Property"); } Matcher m5 = p5.matcher(script); if(m5.find()) { Matcher m8 = p8.matcher(script); Matcher m11 = p11.matcher(script); if(m8.find() || m11.find()) { System.out.println("Display Property is None"); status = false; if(showStatus) { showScript("IFrame \n"+script+"\n"); showStatus = false; } CheckLinks.setErrorStatus("Display None"); } Property is Scource : Property is Scource :
Defence mechanism and prevention of attack for cross-site scripting forgery________ 68 } else { System.out.println("There is No Display Property"); } } return status; } /*public static void main(String[] args) { String script1 = "<script language=\"javascript\"> <iframe width=\"0\" height=\"0\"><//script>"; String script2 = "<script language=\"javascript\"> <iframe width=\"100\" height=\"100\" style=\"display:none;\"><//script>"; String script3 = "<script language=\"JavaScript.Encode\">ZG9jdW1lbnQud3JpdGVsbiAoIjxJZnJhbWUiIHNyYz 1odHRwOi8vd3d3LmhhY2tlcmV4YW1wbGUuY24gd2lkdGg9MCBoZWlnaHQ9MD48 Ly9pZnJhbWU+KTs=<//script>"; new ScriptReader(script1).scanScript(); new ScriptReader(script2).scanScript(); new ScriptReader(script3).scanScript(); }*/ }
Defence mechanism and prevention of attack for cross-site scripting forgery________ 69 public class ScriptEncoder { public static char[] public static byte[] map1 = new char[64]; map2 = new byte[128];
public ScriptEncoder() { } static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; }
static { for (int i=0; i<map2.length; i++) map2[i] = -1; for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; } // Encodes a string into Base64 format. public static String encodeString (String s) {
Defence mechanism and prevention of attack for cross-site scripting forgery________ 70 return new String(encode(s.getBytes())); } public static char[] encode (byte[] in) { return encode(in,in.length); }
public static char[] encode (byte[] in, int iLen) { int oDataLen = (iLen*4+2)/3; padding int oLen = ((iLen+2)/3)*4; padding char[] out = new char[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++] & 0xff; int i1 = ip < iLen ? in[ip++] & 0xff : 0; int i2 = ip < iLen ? in[ip++] & 0xff : 0; int o0 = i0 >>> 2; int o1 = ((i0 & 3) << 4) | (i1 >>> 4); int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; op++; // output length including // output length without
Defence mechanism and prevention of attack for cross-site scripting forgery________ 71 out[op] = op < oDataLen ? map1[o3] : '='; op++; } return out; } public static void main(String a[]) { System.out.println(encodeString("document.writeln(\"<iframe height=0>\");")); } } width=0
public class ScriptDecoder { public static char[] public static byte[] map1 = new char[64]; map2 = new byte[128];
public ScriptDecoder() { } static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; }
static { for (int i=0; i<map2.length; i++) map2[i] = -1; for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; } // Decodes a string from Base64 format.
public static String decodeString (String s) { return new String(decode(s)); } public static byte[] decode (String s) { return decode(s.toCharArray()); } public static byte[] decode (char[] in) { int iLen = in.length; if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iLen-1] == '=') iLen--; int oLen = (iLen*3) / 4; byte[] out = new byte[oLen]; int ip = 0; int op = 0; while (ip < iLen) {
Defence mechanism and prevention of attack for cross-site scripting forgery________ 73 int i0 = in[ip++]; int i1 = in[ip++]; int i2 = ip < iLen ? in[ip++] : 'A'; int i3 = ip < iLen ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int o0 = ( b0 <<2) | (b1>>>4); int o1 = ((b1 & 0xf)<<4) | (b2>>>2); int o2 = ((b2 & 3)<<6) | b3; out[op++] = (byte)o0; if (op<oLen) out[op++] = (byte)o1; if (op<oLen) out[op++] = (byte)o2; } return out; }
public class ScriptDecoder { public static char[] public static byte[] map1 = new char[64]; map2 = new byte[128];
public ScriptDecoder() { } static { int i=0; for (char c='A'; c<='Z'; c++) map1[i++] = c; for (char c='a'; c<='z'; c++) map1[i++] = c; for (char c='0'; c<='9'; c++) map1[i++] = c; map1[i++] = '+'; map1[i++] = '/'; } static { for (int i=0; i<map2.length; i++) map2[i] = -1; for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; } // Decodes a string from Base64 format.
public static String decodeString (String s) { return new String(decode(s)); } public static byte[] decode (String s) { return decode(s.toCharArray());
Defence mechanism and prevention of attack for cross-site scripting forgery________ 75 } public static byte[] decode (char[] in) { int iLen = in.length; if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64 encoded input string is not a multiple of 4."); while (iLen > 0 && in[iLen-1] == '=') iLen--; int oLen = (iLen*3) / 4; byte[] out = new byte[oLen]; int ip = 0; int op = 0; while (ip < iLen) { int i0 = in[ip++]; int i1 = in[ip++]; int i2 = ip < iLen ? in[ip++] : 'A'; int i3 = ip < iLen ? in[ip++] : 'A'; if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int b0 = map2[i0]; int b1 = map2[i1]; int b2 = map2[i2]; int b3 = map2[i3]; if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) throw new IllegalArgumentException ("Illegal character in Base64 encoded data."); int o0 = ( b0 <<2) | (b1>>>4); int o1 = ((b1 & 0xf)<<4) | (b2>>>2); int o2 = ((b2 & 3)<<6) | b3;
Defence mechanism and prevention of attack for cross-site scripting forgery________ 76 out[op++] = (byte)o0; if (op<oLen) out[op++] = (byte)o1; if (op<oLen) out[op++] = (byte)o2; } return out; }
CHAPTER 10 REFERENCES
1] OWASP CSRFGuard Project, Accessed from http://www.owasp.org (May 2010). [2] A. Barth, C. Jackson, and J. Mitchell, Robust Defenses for Cross-Site Request Forgery, Proc. of the 15th ACM Conference on Computer and Communications Security, Alexandria, Virginia . [3] W. Maes, T. Heyman, L. Desmet, and W. Joosen, Browser Protection against CrossSite Request Forgery, In Proc. Of the Workshop on Secure Execution of Untrusted Code, Chicago, USA .