org.owasp.esapi
Class HTTPUtilities

java.lang.Object
  extended byorg.owasp.esapi.HTTPUtilities
All Implemented Interfaces:
IHTTPUtilities

public class HTTPUtilities
extends java.lang.Object
implements IHTTPUtilities

Reference implementation of the IHTTPUtilities interface. This implementation uses the Apache Commons FileUploader library, which in turn uses the Apache Commons IO library.

To simplify the interface, this class uses the current request and response that are tracked by ThreadLocal variables in the Authenticator. This means that you must have called ESAPI.authenticator().setCurrentHTTP(null, response) before calling these methods. This is done automatically by the Authenticator.login() method.

Since:
June 1, 2007
Author:
Jeff Williams (jeff.williams .at. aspectsecurity.com) Aspect Security
See Also:
IHTTPUtilities

Constructor Summary
HTTPUtilities()
           
 
Method Summary
 java.lang.String addCSRFToken(java.lang.String href)
          Adds the current user's CSRF token (see User.getCSRFToken()) to the URL for purposes of preventing CSRF attacks.
 javax.servlet.http.HttpSession changeSessionIdentifier()
          Invalidate the old session after copying all of its contents to a newly created session with a new session id.
 java.lang.String decryptHiddenField(java.lang.String encrypted)
          Decrypts an encrypted hidden field value and returns the cleartest.
 java.util.Map decryptQueryString(java.lang.String encrypted)
          Takes an encrypted querystring and returns a Map containing the original parameters.
 java.util.Map decryptStateFromCookie()
          Retrieves a map of data from the encrypted cookie.
 void enableRememberToken(int maxAge, java.lang.String domain, java.lang.String path)
          Save the user's remember me token in a cookie.
 java.lang.String encryptHiddenField(java.lang.String value)
          Encrypts a hidden field value for use in HTML.
 java.lang.String encryptQueryString(java.lang.String query)
          Takes a querystring (i.e.
 void encryptStateInCookie(java.util.Map cleartext)
          Stores a Map of data in an encrypted cookie.
 java.lang.String getCookie(java.lang.String name)
          Utility method to get a cookie from the current request.
 javax.servlet.http.HttpServletRequest getCurrentRequest()
          Retrieves the current HttpServletRequest
 javax.servlet.http.HttpServletResponse getCurrentResponse()
          Retrieves the current HttpServletResponse
 java.util.List getSafeFileUploads(java.io.File tempDir, java.io.File finalDir)
          Uses the Apache Commons FileUploader to parse the multipart HTTP request and extract any files therein.
 boolean isSecureChannel()
          Returns true if the request was transmitted over an SSL enabled connection.
 void killAllCookies()
          Kill all cookies received in the last request from the browser.
 void killCookie(java.lang.String name)
          Kills the specified cookie by setting a new cookie that expires immediately.
 void logHTTPRequest(ILogger logger)
          Format the Source IP address, URL, URL parameters, and all form parameters into a string suitable for the log file.
 void logHTTPRequest(ILogger logger, java.util.List parameterNamesToObfuscate)
          Formats an HTTP request into a log suitable string.
 void safeAddCookie(javax.servlet.http.Cookie cookie)
           
 void safeAddCookie(java.lang.String name, java.lang.String value, int maxAge, java.lang.String domain, java.lang.String path)
          Adds a cookie to the HttpServletResponse that uses Secure and HttpOnly flags.
 void safeAddHeader(java.lang.String name, java.lang.String value)
          Adds a header to an HttpServletResponse after checking for special characters (such as CRLF injection) that could enable attacks like response splitting and other header-based attacks that nobody has thought of yet.
 java.lang.String safeEncodeRedirectUrl(java.lang.String url)
          Deprecated.  
 java.lang.String safeEncodeRedirectURL(java.lang.String url)
          Return exactly what was sent to prevent URL rewriting.
 java.lang.String safeEncodeUrl(java.lang.String url)
          Deprecated.  
 java.lang.String safeEncodeURL(java.lang.String url)
          Return exactly what was sent to prevent URL rewriting.
 void safeSendError(int sc)
           
 void safeSendError(int sc, java.lang.String msg)
           
 void safeSendForward(java.lang.String context, java.lang.String location)
          This method perform a forward to any resource located inside the WEB-INF directory.
 void safeSendRedirect(java.lang.String context, java.lang.String location)
          This method generates a redirect response that can only be used to redirect the browser to safe locations.
 void safeSetCharacterEncodingInRequest(java.lang.String env)
           
 void safeSetCharacterEncodingInResponse(java.lang.String charset)
           
 void safeSetContentType()
          Set the character encoding on every HttpServletResponse in order to limit the ways in which the input data can be represented.
 void safeSetDateHeader(java.lang.String name, long date)
           
 void safeSetHeader(java.lang.String name, java.lang.String value)
          Sets a header in an HttpServletResponse after checking for special characters (such as CRLF injection) that could enable attacks like response splitting and other header-based attacks that nobody has thought of yet.
 void safeSetIntHeader(java.lang.String name, int value)
           
 void safeSetLocale(java.util.Locale loc)
           
 void safeSetStatus(int sc)
           
 void safeSetStatus(int sc, java.lang.String sm)
           
 void setCurrentHTTP(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response)
          Stores the current HttpRequest and HttpResponse so that they may be readily accessed throughout ESAPI (and elsewhere)
 void setNoCacheHeaders()
          Set headers to protect sensitive information against being cached in the browser.
 void verifyCSRFToken()
          Checks the CSRF token in the URL (see User.getCSRFToken()) against the user's CSRF token and throws an IntrusionException if it is missing.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

HTTPUtilities

public HTTPUtilities()
Method Detail

addCSRFToken

public java.lang.String addCSRFToken(java.lang.String href)
Description copied from interface: IHTTPUtilities
Adds the current user's CSRF token (see User.getCSRFToken()) to the URL for purposes of preventing CSRF attacks. This method should be used on all URLs to be put into all links and forms the application generates.

Specified by:
addCSRFToken in interface IHTTPUtilities
Returns:
the updated href with the CSRF token parameter
See Also:
IHTTPUtilities.addCSRFToken(java.lang.String)

enableRememberToken

public void enableRememberToken(int maxAge,
                                java.lang.String domain,
                                java.lang.String path)
Save the user's remember me token in a cookie. Old remember me cookies should be destroyed first. Setting this cookie will keep the user logged in until the Authenticator.logout method is called, which will destroy the cookie.

Specified by:
enableRememberToken in interface IHTTPUtilities
Parameters:
maxAge -
domain -
path -

safeAddCookie

public void safeAddCookie(java.lang.String name,
                          java.lang.String value,
                          int maxAge,
                          java.lang.String domain,
                          java.lang.String path)
Adds a cookie to the HttpServletResponse that uses Secure and HttpOnly flags. This implementation does not use the addCookie method because it does not support HttpOnly, so it just creates a cookie header manually.

Specified by:
safeAddCookie in interface IHTTPUtilities
Parameters:
maxAge - number of seconds until cookie expires
name - the name
value - the value
domain - the domain
path - the path
See Also:
org.owasp.esapi.interfaces.IHTTPUtilities#safeAddCookie(java.lang.String, java.lang.String, java.util.Date, java.lang.String, java.lang.String, javax.servlet.http.HttpServletResponse)

safeAddHeader

public void safeAddHeader(java.lang.String name,
                          java.lang.String value)
Description copied from interface: IHTTPUtilities
Adds a header to an HttpServletResponse after checking for special characters (such as CRLF injection) that could enable attacks like response splitting and other header-based attacks that nobody has thought of yet.

Specified by:
safeAddHeader in interface IHTTPUtilities
Parameters:
name - the name
value - the value

safeSendError

public void safeSendError(int sc)
                   throws java.io.IOException
Throws:
java.io.IOException

safeSendError

public void safeSendError(int sc,
                          java.lang.String msg)
                   throws java.io.IOException
Throws:
java.io.IOException

getCookie

public java.lang.String getCookie(java.lang.String name)
Utility method to get a cookie from the current request.

Specified by:
getCookie in interface IHTTPUtilities

safeSetDateHeader

public void safeSetDateHeader(java.lang.String name,
                              long date)

safeSetIntHeader

public void safeSetIntHeader(java.lang.String name,
                             int value)

safeSetCharacterEncodingInResponse

public void safeSetCharacterEncodingInResponse(java.lang.String charset)

safeAddCookie

public void safeAddCookie(javax.servlet.http.Cookie cookie)

safeSetLocale

public void safeSetLocale(java.util.Locale loc)

safeSetStatus

public void safeSetStatus(int sc)

safeSetStatus

public void safeSetStatus(int sc,
                          java.lang.String sm)

safeSetCharacterEncodingInRequest

public void safeSetCharacterEncodingInRequest(java.lang.String env)
                                       throws java.io.UnsupportedEncodingException
Throws:
java.io.UnsupportedEncodingException

safeSetHeader

public void safeSetHeader(java.lang.String name,
                          java.lang.String value)
                   throws ValidationException
Description copied from interface: IHTTPUtilities
Sets a header in an HttpServletResponse after checking for special characters (such as CRLF injection) that could enable attacks like response splitting and other header-based attacks that nobody has thought of yet.

Specified by:
safeSetHeader in interface IHTTPUtilities
Parameters:
name - the name
value - the value
Throws:
ValidationException

safeEncodeURL

public java.lang.String safeEncodeURL(java.lang.String url)
Return exactly what was sent to prevent URL rewriting. URL rewriting is intended to be a session management scheme that doesn't require cookies, but exposes the sessionid in many places, including the URL bar, favorites, HTML files in cache, logs, and cut-and-paste links. For these reasons, session rewriting is more dangerous than the evil cookies it was intended to replace.

Parameters:
url -
Returns:

safeEncodeUrl

public java.lang.String safeEncodeUrl(java.lang.String url)
Deprecated.  

Overloads the deprecated response method.


safeEncodeRedirectURL

public java.lang.String safeEncodeRedirectURL(java.lang.String url)
Return exactly what was sent to prevent URL rewriting. URL rewriting is intended to be a session management scheme that doesn't require cookies, but exposes the sessionid in many places, including the URL bar, favorites, HTML files in cache, logs, and cut-and-paste links. For these reasons, session rewriting is more dangerous than the evil cookies it was intended to replace.

Parameters:
url -
Returns:

safeEncodeRedirectUrl

public java.lang.String safeEncodeRedirectUrl(java.lang.String url)
Deprecated.  

Overloads the deprecated response method.


changeSessionIdentifier

public javax.servlet.http.HttpSession changeSessionIdentifier()
                                                       throws AuthenticationException
Description copied from interface: IHTTPUtilities
Invalidate the old session after copying all of its contents to a newly created session with a new session id. Note that this is different from logging out and creating a new session identifier that does not contain the existing session contents. Care should be taken to use this only when the existing session does not contain hazardous contents.

Specified by:
changeSessionIdentifier in interface IHTTPUtilities
Returns:
the http session
Throws:
AuthenticationException

verifyCSRFToken

public void verifyCSRFToken()
                     throws IntrusionException
Description copied from interface: IHTTPUtilities
Checks the CSRF token in the URL (see User.getCSRFToken()) against the user's CSRF token and throws an IntrusionException if it is missing.

Specified by:
verifyCSRFToken in interface IHTTPUtilities
Throws:
IntrusionException

decryptHiddenField

public java.lang.String decryptHiddenField(java.lang.String encrypted)
Description copied from interface: IHTTPUtilities
Decrypts an encrypted hidden field value and returns the cleartest. If the field does not decrypt properly, an IntrusionException is thrown to indicate tampering.

Specified by:
decryptHiddenField in interface IHTTPUtilities
Parameters:
encrypted -
Returns:

decryptQueryString

public java.util.Map decryptQueryString(java.lang.String encrypted)
                                 throws EncryptionException
Description copied from interface: IHTTPUtilities
Takes an encrypted querystring and returns a Map containing the original parameters.

Specified by:
decryptQueryString in interface IHTTPUtilities
Parameters:
encrypted -
Returns:
Throws:
EncryptionException

decryptStateFromCookie

public java.util.Map decryptStateFromCookie()
                                     throws EncryptionException
Description copied from interface: IHTTPUtilities
Retrieves a map of data from the encrypted cookie.

Specified by:
decryptStateFromCookie in interface IHTTPUtilities
Throws:
EncryptionException
See Also:
IHTTPUtilities.decryptStateFromCookie()

encryptHiddenField

public java.lang.String encryptHiddenField(java.lang.String value)
                                    throws EncryptionException
Description copied from interface: IHTTPUtilities
Encrypts a hidden field value for use in HTML.

Specified by:
encryptHiddenField in interface IHTTPUtilities
Parameters:
value -
Returns:
Throws:
EncryptionException

encryptQueryString

public java.lang.String encryptQueryString(java.lang.String query)
                                    throws EncryptionException
Description copied from interface: IHTTPUtilities
Takes a querystring (i.e. everything after the ? in the URL) and returns an encrypted string containing the parameters.

Specified by:
encryptQueryString in interface IHTTPUtilities
Returns:
Throws:
EncryptionException

encryptStateInCookie

public void encryptStateInCookie(java.util.Map cleartext)
                          throws EncryptionException
Description copied from interface: IHTTPUtilities
Stores a Map of data in an encrypted cookie.

Specified by:
encryptStateInCookie in interface IHTTPUtilities
Throws:
EncryptionException
See Also:
IHTTPUtilities.encryptStateInCookie(java.util.Map)

getSafeFileUploads

public java.util.List getSafeFileUploads(java.io.File tempDir,
                                         java.io.File finalDir)
                                  throws ValidationException
Uses the Apache Commons FileUploader to parse the multipart HTTP request and extract any files therein. Note that the progress of any uploads is put into a session attribute, where it can be retrieved with a simple JSP.

Specified by:
getSafeFileUploads in interface IHTTPUtilities
Parameters:
tempDir - the temp dir
finalDir - the final dir
Returns:
list of File objects for new files in final directory
Throws:
ValidationException - the validation exception
See Also:
org.owasp.esapi.interfaces.IHTTPUtilities#safeGetFileUploads(javax.servlet.http.HttpServletRequest, java.io.File, java.io.File, int)

isSecureChannel

public boolean isSecureChannel()
Returns true if the request was transmitted over an SSL enabled connection. This implementation ignores the built-in isSecure() method and uses the URL to determine if the request was transmitted over SSL.

Specified by:
isSecureChannel in interface IHTTPUtilities
Returns:

killAllCookies

public void killAllCookies()
Description copied from interface: IHTTPUtilities
Kill all cookies received in the last request from the browser. Note that new cookies set by the application in this response may not be killed by this method.

Specified by:
killAllCookies in interface IHTTPUtilities

killCookie

public void killCookie(java.lang.String name)
Description copied from interface: IHTTPUtilities
Kills the specified cookie by setting a new cookie that expires immediately.

Specified by:
killCookie in interface IHTTPUtilities
Parameters:
name - the cookie name

safeSendForward

public void safeSendForward(java.lang.String context,
                            java.lang.String location)
                     throws AccessControlException,
                            javax.servlet.ServletException,
                            java.io.IOException
Description copied from interface: IHTTPUtilities
This method perform a forward to any resource located inside the WEB-INF directory. Forwarding to publically accessible resources can be dangerous, as the request will have already passed the URL based access control check. This method ensures that you can only forward to non-publically accessible resources.

Specified by:
safeSendForward in interface IHTTPUtilities
Parameters:
context -
location -
Throws:
AccessControlException
java.io.IOException
javax.servlet.ServletException

safeSendRedirect

public void safeSendRedirect(java.lang.String context,
                             java.lang.String location)
                      throws java.io.IOException
Description copied from interface: IHTTPUtilities
This method generates a redirect response that can only be used to redirect the browser to safe locations. Importantly, redirect requests can be modified by attackers, so do not rely information contained within redirect requests, and do not include sensitive information in a redirect.

Specified by:
safeSendRedirect in interface IHTTPUtilities
Parameters:
location - the URL to redirect to
Throws:
java.io.IOException - Signals that an I/O exception has occurred.

safeSetContentType

public void safeSetContentType()
Set the character encoding on every HttpServletResponse in order to limit the ways in which the input data can be represented. This prevents malicious users from using encoding and multi-byte escape sequences to bypass input validation routines. The default is text/html; charset=UTF-8 character encoding, which is the default in early versions of HTML and HTTP. See RFC 2047 (http://ds.internic.net/rfc/rfc2045.txt) for more information about character encoding and MIME.

Specified by:
safeSetContentType in interface IHTTPUtilities
See Also:
org.owasp.esapi.interfaces.IHTTPUtilities#safeSetContentType(java.lang.String)

setNoCacheHeaders

public void setNoCacheHeaders()
Set headers to protect sensitive information against being cached in the browser.

Specified by:
setNoCacheHeaders in interface IHTTPUtilities
See Also:
org.owasp.esapi.interfaces.IHTTPUtilities#setNoCacheHeaders(javax.servlet.http.HttpServletResponse)

getCurrentRequest

public javax.servlet.http.HttpServletRequest getCurrentRequest()
Description copied from interface: IHTTPUtilities
Retrieves the current HttpServletRequest

Specified by:
getCurrentRequest in interface IHTTPUtilities
Returns:
the current request

getCurrentResponse

public javax.servlet.http.HttpServletResponse getCurrentResponse()
Description copied from interface: IHTTPUtilities
Retrieves the current HttpServletResponse

Specified by:
getCurrentResponse in interface IHTTPUtilities
Returns:
the current response

setCurrentHTTP

public void setCurrentHTTP(javax.servlet.http.HttpServletRequest request,
                           javax.servlet.http.HttpServletResponse response)
Description copied from interface: IHTTPUtilities
Stores the current HttpRequest and HttpResponse so that they may be readily accessed throughout ESAPI (and elsewhere)

Specified by:
setCurrentHTTP in interface IHTTPUtilities
Parameters:
request - the current request
response - the current response

logHTTPRequest

public void logHTTPRequest(ILogger logger)
Description copied from interface: IHTTPUtilities
Format the Source IP address, URL, URL parameters, and all form parameters into a string suitable for the log file. Be careful not to log sensitive information, and consider masking with the logHTTPRequest( List parameterNamesToObfuscate ) method.

Specified by:
logHTTPRequest in interface IHTTPUtilities

logHTTPRequest

public void logHTTPRequest(ILogger logger,
                           java.util.List parameterNamesToObfuscate)
Formats an HTTP request into a log suitable string. This implementation logs the remote host IP address (or hostname if available), the request method (GET/POST), the URL, and all the querystring and form parameters. All the parameters are presented as though they were in the URL even if they were in a form. Any parameters that match items in the parameterNamesToObfuscate are shown as eight asterisks.

Specified by:
logHTTPRequest in interface IHTTPUtilities
Parameters:
parameterNamesToObfuscate - the sensitive params
See Also:
org.owasp.esapi.interfaces.ILogger#formatHttpRequestForLog(javax.servlet.http.HttpServletRequest)