Security Code Review- Identifying Web Vulnerabilities



Similar documents
An Introduction to Application Security in J2EE Environments

What is Web Security? Motivation

3. Broken Account and Session Management. 4. Cross-Site Scripting (XSS) Flaws. Web browsers execute code sent from websites. Account Management

Where every interaction matters.

Passing PCI Compliance How to Address the Application Security Mandates

FINAL DoIT v.4 PAYMENT CARD INDUSTRY DATA SECURITY STANDARDS APPLICATION DEVELOPMENT AND MAINTENANCE PROCEDURES

Top Ten Web Application Vulnerabilities in J2EE. Vincent Partington and Eelco Klaver Xebia

Application Security and the SDLC. Dan Cornell Denim Group, Ltd.

Adobe Systems Incorporated

Thick Client Application Security

FINAL DoIT v.8 APPLICATION SECURITY PROCEDURE

Secure Web Application Coding Team Introductory Meeting December 1, :00 2:00PM Bits & Pieces Room, Sansom West Room 306 Agenda

Check list for web developers

Still Aren't Doing. Frank Kim

Application Security

Criteria for web application security check. Version

Last update: February 23, 2004

Web Application Security Assessment and Vulnerability Mitigation Tests

Is Drupal secure? A high-level perspective on web vulnerabilities, Drupal s solutions, and how to maintain site security

The Top Web Application Attacks: Are you vulnerable?

Simon Fraser University. Web Security. Dr. Abhijit Sen CMPT 470

How to break in. Tecniche avanzate di pen testing in ambito Web Application, Internal Network and Social Engineering

Web Application Security. Vulnerabilities, Weakness and Countermeasures. Massimo Cotelli CISSP. Secure

elearning for Secure Application Development

Creating Stronger, Safer, Web Facing Code. JPL IT Security Mary Rivera June 17, 2011

Top 10 Web Application Security Vulnerabilities - with focus on PHP

Cracking the Perimeter via Web Application Hacking. Zach Grace, CISSP, CEH January 17, Mega Conference

How I hacked PacketStorm ( )

Magento Security and Vulnerabilities. Roman Stepanov

External Vulnerability Assessment. -Technical Summary- ABC ORGANIZATION

(WAPT) Web Application Penetration Testing

Web applications. Web security: web basics. HTTP requests. URLs. GET request. Myrto Arapinis School of Informatics University of Edinburgh

WHITE PAPER. FortiWeb and the OWASP Top 10 Mitigating the most dangerous application security threats

Application Security and the SDLC. Dan Cornell Denim Group, Ltd.

Recommended readings. Lecture 11 - Securing Web. Applications. Security. Declarative Security

Web Application Guidelines

Sitefinity Security and Best Practices

OWASP Top Ten Tools and Tactics

The end. Carl Nettelblad

Web Application Security

Introduction to Web Application Security. Microsoft CSO Roundtable Houston, TX. September 13 th, 2006

Threat Modeling. Categorizing the nature and severity of system vulnerabilities. John B. Dickson, CISSP

Web application security

Out of the Fire - Adding Layers of Protection When Deploying Oracle EBS to the Internet

White Paper BMC Remedy Action Request System Security

1. Introduction. 2. Web Application. 3. Components. 4. Common Vulnerabilities. 5. Improving security in Web applications

Java Web Application Security

WEB SECURITY CONCERNS THAT WEB VULNERABILITY SCANNING CAN IDENTIFY

OWASP and OWASP Top 10 (2007 Update) OWASP. The OWASP Foundation. Dave Wichers. The OWASP Foundation. OWASP Conferences Chair

External Network & Web Application Assessment. For The XXX Group LLC October 2012

Application Security Testing. Erez Metula (CISSP), Founder Application Security Expert

Application Security Policy

CSE598i - Web 2.0 Security OWASP Top 10: The Ten Most Critical Web Application Security Vulnerabilities

Objectives. Security. Fixing Our JSTL Problem. Web Application Architecture. Web Security. A few lines of code can wreak more havoc than a bomb.

Chapter 1 Web Application (In)security 1

ArcGIS Server Security Threats & Best Practices David Cordes Michael Young

Certified Secure Web Application Secure Development Checklist

05.0 Application Development

JVA-122. Secure Java Web Development

Enterprise Application Security Workshop Series

Don t Get Burned! Are you Leaving your Critical Applications Defenseless?

SQL Injection January 23, 2013

OWASP Web Application Penetration Checklist. Version 1.1

ASP.NET MVC Secure Coding 4-Day hands on Course. Course Syllabus

Web Application Attacks and Countermeasures: Case Studies from Financial Systems

Hack Proof Your Webapps

Barracuda Web Site Firewall Ensures PCI DSS Compliance

Web Application Security. Srikumar Venugopal S2, Week 8, 2013

Members of the UK cyber security forum. Soteria Health Check. A Cyber Security Health Check for SAP systems

DFW INTERNATIONAL AIRPORT STANDARD OPERATING PROCEDURE (SOP)

Rational AppScan & Ounce Products

Ruby on Rails Secure Coding Recommendations

Essential IT Security Testing

Implementation of Web Application Security Solution using Open Source Gaurav Gupta 1, B. K. Murthy 2, P. N. Barwal 3

Nuclear Regulatory Commission Computer Security Office Computer Security Standard

Sichere Software- Entwicklung für Java Entwickler

Columbia University Web Security Standards and Practices. Objective and Scope

Application Security Vulnerabilities, Mitigation, and Consequences

Secure Web Applications. The front line defense

5 Simple Steps to Secure Database Development

Web Application Security

National Information Security Group The Top Web Application Hack Attacks. Danny Allan Director, Security Research

EVALUATING COMMERCIAL WEB APPLICATION SECURITY. By Aaron Parke

Web Application Security

The purpose of this report is to educate our prospective clients about capabilities of Hackers Locked.

Web Application Penetration Testing

Client vs. Server Implementations of Mitigating XSS Security Threats on Web Applications

Security features of ZK Framework

Web Application Firewall on SonicWALL SSL VPN

Security First Umbrella

Project 2: Web Security Pitfalls

Web Application Security Considerations

Using Foundstone CookieDigger to Analyze Web Session Management

Testing the OWASP Top 10 Security Issues

Visa U.S.A Cardholder Information Security Program (CISP) Payment Application Best Practices

Web Application Security Guidelines for Hosting Dynamic Websites on NIC Servers

The Weakest Link: Mitigating Web Application Vulnerabilities. webscurity White Paper. webscurity Inc. Minneapolis, Minnesota USA

Annual Web Application Security Report 2011

Introduction:... 1 Security in SDLC:... 2 Penetration Testing Methodology: Case Study... 3

Advanced Web Technology 10) XSS, CSRF and SQL Injection 2

Transcription:

Security Code Review- Identifying Web Vulnerabilities Kiran Maraju, CISSP, CEH, ITIL, SCJP Email: Kiran_maraju@yahoo.com 1

1.1.1 Abstract Security Code Review- Identifying Web Vulnerabilities This paper gives an introduction of security code review s, and provides details about web application security vulnerabilities identification in the source code. This paper gives the details of the s to perform on the Java/J2EE source code. This paper explains the process of identifying vulnerable code and remediation details. This paper illustrates the specific locations of code flows to be checked to identify web application vulnerabilities. 1.1.2 Introduction Security code review is to do code to identify vulnerabilities in the code. Vulnerabilities in the code exist due to the improper design or implementation in SDLC Process life cycle while developing the application. JAVA/J2EE Security Code Review List Input Validation Unreleased resource- Possible DOS J2EE Resource injection Configuration Access Control Authentication Access Control- Authorization Session Implementation Class level Object level Method level Variable/constan t level Inheritance Logging level Configuration level Sensitive data Exception Management Serialization Synchronization/Threa d level Cryptography EJB( Bean component ) Memory Reference Database access Computation/Numeric/Contro l Flow Network communication Web Container based I/O ( Input-Output ) File Level Native method Packaging level Inner classes/ reflection 1.1.3 Input Validation Flaws Input data requested from the client to server is not validated before being used by a web application. Attackers use the unvalidated input flaws to attack web server and backend components. Client-side validation like javascript and vbscript can be easily bypassed. Attackers use the vulnerable unvalidated input calls to be processed by server to execute the malicious content. Security code review involves identifying such unvalidated input calls and prevents those calls to be processed by the server. The following security code review checks are to be performed on tainted calls of servlet to identify unvalidated input from the attacker. Checking for Unvalidated sources of input from URL parameters in javax.servlet.httpservletrequest class getparameter () method 2

Checking for Unvalidated sources of input from Form fields in javax.servlet.httpservletrequest class getquerystring () method Checking for Unvalidated sources of input from Cookies javax.servlet.httpservletrequest class getcookies () method Checking for Unvalidated sources of input from HTTP headers javax.servlet.httpservletrequest class getheaders () method Through the application, an attacker enters malicious data through HTML form of the input fields of the application. The following code is vulnerable because the application accepts the values provided by the client in an iterator and responds back to client with the attacker s script which leads to reflected XSS vulnerability when the request.getparametenames method was called. The following sample code illustrates the unvalidated input vulnerability. Iterator iter = request.getparameternames (); While (iter.hasnext ()) { String paramname = (String) iter.next (); out.println (paramname +request.getparameter (paramname)); Remediation: Unvalidated input vulnerabilities can be prevented either by accepting the valid data and rejecting every thing else such as creating whitelist of the legitimate input characters or cleaning the input or reject the entire input. Rejecting the input: The following code is used as whitelist input validation by accepting specific character patterns and rejecting everything else as a part of servlet request call String input = request.getparameter ("input"); String characterpattern = "/ [^A-z]/"; If (! input. matches (characterpattern)) { out.println ( Invalid Input ); Cleaning the input: The following code is used as input validation by accepting the input and cleaning the malicious charcters by replacing with a space. String filterpattern="[<> {\\ [\\]; \\&]"; String inputstr = s.replaceall (filterpattern," "); 1.1.4 Cross-Site Scripting Vulnerability Cross-site scripting is an attack against web applications. It occurs when an web application accepts input containing malicious script through the application. This input is then sent as part of the response to the client as a reflected script which can lead to phishing attack, and the malicious script can be injected in the database as stored form so that whenever the page is accessed the injected script is executed like<script> alert (document. cookie)</script> The following sample code illustrates the XSS vulnerability. Iterator iter = request.getparameternames (); While (iter.hasnext ()) { String paramname = (String) iter.next (); out.println (paramname +request.getparameter (paramname)); To prevent XSS attacks, it is important to focus on the areas where application code returns output to a user (client). It is important to identify calls that require output to be encoded. The code of the application replaces the special characters before displaying the output is also one of the remediation to xss vulnerability. < < > > 3

( ( ) ) # # & & The approach to preventing XSS attacks is encoding. Server-side encoding is a function in which scripting tags in all dynamic content can be replaced with codes in a chosen character set. For example, < and > becomes < and >. The J2EE, Struts and webworks frameworks support encoding. 1.1.5 Buffer Overflow Flaws Lack of proper validation of input to the web components leads to buffer overflows. As Java is a Type safety language so overrunning the buffer is avoidable but Java based web applications can invoke native methods, libraries that are written in C and C++ using native calls. These native calls introduce vulnerabilities. To mitigate this vulnerability focus should be given on the areas where the Java Native Interface (JNI) API calls. All input passed to these calls should be validated to prevent an attacker from injecting malicious commands into the application. These JNI API calls should be reviewed to determine memory corruption does not take place which leads to buffer overflow. The following code illustrates JNI call in JSP which uses native TestDLL.dll using System.loadLibrary method. Class JNICALL { public native String test (String name); static {System.loadLibrary ("TestDLL") ; 1.1.6 SQL Injection Flaws SQL Queries and SQL Injection Attacks: SQL queries uses unvalidated user input as vulnerable script In an SQL injection attack, an attacker sends malicious input through the application interface like login page and these queries are executed in the backend database and attacker can gain control over a database or perform DOS attacks like Database shutdown. The following example illustrates JSP login form where the attacker can enter malicious commands like XP_cmdshell or *; OR 1=1 etc. String Uname = request.getparameter ( User ); String Pword =request.getparameter (Password ); String s = SELECT * FROM Table WHERE Username = + UName + AND Password = + Pword ; Statement stmt = connection.createstatement (); ResultSet rs = stmt.executequery (s); If (rs.next ()) { UID = rs.getint (1) User = rs.getstring (2) PrintWriter writer= response.getwriter (); writer.println ( User Name: + User); In the above example, the SQL query is created using the username and password transferred to the server without validating the input which is vulnerable to a SQL injection attack. To mitigate the risk of SQL injection is to use only stored procedures or parameterized database calls. Using prepared statement all the queries will be treated as a string but not commands to be executed by the database. The following code can be used as remediation for the above vulnerable code. String s = SELECT * FROM Table WHERE Username = + UName + AND Password = + Pword ; PreparedStatement stmt = connnection.preparestatement(s); stmt.setstring (1, UName); stmt.setstring (2, Pword); 4

ResultSet results = stmt.execute (); 1.1.7 Command Injection Attacks Executing System/Operating System Commands through the application are the sources of Command Injection Attacks. Java has the provision to execute system commands with the Runtime. Exec () method. Improper validation of the exec method arguments leads to vulnerability in the source code and attacker can pass malicious commands through the exec argument and gain control of the system. The following sample code illustrates the Command injection vulnerability. Class Execclass { public static void main (String args []) { Runtime rt = Runtime.getRuntime (); Process proc = rt.exec ("cmd.exe /C") ; 1.1.8 Improper Error/ Exception Handling Improper error messages can reveal information about an application which may helps an attacker in exploiting the application. With the improper error handling detailed internal error messages such as stack traces, database dumps, exception and error details are displayed to the end user. printstacktrace () method reveals the application details and technology usage. The remediation for the improper error handling vulnerability is to redirect all the error messages to log file like using Log4j.The calls should be reviewed to determine whether the appropriate details are displayed to the user. All errors, exceptions, should be logged in log file instead of displaying directly to the end user. If the application shows the attacker a stack trace, it gives technology details. This information will enable the attacker to target known vulnerabilities in these components. A web application must be configured with a default error page. Whenever an exception comes the events should be logged to the log file and default error page should be displayed to the end user. The following example shows the improper error handling vulnerability in the code try { catch (ArrayIndexOutOfBoundsException e) { System.out.println ("exception: " + e.getmessage ()); e.printstacktrace (); The web.xml should include at least the following entries: <Error-page> <exception-type>java.lang.throwable</exception-type> <location>/error.jsp</location> </error-page> <Error-page> <error-code>500</error-code> <location>/error.jsp</location> </error-page> 1.1.9 Improper Access control Improper assignment of restrictions on the privileges of authenticated users is allowed to leads to improper access control flaws. Attackers can exploit these flaws to access other users' accounts, view sensitive files, or use unauthorized functions. Improper Access Control vulnerabilities are identified by inspecting declarative and programmatic access control of J2EE applications. Declarative deployment descriptor specifies restriction of users, beans and methods at the deployment descriptor level. 5

Programmatic access control can query identity of the user to verify privileges of user or business logic in the Bean program. J2EE Access control Security covers both web-tier and EJB-tiers. At Web-tier, the access control is performed on resources which are represented in the form of an URL and at EJB-tier the access control can be applied on business methods of a bean in the application. Web-tier container enforces security policy specified in web.xml deployment descriptor and EJB container will enforce security policy specified in ejb-jar.xml deployment descriptor. Web-tier Declarative Access Control: Web-tier declarative access control applied in web.xml, by defining the security constraint applies to which application resources. The <url-pattern> element inside the <web-resource-collection> element provides restricted access to URL s. The <url-pattern> can refer to a directory, filename, or a <servlet-mapping>. The web-resource-collection element designates the access to which URLs should be restricted the auth-constraint element in web.xml specifies roles that should have access to the given URLs in url-pattern element. <Security-constraint> <Web-resource-collection> <web-resource-name>admin pages</web-resource-name> <url-pattern>/admin/*</url-pattern> </web-resource-collection> <Auth-constraint> <role-name>administrator</role-name> <role-name>normal user</role-name> </auth-constraint> </security-constraint> EJB-tier Declarative Access Control: EJB components provide declarative access control with the elements defined in the ejb-jar.xml deploy descriptor. Security Roles are defined in ejb-jar.xml <Enterprise-beans> <Security-role> <role-name>administrator</role-name> </security-role> <Security-role> <role-name> Normal user </role-name> </security-role> </enterprise-beans> EJB-Tier Programmatic access control: EJB-Tier Programmatic access control can be implemented in the code of the Bean logic of the application. It can be implemented with the iscallerinrole () and getcallerprincipal () methods. GetCallerPrincipal method is used to find out by whom the bean method is called and iscallerinrole method is used to check whether the caller of the application belongs to privileged role. Public interface javax.ejb.ejbcontext { Public java.security.principal getcallerprincipal (); Public Boolean iscallerinrole (String role); 1.1.10 Improper Authentication Flaws Improper assignment of account credentials and session tokens leads to Improper authentication vulnerability. Attackers can compromise passwords, session cookies and other tokens to bypass authentication. Vulnerabilities exist in the areas of weak credentials for authentication usage, unencrypted credentials and inefficient session usage. These vulnerabilities leads to privilege escalation attacks. These mechanisms must be reviewed to ensure proper implementation. Web-Tier Authentication: Authenticating users in web-tier application can be implemented in the following options. Form 6

Basic DIGEST Form-Based Authentication: Form based Authentication can be used in implementation by defining FORM in the <auth-method> element of web.xml. Using this application can use form login page login.jsp as shown in below. < <Login-config> <auth-method>form</auth-method> <Form-login-config> <form-login-page>login.jsp</form-login-page> </form-login-config> </login-config> BASIC Authentication: Form based Authentication can be used in implementation by defining FORM in the <auth-method> element of web.xml. Using this application can use authentication scheme provided by browser as shown in below. <Login-config> <auth-method>basic</auth-method> <realm-name>login</realm-name> </login-config> EJB-Tier Authentication: Two Possible Authentication Schemes in J2EE User credential information passed to web-tier and forwards them for authentication at EJB- tier User credential information passed to web-tier and web-tier authenticates the user at Web-tier. Webtier then forwards the identity of a user to the EJB-tier. 1.1.11 Improper Session Management Inspect the proper configurations for web.xml file for improper session management vulnerabilities. Inspect the Session Timeouts in the code. Session timeout can be checked in web.xml file. Using session. invalidate () to explicitly deactivate the sessions Session timeout can be using session.setmaxinactiveinterval () <Session-config> <Session-timeout> Time-in-minutes </session-timeout> </session-config> 1.1.12 Improper Cookie Management Improper Cookie management leads to cookie poisoning and privilege escalation vulnerabilities in the application. The following vulnerable code set the cookie as persistent and stored in the local system for one hour. Public class SetCookie extends HttpServlet { Public void doget () { Cookie cookie = new Cookie ("Session Cookie + value); cookie.setmaxage (3600); response.addcookie (cookie); The cookie values life time should be small time period and should be encrypted with efficient algorithms so that it can t be readable by anyone 7

1.1.13 Denial of Service Denial of service vulnerability in the code can be identified in the areas where resource consumption or the places where attacker can disrupt the services to the legitimate users. Unreleased Resources causes Denial of Service vulnerability. Denial of service attacks cause a Web application to fail by causing the application to shut down or by consuming the available resources. Identify the calls like System.exit() to prevent from DOS. The exit method forces termination of all threads in the JVM which leads to the DOS for the legitimate user. The following program fails to release the database connection resource Statement stmt = conn.createstatement (); ResultSet rs = stmt.executequery (); Stmt.close (); The remediation for the above example is to release resources in a finally block. Never rely on finalize () to reclaim resources. If, the statement objects in the above program won t be closed frequently then the database will run out of available resources and not be able to execute any more SQL queries. The above vulnerable program can be rewritten as follows: Statement stmt; Try { stmt = conn.createstatement (); stmt.executequery (); Finally { If (stmt! = null) { Try { stmt.close (); catch (SQLException e) { catch (SQLException e) { 1.1.14 Improper Configuration Flaws Proper server configuration is critical to a secure web application. The focus of the code review areas are from most common improper configuration vulnerabilities like Unpatched versions of the products, default files access, access to backup files, access to admin pages, using default accounts and passwords provided by vendor etc. Disabling the default servlet access: Url-pattern element in web.xml can disable the default servlet i.e. Invoking servlet. <url-pattern>/servlet/*</url-pattern> Disabling Unnecessary HTTP methods: Web-resource-collection in web.xml has http-method element that restricts the HTTP methods. The following shows the sample configuration of web.xml to disable PUT and DELETE HTTP methods. <Security-constraint> <Web-resource-collection> <web-resource-name>disallowed Location</web-resource-name> <url-pattern>/*</url-pattern> <http-method>put</http-method> <http-method>delete</http-method> </web-resource-collection> </security-constraint> Restricting access to specific directory: Web-resource-collection in web.xml has an element to restrict access of the clients to specific directories. The following web.xml configuration shows data in the sensitive directory of the Web application should be protected. 8

<Security-constraint> <Web-resource-collection> <web-resource-name>sensitive</web-resource-name> <url-pattern>/sensitive/*</url-pattern> </web-resource-collection> </security-constraint> 1.1.15 Transport Level Flaws One of the element in deployment descriptor web.xml indicates which transport-level protections should be used when accessing the resources. Confidential invokes the use of SSL. For example, the following configuration shows the server to only permit HTTPS connections <Security-constraint> <User-data-constraint> <transport-guarantee>confidential</transport-guarantee> </user-data-constraint> </security-constraint> Insecure transmission of secrets: Plain text transmission of secrets is critical vulnerability. Transmission of sensitive data should be done through encryption. By using HTTPS, using SSL encryption is the solution to protect sensitive web traffic. 1.1.16 Code Review Tools Some of the Code Review Tools for JAVA/J2EE which can be used for security 1) Escjava URL: http://research.compaq.com/src/esc/download.html 2) Hammurapi URL: http://www.hammurapi.org/ 3) Jlint URL: http://www.willowriver.net/products/jlint.php 4) JavaPathFinder URL: http://javapathfinder.sourceforge.net/ 5) JavaPureCheck URL: http://java.sun.com/products/archive/100percent/4.1.1/index.html 6) Checkstyle URL: http://eclipse-cs.sourceforge.net/ 7) Pmd URL: http://sourceforge.net/projects/pmd 8) Findbugs URL: http://findbugs.sourceforge.net/ 1.1.17 References 1) http://www.owasp.org/documentation/topten.html ( www.owasp.org) 2) http://www.javapassion.com/j2ee/ejbsecurity_speakernoted.pdf 3) http://www.ouncelabs.com/audit/softwaresecurityassuranceframework.pdf 4) The Dirty Dozen: The Top Web Application Vulnerabilities and How to Hunt Them Down at the Source ( www.ouncelabs.com ) 5) Controlling Web Application Behavior with web.xml http://developer.java.sun.com/developer/books/javaserverpages/servlets_javaserver/servlets_java server05.pdf 6) Handling Java Web Application Input http://today.java.net/pub/a/today/2005/09/20/handling-web-app-input.html 8) http://www.owasp.org/index.php/cryptography 7) Configuring Security in Web Applications http://e-docs.bea.com/wls/docs70/webapp/security.html 8) web.xml Deployment Descriptor Elements 9

http://e-docs.bea.com/wls/docs61/webapp/web_xml.html 9) http://www.javapractices.com/topic86.cjp 10