Attackers Vs Programmers


Published on

Code Review Methodology

1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Attackers Vs Programmers

  1. 1. ATTACKERS Vs PROGRAMMERS My paper explains about the behavior of the attackers and Programmers in java web applications. Generally both of them don’t know their way of work in terms of attacks and mitigation of web application. This paper explains the behavior of the vulnerabilities attacks and remediation. Common web application vulnerabilities are Cross Site Scriptings, lack of Input Validation, SQL Injection, Command Injection, Un protected Sessions, Error Handlings, Un secured Cryptography. Generally Programmers made the code on the basis of the business requirements and security will come later in the picture. My paper is focus towards the security area that the Programmers and Attackers get familiar with each other. Many website published various attacks and various coding standards of the vulnerabilities in web applications like XSS, SQL injections, etc. This paper gives an introduction of security code review inspections, and provides details about web application security vulnerabilities identification in the source code. This paper illustrates the specific locations of code flows to be checked to identify web application vulnerabilities. 1. Cross Site Scripting Cross Site Scripting (XSS) is an attack which can be executed on the web browser through the input fields with the malicious scripts. Generally Programmer prepares a white list and black list inputs to mitigate this issue or rely on web server validators. How Attackers attack: If there is lack of input validation, then the web browser behaves like this:
  2. 2. Vulnerable Code: The following Servlet code segment queries a database for an employee with a given ID and prints the corresponding employee’s name. String query = "select * from emp where id=?"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setString(1, eid); ResultSet rs = stmt.executeQuery(); if (rs != null) {; String name = rs.getString("name"); out.println("Employee Name: " + name); } An attacker can able to execute his own scripts on the field of employee name. Programmer: What kind of actions required from the Programmer? Reliable on the white list and black list inputs or web server validator are not the best way to mitigate this issue. Attackers have various techniques who can bypass the above validations. HTML and URL encoding are the best solutions to mitigate these issues. Below code include input validation and output encoding to prevent XSS.
  3. 3. String query = "select * from emp where id=?"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setString(1, eid); ResultSet rs = stmt.executeQuery(); if (rs != null) {; String name = rs.getString("name"); if (!NAME_REGEX.matcher(name).matches()) { throw new ValidationException("invalid emp name"); } ... out.println("Employee Name: "+URLEncoder.encode(name, "UTF8")); } So the Programmers have to be careful about his source code that the proper encoding mechanism has been implemented. Don't use StringEscapeUtils.escapeJavaScript() and hope to be safe from XSS in the JavaScript context. Use something more robust (and implemented correctly) like the OWASP Reform project or the OWASP ESAPI. 2. HTTP Response Splitting HTTP response splitting is similar to cross-site scripting, but an HTTP response splitting vulnerability allows an attacker to write data into an HTTP header. What Attackers can do : An attacker passes malicious data to a vulnerable application, and the application includes the data in an HTTP response header. How: If an attacker submits a malicious string, such as robinrnrnHTTP/1.1 200 OKrn..., the HTTP response will be split into two responses of the following form: HTTP/1.1 200 OK Set-Cookie: author=robin HTTP/1.1 200 OK Many Web browsers and Web proxies will mishandle a response that looks like this. An attacker might be able to use the vulnerability to do the following: • Provide malicious content to the victim browser. This is similar to a reflected cross-site scripting attack.
  4. 4. • Confuse a Web proxy. This can result in the Web proxy sending the second HTTP response to a different user, or in the Web proxy sending a different user’s data to the attacker. Programmers: HTTP headers rarely require a great variety of characters, so a white list is almost always feasible. If you must blacklist, the CR and LF characters are at the heart of an HTTP response splitting attack, but other characters, such as the colon (:) and equals sign (=), have special meaning in response headers as well. 3. Improper Error/ Exception Handling Improper error messages can reveal information about an application which may helps an attacker in exploiting the application. When an exception is thrown and not caught, the process has given up an opportunity to decide if a given failure or event is worth a change in execution. Attackers: Attackers can be able to submit or upload malicious data on the application server. When the application server un handle the malicious request it throws out the exception message to the attackers like source code, database connection etc. How:
  5. 5. When there is no validation for the malicious request it throws out the exception like: Improper error handling vulnerable code: try { } catch (ArrayIndexOutOfBoundsException e) { System.out.println ("exception: " + e.getMessage ()); e.printStackTrace (); } Programmer: On web.xml should include entries similar to the following: <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/error.jsp</location> </error-page> <error-page> <error-code>404</error-code> <location>/error.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/error.jsp</location> </error-page> 4. SQL Injections
  6. 6. A SQL Injection is an attack consists of insertion of a SQL query via the input data from the client to the application. Forming a SQL query by concatenating strings leaves this code open to a SQL injection attack. Vulnerable Code: String userName = ctx.getAuthenticatedUserName(); String itemName = request.getParameter("itemName"); String query = "SELECT * FROM items WHERE owner = '" + userName + "' AND itemname = '" + itemName + "'"; Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query);
  7. 7. A programmer who wrote the code intended to form database queries that look like this: SELECT * FROM items WHERE owner = <userName> AND itemname = <itemName>; Many database servers, including Microsoft SQL Server, allow multiple SQL statements separated by semicolons to be executed at once. How attackers can do: How vulnerable application behave: Programmers: A programmer might accept characters only from a white list of safe values or identify and escape a blacklist of potentially malicious values. As always, white listing is an effective means of enforcing strict input validation rules, but parameterized SQL statements require less maintenance and can offer more guarantees with respect to security. Again, blacklisting is riddled with loopholes that make it ineffective at preventing SQL injection attacks. For example, attackers can: • Target fields that are not quoted • Find ways to bypass the need for certain escaped metacharacters
  8. 8. • Use stored procedures to hide the injected metacharacters Using a parameterized query helps to prevent SQL injection. String userName = ctx.getAuthenticatedUserName(); String itemName = request.getParameter("itemName"); String query = "SELECT * FROM items WHERE owner = ?" + " AND itemname = ?"; PreparedStatement stmt = conn.prepareStatement(query); stmt.setString(1, userName); stmt.setString(2, itemName); ResultSet rs = stmt.executeQuery(); 5. Use Post not GET For the sensitive applications the best practices recommend to use Post not Get. For all major browsers, GET is the default method for form submission, which means that every HTML form in an application needs to specify POST explicitly like this: <form method="POST" ... > Attackers: If the users perform sensitive actions or links through the GET request then the attackers can able to view the unauthorized data through the log file or Browser history. Vulnerable Code: public void doGet( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException { doPost( request, response ); } What Programmer can do: We recommend against this practice. Instead, send GET requests to an error page, like this: public void doGet( HttpServletRequest request, HttpServletResponse response )
  9. 9. throws ServletException, IOException { response.sendRedirect(ERROR_PAGE); }
  10. 10. 6. Session Management The most common method of tracking a customer through a web site is by assigning a unique session ID ? and having this information transmitted back to the web server with every request. Unfortunately, should an attacker guess or steal this session ID information, it is normally a trivial exercise to hijack and manipulate another user’s active session How Attackers can steal the session ID: a)Session ID information embedded in the URL, which is received by the application through HTTP GET requests when the client clicks on links. E.g.;session id= ER69045454 b) Session ID information stored within the fields of a form and submitted to the application. Typically the session ID information would be embedded within the form as a hidden field and submitted with the HTTP POST command. FORM METHOD=POST ACTION=?/cgi-bin/> <INPUT TYPE=?hidden? NAME=?sessionid? VALUE=?ER69045454?> <INPUT TYPE=?hidden? NAME=?allowed? VALUE=?true?> <INPUT TYPE=?submit? NAME=?Read News Article?> Session Hijacking As session ID’s are used to uniquely identify and track a web application user, any attacker who obtains this unique identifier is potentially able to submit the same information and impersonate someone else ? this class of attack is commonly referred to as Session Hijacking Programmers : Applications avoid or prevent common web attacks, such as replay, request forging, and man-in-the-middle. Session identifiers should be passed to the user in a secure manner such as not using HTTP GET with the session ID being placed in the query string. Such data (query string) is logged in web server logs. Cookie transport should be performed over a secure channel. Review the code in relation to cookie manipulation. Verify if the secure flag is set. This prevents the cookie being transported over a non-secure channel. String sessionid = request.getSession().getId(); response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; secure"); Session Timeout - Sessions should have a defined inactivity timeout and also in some cases a session hard-limit. The code review should examine such session settings. They may be defined in configuration files or in the code itself. Hard limits shall kill a session regardless of session activity.
  11. 11. Configure the session timeout in web.xml like this: <session-config> <!-- argument specifies timeout in minutes --> <session-timeout>30</session-timeout> </session-config> The log-out commands must do more that simply kill the browser. Review the code to verify that log-out commands invalidate the session on the server. Upon the logout request, be it a parameter or URL, one must review the code to ensure the session is invalidated. import*; import javax.servlet.*; import javax.servlet.http.*; import java.sql.*; public class doLogout extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException { res.setContentType("text/html"); HttpSession ses =req.getSession(); ses.removeValue("Login"); ses.removeValue("password"); ses.invalidate(); res.sendRedirect(""); } } The Session ID or Cookie issued to the client should not be easily predictable (don't use linear algorithms based on predictable variables such as the client IP address). The use of cryptographic algorithms with key length of 256 bits is encouraged (like AES).
  12. 12. 7. Command Injection If user input is allowed to specify system commands your program executes, attackers might be able to cause the system to carry out malicious commands on their behalf. Unauthorized command execution is called command injection Attackers: A command injection vulnerability in an administrative Web application. String btype = request.getParameter("backuptype"); String cmd = new String("cmd.exe /K "c:utilrmanDB.bat " + btype + "&&c:utlcleanup.bat"") Runtime.getRuntime().exec(cmd); When the shell is invoked, it will happily execute multiple commands separated by two ampersands. If an attacker passes a string of the form "&& del c:dbms*.*", the application will execute this command along with the others specified by the program. Programmers: This code uses a whitelist to prevent command injection. final static int MAXNAME = 50; final static String FILE_REGEX = "[a-zA-Z]{1,"+MAXNAME+"}"; // vanilla chars in prefix final static Pattern BACKUP_PATTERN = Pattern.compile(FILE_REGEX); public void validateBackupName(String backupname) { if(backupname == null || !BACKUP_PATTERN.matcher(backupname).matches()) { throw new ValidationException("illegal backupname"); } } ... String btype = validateBackupName(request.getParameter("backuptype")); String cmd = new String("cmd.exe /K "c:utilrmanDB.bat " + btype + "&&c:utlcleanup.bat"") Runtime.getRuntime().exec(cmd); 8. Path Manipulation If user input is allowed to include file system metacharacters such as a forward slash (/), backslash (), or period (.), an attacker might be able to specify an absolute path where a relative path is expected or traverse the file
  13. 13. system to an unintended location by moving up the directory tree. Unauthorized file system access of this type is called path manipulation. Attackers: A path manipulation vulnerability in a Web application. String rName = request.getParameter("reportName"); File rFile = new File("/usr/local/apfr/reports/" + rName); rFile.delete(); Programmers: This code uses a white list to prevent path manipulation. final static int MAXNAME = 50; final static int MAXSUFFIX = 5; final static String FILE_REGEX = "[a-zA-Z0-9]{1,"+MAXNAME+"}" // vanilla chars in prefix + ".?" // optional dot + "[a-zA-Z0-9]{0,"+MAXSUFFIX+"}"; // optional extension final static Pattern FILE_PATTERN = Pattern.compile(FILE_REGEX); public void validateFilename(String filename) { if (!FILE_PATTERN.matcher(filename).matches()) { throw new ValidationException("illegal filename"); } } 9. Open Redirects Phishing involves luring potential victims to an attacker-controlled Web site masquerading as a trustworthy site, such as a bank or e-commerce site, which many users are likely to recognize. Attackers: In this open redirect, an attacker can send a victim a link to a legitimate Web site, but clicking on the link will take the victim to a site specified by the attacker. String nextPage = request.getParameter("next"); if (nextPage.matches("[a-zA-Z0-9/:?&_+]+") { response.sendRedirect(nextPage); }
  14. 14. ... Programmers: A level of indirection allows the programmer to control where the redirect goes. String nextPage = pageLookup.get(request.getParameter("next")); response.sendRedirect(nextPage); Specifying the protocol and the host name limits the attacker’s ability to make use of a redirect. String nextPage = request.getParameter("next"); if (nextPage.matches("[a-zA-Z0-9/]+") { response.sendRedirect("" + nextPage); 10 : SECURE APPLICATION DEPLOYMENT One of the very critical task for the programmer is to secure the application deployment on application server. The WEB-INF directory tree contains web application classes, pre- compiled JSP files, server side libraries, session information and files such as web.xml and Attackers: If the WEB-INF un protected and unsecured then attackers can do better source code review of the target applications. This issue causes Directory Indexing and Path traversal attacks like Programmer: Tomcat web.xml to prevent directory indexing:
  15. 15. <servlet> <servlet-name>default</servlet-name> <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class> <init-param> <param-name>debug</param-name> <param-value>0</param-value> </init-param> <init-param> <param-name>listings</param-name> <param-value>false</param-value> </init-param> <init-param> <param-name>readonly</param-name> <param-value>true</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> Alternative: To stop directory indexing we place the following directive into the .htaccess file: IndexIgnore * .The * is a wildcard to prevent all files from being indexed. To protect the .htaccess file itself we place: <Files .htaccess> order allow,deny deny from all </Files>
  16. 16. Source code should not go into production directories. The compiled class files are all that is required in most cases. All source code should be removed and only the “executables” should remain. No development tools should be present in a production environment. For example a Java application should only need a JRE (Java Runtime Environment) and not a JDK (Java Development Kit) to function. Code Review Tools Some of the Code Review Tools for JAVA/J2EE which can be used for security 1) Escjava URL: 2) Hammurapi URL: 3) Jlint URL: 4) JavaPathFinder URL: 5) JavaPureCheck URL: 6) Checkstyle URL: 7) Pmd URL: 8) Findbugs URL: References :
  17. 17.