How do I prevent Cross-site Scripting (XSS) attacks in J2EE Web applications ?

I received this question from one of our book readers …ofcourse XSS is becoming widely popular. I had my own first-hand experience of XSS by test driving in my lab – believe me – I don’t have malicious intentions or crazy motives. If you want to verify your J2EE Web applications for XSS ulnerability…here is my cooked response – for your better understanding !

Cross-site Scripting (XSS) is one of the most popular attacks on Web-based applications by exploiting their hyperlinks or client-side scripts (aka Scriptlets) such as JavaScript, VBScript, ActiveX, XHTML, Flash etc. An XSS attacker typically uses a scriptlet mechanism to inject malicious code into a user session or its target Web server to redirect the user with a malicious hyperlink or trigger a script that hijacks the user session to another Web site. This XSS attack potentially leads to hijacking the user’s account information, changing user privileges, stealing cookie or session information, poisoning the user-specific content, defacing the Web site and so on. To protect Java EE (J2EE) based Web applications from XSS related risks and vulnerabilities, the golden rule is to perform input validation and output sanitation of Web-tier/presentation components that allows user interaction via a Web browser or a client application.

TechnicalInfo.Net)

Anatomy of XSS (Source: TechnicalInfo.Net)

In a nutshell, input validation in a Java EE Web application is done via filtering and encoding mechanisms. In practice, it is quite important to validate the input parameters at both client-side and server-side before accepting the request and resuming the process on input parameters. The filtering mechanism should validate data in terms of data type (string, integer), format, length, range, null-value handling, verifying for character-set, locale, patterns, context, legal values, session validity, redirection URL, idle time and so on.

Although filtering is a promising solution, in some scenarios we cannot discard or reject data using filters where the user is requested to provide input content that includes special characters. To handle special input content with undiagnosed characters or scripts, it is often recommended to use encoding mechanisms that allow transformation of the stream of encoded characters to a special sequence of character sets that cannot be executed at the Java EE application server or Web server. This allows us to defeat XSS attempts through malicious hyperlinks and scriptlets. If the Web application relies on client-side data validation, it is always safe and good practice to re-verify and re-validate input at server-side, even after client-side validation.

Output sanitation is also plays a vital role in avoiding XSS. Re-displaying or echoing the data values entered by users causes a potential XSS threat because it provides a hacker with a means to match the given input and its output. This provides a way to explore the Web component by inserting malicious data inputs. If the page generated by a user’s request is not properly sanitized before it is displayed, a hacker may be able to identify a weakness or loophole by reading the generated output. Using the weakness, the hacker can design and insert malicious scripts and hyperlinks. From there, a hacker may change the content originally displayed by the site or perform malicious operations.

From my experience, to thwart XSS attacks I strongly recommend using appropriate design strategies prescribed in the “Intercepting Validator” and “Secure Session Manager” patterns from the Core Security patterns catalog. In addition to input validation and output sanitization mechanisms, I often recommend the following best practices to be considered for identifying and preventing XSS-based attacks:

1. Secure the Transport:
For all security-sensitive Web applications and Web-based online transactions, make sure the session and data exchanged between the server and client remain confidential and tamper-proof during transit. Using SSL communication with digital certificates offers confidentiality and integrity of data transmitted between the Web applications and client authentication.

2. Use stateful firewalls:
Use a stateful firewall inspection to keep track of all Web-tier transmissions and protocol sessions. Make sure it blocks all unrequested transmissions.

3. Validate form fields:
Ensure that any alteration, insertion, and removal of HTML form fields by the originating browser are detected, logged, and result in an error message.

4. Use HTTP POST:
Use HTTP POST rather than HTTP GET and avoid using HTTP GET requests while generating HTML forms. HTTP GET requests reveal URL-appended information, allowing sensitive information to be revealed in the URL string. Also, disable processing of HTTP TRACE method in the target Java EE application or Web server to defeat cross-site tracing (XST) attacks.

5. Track user sessions:
Identify the originating user and the host destination making the application request in the user session ID. Verify that all subsequent requests are received from that same user’s host origin until the user logs out. This protects application sessions from XSS hijacking and spoofing.

6. Error reporting:
Always return an error page or exception specific to the application error and the user’s request. For example, you might use an application-specific InvalidUserException and NoAccessPrivilegesException. Do not expose remote, system-level and naming service specific exceptions to the user accessing the applications. To the end user, these exceptions expose weaknesses in the application and allow hackers to design potential attacks.

7. Audit all relevant business tasks:
Create audit trails for all identified user-level sessions and actions with timestamps and store them in a different log file with unique line identifiers. This helps identify any potential exploitation or weakness of the Web application. The audit trails should include user attempts and failures, logouts, disconnects, timeouts, administration tasks, user requests and responses, exceptions, database connections, and so forth.

Amazon EC2 Cloud hosts Spammers !

      No Comments on Amazon EC2 Cloud hosts Spammers !

The CLOUD computing buzz.. always sounded to me like another hosting infrastructure services that builds on XEN Virtualization services. What it makes more compelling is…. it facilitates on-demand/out-sourced datacenter that scales up and allows us to pay-as-you-go for used services. Couple of months ago, I had a chance to try out my own Amazon EC2 Web services account playing with creating/uploading AMIs and test-driving them for my hello world exercises – ofcourse I paid for it.

To my surprise, recently I came across this interesting news at Washington Post…highlighting Amazon: Hey Spammers, Get Off My Cloud !

Digging into the details, a bunch of spammers comfortably hosted on Amazon EC2 and using their infrastructure to initiate POrN spam and junk e-mail few of them with malware. More to the surprise, SPAMHAUS (An Anti-Spamware group) identified a bunch of Amazon EC2 IP addresses and flagged them on SPAMHAUS Policy Blocked Lists.

Buyers Beware:  Does it worth scaling out with Cloud computing without “Security” ?

HTTP response splitting? How-to prevent them in J2EE/Web applications ?

Couple of days ago, I received the above question from one of our readers.  Although I briefly responded to him over email,  I really wanted to explore the known traits for defending this vulnerability :

HTTP response splitting is a Web application input validation vulnerability that allows to exploit the HTTP headers of a Web application for initiating attacks leading to Cross-site Scripting (XSS),  user/page hijacking, cookie poisioning, Web-site spoofing/defacement and so on. The attacker initiates this attack through the injection of  a  sequence of hex-coded Carriage-Return (CR) and Line-Feed (LF) characters in the HTTP heaer and then appending it with malicious HTTP Set-Cookie headers  crafted to force the server to process and  break the requests into two individual responses.  To protect Java EE (J2EE) based Web applications from  HTTP Response Splitting related risks and vulnerabilities, the golden rule is to perform “Input Validation and Output Sanitation” of Web-tier/presentation components that allows user interaction via a Web browser or a client application.

  • Input Validation in a Java EE Web application is done via Filtering and Encoding mechanisms. In practice, it is quite important to validate the input parameters at both “client-side and server-side” before accepting the request and resuming the process on input parameters. The filtering mechanism should validate data in terms of data type (string, integer), format, length, range, null-value handling, verifying for character-set, locale, patterns, context, legal values, session validity, redirection URL, idle time and so on. Although filtering is a promising solution, in some scenarios we cannot discard or reject data using filters where the user is requested to provide input content that includes special characters. Particularly to mitigate HTTP Response Splitting risks,  it becomes important to parse and verify the input for CRLF \r\n %0d%0a or any other form of encoding CRLF characters before processing them. To handle special input content with undiagnosed characters or scripts, it is often recommended to use encoding mechanisms that allows to transform the stream of encoded characters as special sequence of character sets that cannot be executed at the Java EE application server or Web server. This allows to defeat HTTP Response Splitting and related XSS attempts through malicious code and script injection. If the Web application relies on client-side data validation, it is always safe and good practice to re-verify and re-validate input at server-side, even after client-side validation.

  • Output Sanitation also plays a vital role in avoiding HTTP Response Splitting. Re-displaying or echoing the data values entered by users causes a potential threat because it provides a hacker with a means to match the given input and its output. This provides a way to explore the Web component by inserting malicious data inputs. If the page generated by a user’s request is not properly sanitized before it is displayed, a hacker may be able to identify a weakness or loophole by reading the generated output. Using the weakness, the hacker can design and insert malicious scripts and hyperlinks that may be able to change the content originally displayed by the site or perform malicious operations.

For Java EE Web application developers, I strongly recommend using appropriate design strategies prescribed in the “Intercepting Validator” and “Secure Session Manager” patterns from the Core Security patterns catalog. In addition to “Input Validation and Output Sanitization” mechanisms, I often recommend the following best practices to be considered for pro-actively thwarting related attacks:

  1. Secure the Transport: For all security-sensitive Web applications and Web-based online transactions, make sure the session and data exchanged between the server and client remain confidential and tamper-proof during transit. Using SSL communication with digital certificates offers confidentiality and integrity of data transmitted between the Web applications and client authentication.
  2. Use Stateful Firewalls. Use a stateful firewall inspection to keep track of all Web-tier transmissions and protocol sessions. Make sure it blocks all unrequested transmissions.
  3. Validate Form Fields: Ensure that any alteration, insertion, and removal of HTML form fields by the originating browser are detected, logged, and result in an error message.
  4. Use HTTP POST: Use HTTP POST rather than HTTP GET and avoid using HTTP GET requests while generating HTML forms. HTTP GET requests reveal URL-appended information, allowing sensitive information to be revealed in the URL string. Also, disable processing of HTTP TRACE method in the target Java EE application or Web server to defeat Cross-site Tracing (XST) attacks.
  5. Track User Sessions: Identify the originating user and the host destination making the application request in the user sessionid. Verify that all subsequent requests are received from that same user s host origin until the user logs out. This protects application sessions from XSS hijacking and spoofing.
  6. Error reporting: Always return an error page or exception specific to the application error and the user s request. For example, you might use an application-specific InvalidUserException and NoAccessPrivilegesException. Do not expose remote, system-level, and naming service specific exceptions to the user accessing the applications. These exceptions to the end user expose weakness in the application and allow hackers to design potential attacks.
  7. Audit All Relevant Business Tasks: Create audit trails for all identified user-level sessions and actions with timestamps and store them in a different log file with unique line identifiers. This helps identifying any potential exploitation or weakness of the Web application. The audit trails should include user attempts and failures, logouts, disconnects, timeouts, administration tasks, user requests and responses, exceptions, database connections, and so forth.

OpenSSL as Certificate Authority/SSL Test Kit: Quick Cheatsheet

I always had a love and hate interest with using OpenSSL ! But I should agree that it did help me many times…whenever I wanted to quickly test-drive my craziest ideas with PKI certificates. Couple of things I like about OpenSSL is its tools/utilities for testing as equivalent to a commerecial-grade CA and its FIPS-140 compliance. Also, I always get the required help on Web, right from the details of how-to install, configure…and all the operations. Here is my attempt to share a quick recipe on using OpenSSL commands.. particularly for those looking for help on test-driving SSL certificates using OpenSSL.

(A) Creating RSA Certificates

# openssl  genrsa   2048   >   myRSA-key.pem

This command creates a 2048-bit key pair and stores it in myRSA-key.pem. The default key size is 512 bits. In case if you want to password protect the RSA private key, use the following command:

# openssl genrsa 2048 -aes256 -out myRSA-key.pem

When you run the above command, OpenSSL prompts you for a passphrase for encrypting the key file using an algorithm – ex. AES (aes128, aes192 aes256), DES/3DES (des, des3).

(B) Creating a SSL Server Certificate Signing Request (CSR)

Important Note: This process requires signing by a valid Certificate Authority (CA)

For a commercial deployments, you need to obtain the SSL certificates and associated root CA certificates from a CA (ex. Cybertrust, Entrust, Verisign) . As a first step, you need to create a CSR for requesting the CA to sign (trust) your certificates. The following is the command for creating a CSR.

# openssl req -new rsa:1024 -node -out myCertReq.pem -keyout myPrivCertkey.pem -subj /C=US/ST=MA/L=Burlington/CN=myHost.domain.com/emailAddress=nramesh@sun.com

The generated certificate request (myCertReq.pem) must be signed by a CA otherwise it will not be a valid certificate. The key algorithm is RSA and size 1024 bits, the certificate will be valid for 365 days, and with -nodes option the key will be unencrypted. The -subj allows setting the Subject DN value that identifies the hostname “CN” must be fully qualified name that you’ll be using to access your SSL site.

Save the private key file (myPrivCertKey.pem) as you need the key in order to use the Server certificate from the CA. Just for the reason not to send the private key information to CA. Send the certificate request (myCertReq.pem) to the CA via email or using their web site. After signing process, The CA will return you the signed certificate and also root CA certificates.

(C) Creating the OpenSSL CA certificate

For Intranet or testing purpose, you may want to test with your own CA and it can be done with OpenSSL. Similar to the process (A) , you need to create a private CA key (myCA.key) and then a private CA X.509 certificate (myCACert.pem).

# openssl genrsa 2048 -aes256 -out myCA.key

# openssl req -new -x509 -days 3650 -key myCACert.key -out myCACert.pem

 

(D) Creating a Self-signed certificate (For SSL)

For your testing purposes, you may want to SSL test your applications with self-signed certificates and with your own CA. To create a self-signed certiicate:

# openssl req -nodes -x509 -newkey rsa:1024 -out mySelfSignedCert.pem -keyout myPrivServerKey.pem -days 365 -set_serial 01-subj “/C=US/ST=MA/L=Burlington/CN=myHost.domain.com/emailAddress=nramesh@sun.com

-x509 identifies it as a self-signed certificate and -set_serial sets the serial number for the server certificate. You may want to remove the password from the private key (so that the SSL server will not prompt you for password). Here is the command:

# openssl rsa -in myPrivServer.key -out myPrivServer.key.insecure

In some cases, you may want to create a single file that contains both private key and the self-signed certificate:

# openssl req -x509 -nodes -days 365 -newkey rsa:1024 -subj”/C=US/ST=MA/L=Burlington/CN=myHost.domain.com/emailAddress=nramesh@sun.com -keyout myServerCert.pem -out myServerCert.pem

To create a SSL certificate signed by your own Certification Authority (CA).

# openssl ca -cert myCACert.pem -in myCertReq.pem -out myServerCert.pem

Where myCACert.pem is the CA certificate, we discussed in (C).

(E) Testing the Certificate with OpenSSL

OpenSSL provides an s_server command that provides a SSL/TLS server implementation to test/verify support SSL/TLS based connections. By default, the s_server listens on port 4433. You should able to test your certificate by running the following command:

# openssl s_server -cert myServerCert.pem -www

The above command should launch an OpenSSL based SSL server using your certificates. To verify SSL connection with your certificates, try accessing https://localhost:4443/ from your browser. You must be seeing a simple web page listing the connection details and all the supported ciphers.

(F) Converting certificates from PEM to PKCS#12 formats

PKCS12 is an RSA standard for creating “Personal Information Exchange Syntax Standard” based certificates commonly used for email signatures (ex. pfx or p12). A PKCS#12 file combines all-in-one file including public key, private key, and the root CA certificate. With OpenSSL, you would able to convert a PEM file to PKCS#12 format file, you would use the following command (all in one line ignore \ ):

# openssl pkcs12 -export -in myServerCert.pem -inkey myPrivateServerKey.pem -certfile myCACert.pem -name “[friendly name – Ramesh Nagappan]” -out myServerPKCS12Cert.pfx

 

(G) SSL Certificate Pre-requisites for Apache and MySQL

If you are thinking about configuring SSL for your Apache Web Server or MySQL database connections, you would need the following:

1) Create the CA (private key and public cert) certificates.

2) Create your SSL server key.

3) Create your SSL server certificate.

Make sure your Common Name (CN( identifies “full-qualified domain name (FQDN)” of your server. Follow the directions for configuring SSL using Apache and MySQL documentation.

Enjoy. Let me know, if you had any suggestions.

Exploring SPML with Sun Identity Manager 7.x – A Cheatsheet

Are you tired of the high-level SPML content floating around the web from couple of analysts with no practical guidance ! If you are a practical guy..who want to explore SPML, here is something that you may find worth test-driving for SPML 1.0 amd SPML 2.0 based provisioning operations.

I had been using SPML using Sun IDM 7.0 for a while now.  Most frequently,  I forget the steps for configuration and also did’nt have the patience of going through the documentation (Frankly..I’m bit lazy).  So, I ended up doing my crazy way and here is the cheat sheet of the steps required.

Configuring SPML Web Services Endpoint in Sun IDM

1.  Make sure Sun IDM is deployed and tested to run in your Web container environment (My choice would be Glassfish on Solaris 10). Sorry, I am not a Windows guy 🙂

2. Open a terminal, set your JAVA_HOME and WSHOME environment variables

bash-3.00#  export JAVA_HOME=export JAVA_HOME=/usr/java
bash-3.00#  export WSHOME=/opt/SUNWappserver/domains/domain1/applications/j2ee-modules/idm
bash-3.00#  export
bash-3.00#  export DISPLAY=<your host_name>:0.0

bash-3.00# cd /opt/SUNWappserver/domains/domain1/applications/j2ee-modules/idm/bin
bash-3.00# ./lh console

3.  Configure SPML 1.0 and SPML 2.0 objects by importing them.

Configurator> import -f /opt/SUNWappserver/domains/domain1/applications/j2ee-modules/idm/sample/spml.xml
Added TaskDefinition:SPMLRequest
Added Configuration:SPML
Added Configuration:SPMLPerson
Added Configuration:SPMLRole
Added Configuration:SPMLResourceGroup
Added Configuration:BasicUser
Added Configuration:Empty
Added Configuration:SPMLviewtest1
Added Configuration:SysInfoForm
Configurator> exit

Configurator> import -f /opt/SUNWappserver/domains/domain1/applications/j2ee-modules/idm/sample/spml2.xml
Added TaskDefinition:SPML2Request
Updated Configuration:User Extended Attributes
Added Configuration:SPML2
Added Configuration:spml2PersonForm

Configurator> exit

4.  Set the Username/Password properties in Waveset.properties file.

bash-3.00# vi /opt/SUNWappserver/domains/domain1/applications/j2ee-modules/idm/config/Waveset.properties

Add the following to the end of Waveset.properties file:

soap.username=configurator
soap.password=configurator

4. Restart your Application Server:

bash-3.00# /opt/SUNWappserver/bin/asadmin stop-domain domain1

bash-3.00# /opt/SUNWappserver/bin/asadmin start-domain –user admin domain1

5. Test your SPML Web services connection. The following command will launch “SPML Monitor” Java application.

bash-3.00# ./lh spml

Sample code

Here is my code for testing (both SPML 1.0 and SPML 2.0), just compile and run it.

SPMLv1Starter.java

SPMLv2Starter.java

SPMLAddClient.java

SPMLModifyClient.java

Enjoy !

Using PIV cards in a Sun Ray Environment.

      No Comments on Using PIV cards in a Sun Ray Environment.

Sun Ray Thin Clients has been widely popular in Government applications for a while now.  With the introduction of HSPD-12/PIV cards,  I had multiple requests from my SI friends asking me to verify whether PIV cards work on SunRays for hotdesking and enabling PKI based authentication.  As on today, Sun Ray Session Server 4.0 does’nt officially support PIV cards …particularly I meant PIV cards from Obethur and GemAlto.  Here is the SunRay-PIV-OberthurCards-CheatSheet and also download the Oberthur Card Profile for SunRays – I prepared this cheatsheet based on my first successful attempt using Oberthur PIV on SunRays to verify that  IT WORKS for hotdesking/session mobility and desktop authentication using OpenSC PAM.

For those curious to know about OpenSC support for PAM authentication on Sun Rays – make a note OpenSC.org does support Solaris 10 and Sun Rays that includes a PAM module. Also, here is some useful information about PIV card support in OpenSC.

BTW, Sun Rays already provides support for DoD CAC cards.

Enjoy.

Update: The download URL changed to Sun ThinkThin blog.

SPML 2.0 @RSA 2007

      No Comments on SPML 2.0 @RSA 2007

Last week, I was at RSA Conference and I joined a panel with Mark Diodati (Burton Group) and Sampo Kellomaki (Symlabs) to discuss interoperable Identity provisioning ! I delved into SPML 2.0 and highlighted the strategies of using SPML 2.0 for interoperable provisioning. Here is the link to our slides – Interoperable Identity Provisioning in a Distributed World (With emphasis on SPML).

Using SAML w/ SPML – A potential reality !

      No Comments on Using SAML w/ SPML – A potential reality !

I had multiple opportunities to work on SPML based user-provisioning with Sun Java System Identity Manager.  I found SPML as a very compelling standard, it worked as piece-of-cake on Sun IDM that certainly simplified my efforts on representing provisioning requests intended for creating, modifying, canceling, deleting, enabling, disabling, searching user accounts and associated access control privileges with multiple resources. Naturally I had the passion to dig deeper into SPML 2.0 !  I briefly involved with OASIS SPML TC forums and their discussions… unlike other standard efforts I am quite convinced about SPML gaining strong adoption as a de-facto standard in the user-provisioning industry and sooner it is also expected to play a vital role in enabling identity federation (yes, seriously!). We do know well, SPML helps to initiate XML-based provisioning/de-provisioning processes from the identity provider to its target service providers. This means SPML does allow users to bypass out-of-band account creation requirements using provisioning/synchronization mechanisms from LDAP, database and other user repositories. By working together with SAML, SPML can make use of SAML assertions by facilitating a trust model in which senders and receivers using SPML messages agree upon the context of a predefined unique user identifier represented by a SAML assertion. To be more precise, the SAML assertion allows users to qualify a subject, against which a provisioning request is targeted.

Lately “Federated Provisioning Profile” (SAML 2.0 Profile for SPML), a supporting profile effort, is in progress as part of OASIS Security Services (SAML) TC, which addresses the use of SAML within SPML messages. The Federated Provisioning Profile focuses on the usecase requirements, facilitating the use of SPML provisioning in identity federation where SPML messages can make use of SAML assertions as provisioning data and on-demand/just-in-time bulk user provisioning between an identity provider (IdP) and a service provider (SP). It is promising, but I am not sure where this effort stands now !

How to begin a Java security career ?

      No Comments on How to begin a Java security career ?

I received the following question from one of the readers from TechTarget.com:

Though I am not a beginner in Java, I recently got interested in Java security. What should I be learning in order to get a job in Java security? Is there anything in particular that could lead me to a career in this area?

Here is my response:

Learning application security development from Java is obviously a great choice. I often emphasize this, because the Java platform was designed with security from ground-up — including its runtime environment and programming language. With its extensible security architecture, Java provides end-to-end security mechanisms for an application beyond its underlying runtime by ensuring security at all levels including its users, components, services and communication.

In particular, Java provides APIs and mechanisms for applying cryptographic techniques, securing communication, authenticating and authorizing application users, securing micro-devices, securing XML Web services, enabling single sign-on and integrating PKI/Certificates, biometrics, smart cards, cryptographic devices and appliances.

From a Java developer perspective, understanding security technologies from Java is much easier and simpler than it is for other programming languages. Because the Java platform facilitates an interoperable, platform-neutral application development and deployment environment, the security development gets further simplified via its standardized API mechanisms and runtime environment.

To learn Java security development, I would start practicing the Java platform security mechanisms and APIs applied to your target application environment. In particular, you should explore how to bake in essential security features such as confidentiality, integrity and availability during application development. Use Java Standard Edition (Java SE) for standalone applications, Java Micro Edition (Java ME) for consumer micro devices and embedded systems and Java Enterprise Edition (Java EE) for enterprise-class applications. Understanding the basic Java security mechanisms would definitely allow a developer to solve critical application-level security requirements.

To gain expertise, I would strongly suggest adopting a proactive and holistic approach in your security development process. Do this by practicing the use of security patterns and implementation strategies, and understanding the best practices and pitfalls related to your target application environment. As a result, this expertise also would help when building robust application security using proactive and best practices based approaches — and also pave the way for a successful application security career.