org.owasp.esapi.reference
Class DefaultHTTPUtilities

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

public class DefaultHTTPUtilities
extends java.lang.Object
implements HTTPUtilities

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:
HTTPUtilities

Field Summary
 
Fields inherited from interface org.owasp.esapi.HTTPUtilities
REMEMBER_TOKEN_COOKIE_NAME
 
Constructor Summary
DefaultHTTPUtilities()
           
 
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.
 void assertSecureRequest()
          Checks the method of the current request.
 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 cleartext.
 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 a cookie encrypted with encryptStateInCookie().
 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.
 java.lang.String getCSRFToken()
          Returns the current user's CSRF token.
 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(Logger logger)
          Format the Source IP address, URL, URL parameters, and all form parameters into a string suitable for the log file.
 void logHTTPRequest(Logger 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.
 java.lang.String setRememberToken(java.lang.String password, int maxAge, java.lang.String domain, java.lang.String path)
          Save the user's remember me token in a cookie.
 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

DefaultHTTPUtilities

public DefaultHTTPUtilities()
Method Detail

addCSRFToken

public java.lang.String addCSRFToken(java.lang.String href)
Description copied from interface: HTTPUtilities
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 HTTPUtilities
Parameters:
href -
Returns:
the updated href with the CSRF token parameter added
See Also:
HTTPUtilities.addCSRFToken(java.lang.String)

getCSRFToken

public java.lang.String getCSRFToken()
Description copied from interface: HTTPUtilities
Returns the current user's CSRF token. If there is no current user then return null.

Specified by:
getCSRFToken in interface HTTPUtilities
Returns:
the current users CSRF token
See Also:
HTTPUtilities.getCSRFToken()

setRememberToken

public java.lang.String setRememberToken(java.lang.String password,
                                         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 maxAge passes, the password is changed, or the cookie is deleted.

Specified by:
setRememberToken in interface HTTPUtilities
Parameters:
password - the user's password
maxAge - the length of time that the token should be valid for in relative seconds
domain - the domain to restrict the token to or null
path - the path to restrict the token to or null

assertSecureRequest

public void assertSecureRequest()
                         throws AccessControlException
Checks the method of the current request. For example, any application logic that uses sensitive data from a web form should call ESAPI.httpUtilities().assertMethod("POST");

Specified by:
assertSecureRequest in interface HTTPUtilities
Throws:
AccessControlException

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 HTTPUtilities
Parameters:
maxAge - number of seconds until cookie expires
name - the cookie name
value - the cookie value
domain - the domain to restrict the cookie to, or null
path - the path to restrict the cookie to, or null
See Also:
org.owasp.esapi.HTTPUtilities#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: HTTPUtilities
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. This method uses HTTPUtilities.getCurrentResponse() to obtain the current HttpServletResponse object

Specified by:
safeAddHeader in interface HTTPUtilities
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 HTTPUtilities

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: HTTPUtilities
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. This method uses HTTPUtilities.getCurrentResponse() to obtain the current HttpServletResponse object

Specified by:
safeSetHeader in interface HTTPUtilities
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: HTTPUtilities
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. This method uses HTTPUtilities.getCurrentRequest() to obtain the current HttpSession object

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

verifyCSRFToken

public void verifyCSRFToken()
                     throws IntrusionException
Description copied from interface: HTTPUtilities
Checks the CSRF token in the URL (see User.getCSRFToken()) against the user's CSRF token and throws an IntrusionException if it is missing. This method uses HTTPUtilities.getCurrentRequest() to obtain the current url

Specified by:
verifyCSRFToken in interface HTTPUtilities
Throws:
IntrusionException

decryptHiddenField

public java.lang.String decryptHiddenField(java.lang.String encrypted)
Description copied from interface: HTTPUtilities
Decrypts an encrypted hidden field value and returns the cleartext. If the field does not decrypt properly, an IntrusionException is thrown to indicate tampering. FIXME RD: What value does this offer over Encryptor.decrypt(String) ?

Specified by:
decryptHiddenField in interface HTTPUtilities

decryptQueryString

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

Specified by:
decryptQueryString in interface HTTPUtilities
Parameters:
encrypted -
Returns:
FIXME RD: What value does this offer over Encryptor.decrypt(String) ? FIXME RD: Is it really valid to return a Map, if the parameter names can be duplicated? e.g. ?a=1&a=2
Throws:
EncryptionException

decryptStateFromCookie

public java.util.Map decryptStateFromCookie()
                                     throws EncryptionException
Description copied from interface: HTTPUtilities
Retrieves a map of data from a cookie encrypted with encryptStateInCookie(). This method uses HTTPUtilities#getCurrentResquest() to obtain the HttpServletRequest object FIXME RD: More information needed about why this may be useful

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

encryptHiddenField

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

Specified by:
encryptHiddenField in interface HTTPUtilities
Parameters:
value - the cleartext value
Returns:
the encrypted value
Throws:
EncryptionException - FIXME RD: What value does this offer over Encryptor.encrypt(String) ?

encryptQueryString

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

Specified by:
encryptQueryString in interface HTTPUtilities
Returns:
FIXME RD: What value does this offer over Encryptor.encrypt(String) ?
Throws:
EncryptionException

encryptStateInCookie

public void encryptStateInCookie(java.util.Map cleartext)
                          throws EncryptionException
Description copied from interface: HTTPUtilities
Stores a Map of data in an encrypted cookie. Generally the session is a better place to store state information, as it does not expose it to the user at all. If there is a requirement not to use sessions, or the data should be stored across sessions (for a long time), the use of encrypted cookies is an effective way to prevent the exposure. This method uses HTTPUtilities.getCurrentResponse() to obtain the HttpServletResponse object

Specified by:
encryptStateInCookie in interface HTTPUtilities
Throws:
EncryptionException
See Also:
HTTPUtilities.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 HTTPUtilities
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.HTTPUtilities#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.


killAllCookies

public void killAllCookies()
Description copied from interface: HTTPUtilities
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. This method uses HTTPUtilities.getCurrentRequest() to obtain the HttpServletRequest object This method uses HTTPUtilities.getCurrentResponse() to obtain the HttpServletRequest object

Specified by:
killAllCookies in interface HTTPUtilities

killCookie

public void killCookie(java.lang.String name)
Description copied from interface: HTTPUtilities
Kills the specified cookie by setting a new cookie that expires immediately. This method uses HTTPUtilities.getCurrentResponse() to obtain the HttpServletResponse object

Specified by:
killCookie in interface HTTPUtilities
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: HTTPUtilities
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. This method uses HTTPUtilities.getCurrentResponse() to obtain the HttpServletResponse object

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

safeSendRedirect

public void safeSendRedirect(java.lang.String context,
                             java.lang.String location)
                      throws java.io.IOException
Description copied from interface: HTTPUtilities
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. This method uses HTTPUtilities.getCurrentResponse() to obtain the HttpServletResponse object

Specified by:
safeSendRedirect in interface HTTPUtilities
Parameters:
context -
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 HTTPUtilities
See Also:
org.owasp.esapi.HTTPUtilities#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 HTTPUtilities
See Also:
org.owasp.esapi.HTTPUtilities#setNoCacheHeaders(javax.servlet.http.HttpServletResponse)

getCurrentRequest

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

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

getCurrentResponse

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

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

setCurrentHTTP

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

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

logHTTPRequest

public void logHTTPRequest(Logger logger)
Description copied from interface: HTTPUtilities
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. This method uses HTTPUtilities.getCurrentRequest() to obtain the HttpServletRequest object

Specified by:
logHTTPRequest in interface HTTPUtilities
Parameters:
logger - the logger to write the request to

logHTTPRequest

public void logHTTPRequest(Logger 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 HTTPUtilities
Parameters:
logger - the logger to write the request to
parameterNamesToObfuscate - the sensitive params
See Also:
org.owasp.esapi.Logger#formatHttpRequestForLog(javax.servlet.http.HttpServletRequest)