Hacker Proofing Web Apps with the New Java EE 6

Uploaded on

Slides of the popular talk "Hacker Proofing Web Apps with the new Java EE 6" The talk was first showcased at the JavaOne, Oracle OpenWorld 2010. It was very well received by the audiences in the …

Slides of the popular talk "Hacker Proofing Web Apps with the new Java EE 6" The talk was first showcased at the JavaOne, Oracle OpenWorld 2010. It was very well received by the audiences in the conference. It is by the authors of the book "Secure Java: For Web Application Development"

More in: Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
    Be the first to like this
No Downloads


Total Views
On Slideshare
From Embeds
Number of Embeds



Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

    No notes for slide

  • we45 Solutions is an Information Security consulting company.

  • Abhay: Bangalore is known as the pub-city of India. There are probably more pubs here than there are people.
    Dr. Kumar: This talk evolved from a discussion we had in one of the many pubs in Bangalore. We were discussing the state of web security and web application security in general. Such nerdy behaviour is observed after a few drinks...
    Abhay: I had gone off on a tangent about a super-vulnerable web application I was testing and how the developers there seemed clueless about security
    Dr. Kumar: and I told him that my apps could not be hacked.
    Abhay: Which I found unbelievable. That naive confidence that he had in his app security skills was cute, but so wrong
    Dr. Kumar: So I challenged him. I told him that I would build an app
    Abhay: and I told him I would break it.
    Dr. Kumar: What do you mean by breaking an app?
    Abhay: By breaking an app, I mean that I will identify vulnerabilities and exploit them using proof-of-concept exploits for them....
    Dr. Kumar: That’s why we are here. To tell you what this is all about.

  • Abhay: Have any of you noticed that web apps have become the way of life all over the world today. We now have web apps that do everything. From booking our tickets, to scheduling our events and banking. This has resulted in a great deal of information stored, processed and transmitted by these web apps. Credit Card numbers, financial information, banking data and personal data are some examples of information that is stored, processed and transmitted by these web apps. Attackers always look for easier ways to steal valuable information and organizations that host these web applications are consistently making it easier for them to do so, because they deploy incredibly vulnerable web apps. According to studies, 70% of all web apps out there are vulnerable to attack. In my own experience with the web apps my company tests, we find 8 out of 10 web apps vulnerable to serious web application flaws.
  • Abhay: and its getting worse. Web 2.0 is the biggest thing that is happening today. Ajax, mashups, web services, JSON are some of the words you hear when you say web 2.0. I hear one word. Client side. I love the fact that a lot of business logic is moved to the client side now, because that makes applications easier to exploit. Thereby making my job a whole lot easier. Now, one would thing that developers are supposed to know all of this. that it seems rudimentary and simple. However, that is far from the truth. Developers and architects are largely unaware of the web application security practices. in fact according to a Gartner study 75% of web apps are vulnerable due to flawed coding.

    Dr. Kumar: You are making bold statements. But tell me something, how are you actually planning to break my app???
    Abhay: This is not the first time, I am breaking an app. Let me share some of my personal experiences on how easy it is to break apps.....
    Dr. Kumar: I have had some expertise with web application security. I will tell you three types of attacks and you tell me if you are able to do anything like this...
    Abhay: What are those?
    Dr. Kumar: Have you used Cross Site Scripting?
    Abhay: I love Cross Site Scripting. I have tons of Cross Site Scripting experience
    Dr. Kumar: What about SQL Injection?
    Abhay: SQL Injection is a great attack. Yes, I have injected SQL in several sites and have owned the database after that.....
    Dr. Kumar: What about Authentication and Authorization Bypass??
    Abhay: Oh yes, I love breaking Access Control. I have story for that as well.
    Dr. Kumar: Ok then, tell me your stories.....
  • Abhay: Before I delve into my hair-raising stories, let me tell you the consequences of a security breach. We all know that apps handle tons of information on a daily basis and a security breach can have serious consequences. Let us talk of some specifics. First of all, financial backlash is something that an organization suffers when it is hacked. Financial losses come from several areas, fines, loss of revenue, loss of customer faith - resulting in loss of revenue. Recently, a large credit card processor in the US was hit with a SQL injection attack, where over a 100 million credit cards were stolen from their databases. This cost the company over $32 million in losses, fines and fees. This is usually compounded with loss of reputation which precedes further financial losses.

    Dr. Kumar: Reputation - It takes 20 years to build a reputation and it takes 10 minutes to destroy it. Customers would think more than twice before offering your organization financial and personal information. Believe me

    Abhay: In the wake of several security breaches and high profile incidents, the government and governing bodies have realized that it is no longer a matter of comfort, but a matter of necessity to secure critical information assets. We have several security compliance requirements from the government, namely HIPAA - for Health Information, GLBA - for Financial Information, SB1386 - California Breach Security Act for Personal Information of users. We will discuss compliance at length in the next slide.

    Dr. Kumar: Hackers earlier, for the most part were individuals who did it for the fun of it or in some cases for individual personal gain. However, in the web2.0 world it has all changed. Large criminal rings and transnational criminal elements fund and support large scale hacking of financial data and personally sensitive information to fuel identity theft and financial theft. Hacking has taken an ugly turn.
  • Abhay:
    Compliance is one of the driving forces for Web Application Security. Some of the important Security Requirements are as follows:
    PCI-DSS: PCI-DSS is the Payment Card Industry Data Security Standard. This is a standard laid down by the card payment brands like visa, mastercard, amex, jcb and discover. This standard mandates several specific application security requirements among other information security requirements. The standard mandates compliance for any entity, storing, processing or transmitting cardholder information. Merchants, service providers, banks and hosting providers are some of the entities that are under the purview of this standard.

    The HIPAA is an important compliance standard that is mandatory for entities handling personal health information. The act mandates security measures which may include web application security, as these apps handle a great volume of sensitive health information.

    The GLBA is an act driven to modernize the Financial Services industry. In its multiple requirements, GLBA also mandates entities handling personal financial information to have a stringent information security program.

    SOX is a law requiring listed entities to have internal control measures to ensure integrity of their financial statements. Now, in this age of computerized accounting and ERP, web applications play a major role in the preparation and creation of financial statements, thereby requring application security measures to be a part of the system.
  • Now lets get to some of the case studies of Web Application attacks that we have lined up....
  • Abhay: Our first case study is a personal experience of mine with an online educational services provider, let us call the company “Prudent Educational Services”. They were affected by a Cross Site Scripting vulnerability...
  • Dr. BVK: For the benefit of some of the audience here, can you explain Cross Site Scripting....??
    Abhay: Cross Site Scripting is a vulnerability where an attacker injects JavaScript into application input. If the application does not filter input and output, the application deems the input to be html code and executes the JavaScript on the user’s browser. This has multi-pronged effects. This could be used to steal user cookies, or even take over the user’s browser and feed him/her with malware. User Session Hijacking, Malicious redirection to another site, Denial of service, a crafted JavaScript could force the site to crash after a point. This has been seen with several sites like Myspace....
  • So what happened at Prudent was this....They were a company that was upgrading their app to a newer app. They have several users accessing their online educational classes. We found Cross Site Scripting in certain sections of the site, but their developers were not convinced. So, we had a simple experiment. They hadnt gone live yet and they were testing, so we injected a JavaScript into the message board section of the application and hooked it up to a browser exploitation framework.
  • What we can do with the browser exploitation framework is this. We identify the Cross Site Scripting flaw and have the framework run a cross site scripting against the application. This attack is intended to hook any user browser that executes the script in the vulnerable site. The browser exploitation framework hooks a user computer turning it into a zombie. Once hooked the attacker can do anything to the browser and in some cases the computer. Exploits can be fed, owning the computer. We did the same to Prudent’s testing team and by the end of the day 50 users were hooked. Let’s say they took things pretty seriously after that....

  • Dr. BVK: For the benefit of some of the audience here, please explain this attack SQL Injection?
    Abhay: SQL Injection is an attack where an attacker passes SQL queries into the application’s input. If the application does not filter the input effectively, the query is executed and the attacker can gain access to sensitive database information and in some cases, can compromise the entire database.

  • Notes:
    We will show you a demo of a SQL Injection attack.
    This is the site of an e-commerce where people can buy and sell items. Its a typical e-commerce site.
    We will show you how we identify SQL Injection vulnerabilities. We add a single quote to the HTTP GET request parameter. This is done to induce an error page. If the error page comes up, the parameter with the single quote is being parsed and the app is potentially vulnerable to SQLi
    We will show you how we use tools to exploit the given vulnerability. We fire up SQLmap to identify and exploit the given SQL Injection vulnerability.
    The tool is able to perform any kind of injection, including enumerating DB usernames and passwords

  • What happened to the header?
  • We will now show you an example of authentication authorization bypass.
    This is a login screen for a typical e-ticket booking website. In this case a bus booking site
    We dont have valid credentials on the site, we just improvise!!
    We use an innocuous parameter like chkRules and nullify all the values.
    We use an interception proxy to alter the param values on the fly
    Voila!! We gain access to a user account and use our access to pivot to other parts of the web app.
  • Dr. BVK: Abhay, werent we discussing a formula for secure web apps?
    Abhay: Yup, here it is....
    Dr. BVK: We will be exploring each of these elements that are summed up to make a secure web application.....
  • The unifying process to build secure web applications is to have a Secure Software Development Lifecycle or SSDLC. Now, an SDLC is nothing but a typical SDLC with Security as a priority in every step of the SDLC. Dr. Kumar and I have covered a unique methodology for SSDLCs in great detail in our book Secure Java for Web Application Development. We will not go into Secure SDLC in this talk due to the paucity of time.

  • Abhay: Authentication is probably considered the perimeter defense for web applications. If an attacker can authenticate into the web app, then the access can be used to do more damage to the web app.

    One of the primary authentication requirements is password management. The web app must enforce password strength requirements (atleast in the case of high risk applications like Banking and E-Commerce or Admin Consoles). Web Apps should also enforce password changes.

    Another important password feature is the password lockout. For high-risk applications accounts should be locked out of the application after say 4/5 failed authentication attempts. Oftentimes, it is seen that password bruteforcing is done extensively by attackers. Another major bone of contention is password reset questions. How many of you have come across Rudimentary questions when you do a password reset like “What is the name of your school?” or “What is your favourite hobby?”. I have a great answer to all these questions and it is called “Social Networking” Using the power of Social Networks, where you put up everything from your favourite shirt colour to your dog’s spouse’s name. Its easy to find the name of your highschool or your favourite hobby. In fact, a major telecom company had this particular password reset question. Which car do you own at home? with 4 options: Lamborghini, Lotus, Fiat or Honda. No prizes for guessing the correct answer.

    Many applications also implement Authentication parameters like isValidated() or isAuthenticated() and by setting these parameters to null or no, the attacker is able to gain access to the account. The key is to validate these parameters.

    Abhay: There is another attack called CSRF, which we will discuss at a later part of the presentation.
  • Abhay: Authorization is the next important piece of the access control puzzle. Once a user is authenticated, he/she needs to have access to resources that she is allowed to access. The principle of “Least Privilege” governs an effective authorization system. Least Privilege dictates that resources should only be granted to users based on their need to know/use that resource.

    Abhay: Another important point of mention is that Authorization systems need to be driven by the server side. I have seen certain “Authorization systems” that have relied on either JavaScript or HTML commenting to enforce authorization to pages and disabled functionality. Authorization needs to be driven based on the sensitivity of the resource/function and the need for a user to access the resource/perform the function.

  • Abhay: Session management is the glue that holds authentication, authorization and access control together in a web application. In most cases the default session token system implemented by the web/application server is cryptographically strong. It is strongly advised that developers not write their own session token scheme....

    Applications must also enforce Session timeouts after a stipulated timeframe, say 15 minutes. In case of high-risk web apps like Banking, session timeout must be set to lower, like 5 minutes or so...

    Certain functions or actions in a web application are highly privileged functions, which are also highly at risk. For instance, transfer of funds in a banking web app is a highly critical function. In such cases, it is prudent to have the user reauthenticate with a different set of credentials or regenerate the session token for a higher privilege transaction. This may also be implemented for Application Administrators when they need to perform highly privileged functions in the web app.

    Session fixation attacks are common among several applications. Session fixation attacks rely on the fact that the application does not invalidate existing session tokens, when logging a user into the application, Thereby giving an attacker access to the user’s account on an older session. Existing sessions must be invalidated before giving a user access to the application.
  • Abhay: So, What does the new Java EE has to offer for the Triple A??

    Dr. Kumar: Authentication and authorization part of the java web applications can be handled using the Services and APIs of JAAS - The Java Authentication and Authorization Services part of the Java Platform. The JAAS has evolved since a long time along with the platform and has been easing the pains of the web application developers using the Java Platform for Application Access Control Implementation. We focus, in this particular talk, on the advanced features of Java EE 6 and of the security aspects as applicable to a web application.
  • Dr. Kumar: (Continue)
    As we are focusing on the web application security part, we will restrict our time in understanding the web application development part of the new security features in Java EE 6. Again we will filter-out the non-java part (on things such as http-method-omissions, Filter Mappings etc). We will elucidate the servlet security feature that was introduced in Java EE 6. There are essentially three items that we need to focus - the authenticate() method, the login() method and logout() method. Also, note that their implementation as a part of the new GlassFish V3 app is complete and tested for the new Java EE 6 version.

  • Dr. Kumar: (Continue)
    The authenticate() method is provided in the javax.servlet.http.HttpServletRequest  interface. This method is one of the  examples of programmatic security (login, in particular) in Java EE 6. It can be used as an alternative to the <auth-constraint>. When used in a servlet or a JSP, it forces authentication, using the login-mechanism specified in web.xml even if no security-constraint element is specified in the web.xml. After a call to authenticate succeeds, the user credentials are validated using appropriate methods().
    Abhay: Oh! What are these methods and how do they help??
    Dr. Kumar: The following methods provide the desired results for authentication part of the web application:
    (i) getRemoteUser(), (ii) isUserInRole(), (iii) getUserPrincipal()
    We will discuss aout these methods a little later during the Authorization part of the presentation.
    The advantage of using the authenticate method is that it provides the flexibility to login in dynamically combined with the ability to be used with the configured  login-mechanism like BASIC. Here is a sample code that illustrates the use of the new authenticate() method. On deploying the war file and accessing the servlet (http://<server-name>:<port-number>/application/test , a BASIC authentication is forced by the  container, since the call to authenticate() is made in the service method of the servlet.

  • Dr. Kumar: (Continue)
    The other two related methods are login() and logout(). Note that they also throw ServletException.
    Similar to the authenticate() method, the login() method serves to authenticate a given username and password programmatically. This method throws a ServletException when the validation of username, password provided fails or if the caller identity has been already established before a call to this method or if the configured login mechanism (in web.xml) is does not support username, password validation.
    A recent fix was made to have the authentication state in the existing session after a successful login. The session is created if it does not exist at this time to store the auth state. In the orthogonal HttpServletRequest.logout() method, this authentication state is cleared from the session. Please note the servers need to appropriately implement these new features. For example the new GlassFish V3 takes care of the same.
    Notice that the login() method allows to programmatically collect with the provided username/password credentials (as an alternative to FORM-based authentication) and perform user authentication. Similarly, the logout() method performs logging out the user and resets the context.
  • Abhay: You just now completed the Authentication part. How about Authorization part in the new Java EE 6??
    Dr. Kumar: We have a few new methods introduced which are very useful in the Authorization part of the application. After a call to authenticate() method succeeds, the user credentials can be validated and the following methods provide the desired results: Recall we mentioned it earlier that there are three of them. They are:
    (i) getRemoteUser()
    (ii) isUserInRole()
    (iii) getUserPrincipal() 

  • Abhay: Can you elaborate on these methods in brief??
    Dr. Kumar: Sure. Lets go with the first one, the getRemoteUser() method. The method getRemoteUser() - provides the name of the remote user associated with the request, as highlighted here. In this code snippet, we are just printing the remote user name....

  • Dr. Kumar: (Continue)
    The next method is the isUserInRole() Method: This method determines if the remote user (that is, the caller) associated with the request is in a specified security role - returns true after a successful authenticate, provided the role is specified. We have provided a snap shot of the usage of validating whether the user is in a given role or not in this if statement.

  • Dr. Kumar: (Continued)
    FInally the getUserPrincipal() method: This method determines the principal name of the remote user (that is, the caller) and returns a java.security.Principal object corresponding to the remote user. Here is the usage of the getUserPrincipal() method.

  • Abhay: What about Annotations in the new Java EE 6 for web application development??
    Dr. Kumar: The annotations part of the java has enter the Servlet world now. Accordingly we also have security related annotations (and the corresponding deployment descriptors) taking care of Security requirements for web applications.

    With Servlet 3.0 implementation, we would able to use standard Java annotations for declaring security constraints as equivalent to those defined in a standard Web deployment descriptor (web.xml). With Security annotation you should able to define roles, access control to HTTP methods, transport-layer protection (for enforcing SSL/TLS). To make use of security annotations in Servlets, Servlet 3.0 has introduced @ServletSecurity annotation to support defining security constraints.
  • Abhay: What other Annotations are available for web application development??
    Dr. Kumar: The @ServletSecurity annotation allows to define the security constraints as its fields - @HTTPConstraint, @HTTPMethodConstraint. @DeclareRoles and @RoleAllowed.
    Abhay: Can you briefly mention how these annotations are used in the web application for handling the security??
    Dr. Kumar: For example use @HttpConstraint(rolesAllowed to ensure that all HTTP methods (GET, POST, TRACE) are protected and access is allowed to security role “customer” and @HttpConstraint annotation to ensure the methods require SSL transport.
    Similarly, we can use HttpMethodConstraints  to ensure only authenticated users with security role is allowed to access HTTP POST method and transport-layer security/SSL is supported but not required.

    Finally, the @DeclareRoles and @ RoleAllowed are a no brainer
  • Dr. Kumar: (Contiuned) A Typical usage of the Servlet Annotations and their fields are shown in this slide.
  • Dr. Kumar: Hey, you said something about an attack called CSRF. What is that????

    Abhay: Let me give you Scenario: Let us say an attacker wants to hack your bank account and steal some money. He sends you an email with a URL, actioning a transfer to his account. Let us assume that you are logged into your email and your bank account simultaneously. You click on the link of the malicious email and a request is raised to the bank. The bank does not know that it is a phantom request coming from a phantom source. For the bank, you a currently logged in and the request is legit. The funds are transferred because the bank’s site was vulnerable to CSRF.
  • Dr Kumar: How can this be prevented??

    Abhay: This can be prevented in a few ways. One of the most effective ways is to raise a cryptographically secure string and store it in every user’s session object. The string should be accessed and made as an HTML hidden form field and submitted with every request that the user makes to the application. On the server side, the token submitted must be matched against the string in the session object. If it matches, the request should be considered legit. Usage of Java’s SecureRandom is ideal for these implementations.
  • Abhay: Data is the reason why we are actually talking about security. While Access control is important to protect unauthorized access to data, it is also important to secure data when it is stored and transported as there are several attacks which are attempted by attackers to extract data at rest and in transit. Let us talk about these four topics on Data Protection....

  • Dr. Kumar: Abhay, Why dont you tell us something about Crypto implementations for Web Apps?

    Abhay: One of the primary mistakes people make is to believe that the cryptographic algorithms they develop are way better than the industry standard algorithms out there and design their own encryption schemes. Once, I came across a developer who wanted to encrypt credit card numbers in his app by subtracting with one set of digits and adding with another set of digits. Please do not write home grown crypto.

    Strong Encryption algorithms need to be used to protect data at rest. Preferably AES-128 bit or above) or 3DES or in case of asymmetric crypto, keylengths of atleast 1024 bit.

    Apart from key and key parameters, it is very important to ensure that a single encryption key performs a single task, for instance, a key used to encrypt data should not be used as a key used to encrypt transmissions. Higher usage of the key results in higher possibility of a key compromise.

    Ensure that data at rest is stored with a key and and that key is encrypted with another key called the Key Encrypting Key. The data encryption key is more likely to be compromised, therefore there is an additional layer of security with the key encrypting key. It has to be ensured that the DEK and KEK are not stored in the same location.
  • It is ideal if the key management process is driven from the application. In some cases, organizations dedicate specific key management servers or devices for key management, but that is a luxury.

    One of the golden rules of thumb is to never ever store key or key strings in the source code. I was assessing a banking application, where the developer had written down the key value in a serverside comment and their application was also vulnerable to a source code disclosure attack, where I could enter arbitrary strings and gain access to their source code on my browser. Finding a key encrypting millions of personal records is like gold for an attacker....

    Asymmetric crypto requires a public-private key pair. And the private key, as the word goes needs to be kept private. Export of the private key should be disallowed.

    In many cases, encryption keys are generated, in some other cases, the key is a password or passphrase which is created by the key custodian(s). In such cases, the quality of the password must be compulsorily specified by the organization to ensure that the quality of the encryption key remains paramount.
  • It is a moot point, when you take a great deal of care to store, manage keys and transport these keys across an unencrypted channel. Anyone sniffing the wire is likely to find the key in the traffic. All key transport should be across encrypted traffic. Needless to say, keys need to be changed. After a certain point the possibilities of a key being compromised are high and have to be changed.

  • Abhay: How can we implement using Java??

    Dr. Kumar: We have the JCA / JCE coming to our rescue, as usually. You know it is not at all new. The new Java EE 6 introduces several new features for Cryptography, Cipher and Encryption which eases the web application data security.

    The JCA / JCE provides an extensible, full featured API for building secure applications which are Algorithm and implementation independent in a provider-based (pluggable) architecture
  • Dr. Kumar: (Continue)
    We already know JCA and JCE provide a wide range of cryptographic services such as digital signatures, message digest, symmetric and symmetric ciphers, stream and block ciphers, message authentication codes, key generators and key factories.

    These rich libraries also provide support for standard algorithms such as RSA, DSA, AES, Triple DES, SHA, PKCS#5, RC2 and RC4
  • Abhay: Fine, but what are the new features specific to Java EE 6??
    Dr. Kumar: Some of the new features specific to Java EE 6 (and not necessarily web application focused) are:
    Elliptic Curve Cryptography (ECC) in SunPKCS11
    Elliptic Curve CipherSuites in SunJSSE
    Access Network Security Services (NSS) using SunPKCS11
    Cipher Text Stealing (CTS) mode added to SunJCE block ciphers
    Removed the 2048 RSA keysize limit from local_policy.jar
    Access to native PKI and cryptographic services on Microsoft Windows

    -------Additional notes in case there are questions on specifics -------------
    Elliptic Curve Cryptography (ECC) in SunPKCS11

    (For elaboration in case of question - The SunPKCS11 provider now exposes ECC algorithms if the underlying PKCS#11 token supports them. This include ECDSA signing and verification, ECDH key agreement, and generation of EC keypairs. For more information about the supported mechanisms, see the supported algorithms section in the PKCS#11 reference guide.)

    Elliptic Curve CipherSuites in SunJSSE

    (For elaboration in case of question - The SunJSSE now supports the ECC ciphersuites defined in RFC 4492, if a suitable crypto provider is available (for example, SunPKCS11 with an appropriate PKCS#11 library)

    Access Network Security Services (NSS) using SunPKCS11

    (For elaboration in case of question - The SunPKCS11 provider supports new configuration directives which allow it to access the NSS security library. This enables Java applications to read keys stored in the NSS database files, use ECC algorithms, and to use the NSS Softtoken as a FIPS 140 compliant cryptography provider)

    Cipher Text Stealing (CTS) mode added to SunJCE block ciphers

    (For elaboration in case of question - CTS is described in Bruce Schneier's book "Applied Cryptography-Second Edition", John Wiley and is used by some Kerberos implementations)

    Removed the 2048 RSA keysize limit from local_policy.jar

    (For elaboration in case of question - Implementations were previously restricted from obtaining RSA keys larger than 2048 bits without installing the unlimited crypto policy files)

    Access to native PKI and cryptographic services on Microsoft Windows

    Added the SunMSCAPI JCE provider which uses the Microsoft CryptoAPI (CAPI) to offer a variety of RSA cryptographic functions. It acts as a bridge between Java applications and the services offered by the default RSA cryptographic service provider available via CAPI. It provides access to X.509 certificates and RSA key pairs, it performs RSA encryption and decryption, and it creates and validates RSA signatures. It also supports a cryptographic random number generator)

  • Dr. Kumar: Abhay, didnt you mention another data protection technique that you wanted to talk about?

    Abhay: Yes, Hashing is another important data protection technique for data at rest. Hashing as some of you may know, is a one way operation, in that the data once hashed cannot be regenerated as in the case of encryption. In many ways hashing is better as the data is subjected to a one-way procedure and it can be validated with queries and other processes. It is common practice to hash passwords in web apps.

    Having said that it is imperative that strong hashing algorithms upwards of SHA-1 be used. It was proved recently, that MD5 an extremely popular hash algorithm was broken and proven non-secure. So, please change your hashing algos if you are using MD5.

    A Salt is not for food in the case of hashing. Salt is a nonce or a string that is used to add a greater degree of randomness to the hash value. Adding a salt prevents collision of hash values of similar data, thereby adding an extra measure of security to the hashed information.

  • Dr. Kumar: Abhay, what about Logging implementation for Web Apps?

    Abhay: Logging is considered by many to be an unnecessary resource. But imagine this, your application is hacked with a SQL Injection attack and the attacker consistently extracts information out of the database for 6 months and you finally figure it out and want to look for the source and starting point of this attack, the only thing that will tell you this are the logs. This story was a real life incident at one of the largest universities in california, not too far from here....

    Logging currently is not a part of the Java Security Requirements. However, we believe that it should be and we have also made a special mention of the same in our book.

    What should be logged, (READ OUT)

  • Abhay: Dr. Kumar, can you throw some light on the logging features of the new Java??Dr. Kumar: Sure. We already aware that the java.util.logging libraries can help in doing the necessary activities such as servicing, maintenance and security log report generation. These APIs help in capturing the information on security failures, configuration and other errors and exceptions, etc

  • Abhay: Secure Coding is one of the most important facets of Secure Web Application Development, in fact, most attacks are successful against a web application due to the lack of secure coding practices used by developers of these apps. There are quite a few ways to write Secure Code, but we will explore some of the critical requirements from a Secure Coding standpoint and they are....
  • Input validation is a swiss knife against web application attacks. It is a cure for most evils out there. Input validation essentially refers to the process of ensuring that the application receives consistent and correct input that ensures that the processing of the input is smooth and without hindrance. Injection attacks are mostly perpetrated due to lack of input validation where an attacker can enter malicious characters and carry out the attack.

    First step to input validation is to understand all the input to the application, whether it is from user or from a webservice, or other site, or file. All input needs to be identified, text input, checkboxes, radio buttons can all be manipulated to inject if note validated.

    Regular expressions should be used to validate input. Let us suppose that you want to validate an email address, a regular expression with the java.util.regex library can be used for creating the reg ex and validating the user input based on the regex.

    Need I say, that Input Validation has to be done server side and not client side with JavaScript because of that one word : Client side.

    There are 2 approaches to validating input. One is a black list where one needs to identify all the characters deemed as contraband and filter the application input based on these known bad characters. The other is the whitelist, which is a highly recommended approach. Whitelisting allows you to create a known-good set of characters that one can use to filter input. For instance if you would like to filter a username field, you would filter it to only allow letters, numbers and perhaps underscore. This is a better approach than blacklisting, because you cannot effectively ensure 100% protection against attacks in a blacklisting approach as there are several injection attacks that can be encoded differently for the attack to be successful.

  • This is a clear example of a Input Validation fail. As you can see that the developer is just picking up raw input parameters here....
  • and redirecting the same to another page without filtering anything on the server side.
  • Abhay:

    Dr Kumar: For Input validation, we have the usual classes from the java.util.regex and the java.text libraries of the Java Standard edition which can be used as appropriately.

    The Matcher and Pattern classes of the java.util.regex package helps us in matching character sequences against patterns specified by regular expressions.

    Similarly, the Normalizer class in the java.text package provides the method normalize which transforms Unicode text into an equivalent composed or decomposed form, allowing for easier sorting and searching of text. The normalize method supports the standard normalization forms described in the Unicode Normalized forms.

    Specifically for the web components, we have the HttpServletRequestWrapper class, whose methods are useful in wrapping the given HTTPServletRequest object for processing the data input for validation. And, of-course, we have the Filter interface which can help us in designing a validating filter.

  • Dr. Kumar: (Continued) Here are some examples of the HTTPServletRequest wrapper and the use of suitable methods for Input validation. In this example, the matches() method is used on the canonicalized input data.

  • Output Encoding is a complementary control to Input Validation. Output when not encoded/inconsistently encoded, creates a scenario where the attacker’s script injection is executed because the application interprets the input as html and the browser executes the script. However, if the output is explicitly encoded and all special characters (malicious characters are encoded) then the script is taken to be regular input and the special characters will be replaced with the encoded character, thereby rendering a potentially deadly script injection attack useless.
  • Abhay: (Question)

    Dr. Kumar: For Output encoding we have the URLEncoder class from the java.net package for the HTML form encoding. The static encode method converting a String object to the application/x-www-form-urlencoded MIME format.

    Although not a part of the Java EE 6 part we are discussing, we have some interesting libraries from apache.commons.lang whose StringEscapeUtils class provides a number of methods to Escapes and unescapes String objects for Java, Java Script, HTML, XML, and SQL.

    The ResponeUtils class of the Struts framework (of the yesteryears) can also be highlighted here. General purpose utility methods of this class is related to generating a servlet response in the Struts controller framework.

  • Here are the results of an application without output encoding
  • The scenario changes wildly when there is output encoding and the special characters are escaped.
  • Databases are the most targeted sources of data today and SQL injection is the deadliest attack out there. Input Validation helps greatly in alleviating the problems of SQL Injection by filtering malicious SQL oriented input containing quotes and semicolons. However, as a complementary control it is necessary that all SQL queries of the app are done using PreparedStatements as opposed to dynamically generating a SQL query using the input parameters.