org.owasp.esapi
Interface HTTPUtilities

All Known Implementing Classes:
DefaultHTTPUtilities

public interface HTTPUtilities

The HTTPUtilities interface is a collection of methods that provide additional security related to HTTP requests, responses, sessions, cookies, headers, and logging.

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

Field Summary
static java.lang.String REMEMBER_TOKEN_COOKIE_NAME
          Key for remember token cookie
 
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()
          Ensures that the current request uses SSL and POST to protect any sensitive parameters in the querystring from being sniffed or logged.
 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)
          Returns the first cookie matching the given name.
 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)
          Extract uploaded files from a multipart HTTP requests.
 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)
          Format the Source IP address, URL, URL parameters, and all form parameters into a string suitable for the log file.
 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 specified HttpServletResponse and adds the Http-Only flag.
 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.
 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 safeSetContentType()
          Sets the content type on each HTTP response, to help protect against cross-site scripting attacks and other types of injection into HTML documents.
 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 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)
          Set a cookie containing the current User's remember me token for automatic authentication.
 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.
 

Field Detail

REMEMBER_TOKEN_COOKIE_NAME

public static final java.lang.String REMEMBER_TOKEN_COOKIE_NAME
Key for remember token cookie

See Also:
Constant Field Values
Method Detail

assertSecureRequest

public void assertSecureRequest()
                         throws AccessControlException
Ensures that the current request uses SSL and POST to protect any sensitive parameters in the querystring from being sniffed or logged. For example, this method should be called from any method that uses sensitive data from a web form. This method uses getCurrentRequest() to obtain the current HttpServletRequest object

Throws:
AccessControlException

addCSRFToken

public 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. This method should be used on all URLs to be put into all links and forms the application generates.

Parameters:
href -
Returns:
the updated href with the CSRF token parameter added

getCSRFToken

public java.lang.String getCSRFToken()
Returns the current user's CSRF token. If there is no current user then return null.

Returns:
the current users CSRF token

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 specified HttpServletResponse and adds the Http-Only flag. This method uses getCurrentResponse() to obtain the current HttpServletResponse object

Parameters:
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
maxAge - the max age in relative seconds that the cookie should be valid for

safeAddHeader

public void safeAddHeader(java.lang.String name,
                          java.lang.String value)
                   throws ValidationException
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 getCurrentResponse() to obtain the current HttpServletResponse object

Parameters:
name - the name
value - the value
Throws:
ValidationException

safeSetHeader

public void safeSetHeader(java.lang.String name,
                          java.lang.String value)
                   throws ValidationException
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 getCurrentResponse() to obtain the current HttpServletResponse object

Parameters:
name - the name
value - the value
Throws:
ValidationException

changeSessionIdentifier

public javax.servlet.http.HttpSession changeSessionIdentifier()
                                                       throws AuthenticationException
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 getCurrentRequest() to obtain the current HttpSession object

Returns:
the new http session
Throws:
EnterpriseSecurityException - the enterprise security exception
AuthenticationException

verifyCSRFToken

public void verifyCSRFToken()
                     throws IntrusionException
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 getCurrentRequest() to obtain the current url

Throws:
IntrusionException

decryptHiddenField

public java.lang.String decryptHiddenField(java.lang.String encrypted)
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) ?


setRememberToken

public java.lang.String setRememberToken(java.lang.String password,
                                         int maxAge,
                                         java.lang.String domain,
                                         java.lang.String path)
Set a cookie containing the current User's remember me token for automatic authentication. The use of remember me tokens is generally not recommended, but this method will help do it as safely as possible. The user interface should strongly warn the user that this should only be enabled on computers where no other users will have access.

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

encryptHiddenField

public java.lang.String encryptHiddenField(java.lang.String value)
                                    throws EncryptionException
Encrypts a hidden field value for use in HTML.

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
Takes a querystring (i.e. everything after the ? in the URL) and returns an encrypted string containing the parameters.

Returns:
FIXME RD: What value does this offer over Encryptor.encrypt(String) ?
Throws:
EncryptionException

decryptQueryString

public java.util.Map decryptQueryString(java.lang.String encrypted)
                                 throws EncryptionException
Takes an encrypted querystring and returns a Map containing the original parameters.

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

getCookie

public java.lang.String getCookie(java.lang.String name)
Returns the first cookie matching the given name. This method uses getCurrentRequest() to obtain the HttpServletRequest object


getSafeFileUploads

public java.util.List getSafeFileUploads(java.io.File tempDir,
                                         java.io.File finalDir)
                                  throws ValidationException
Extract uploaded files from a multipart HTTP requests. Implementations must check the content to ensure that it is safe before making a permanent copy on the local filesystem. Checks should include length and content checks, possibly virus checking, and path and name checks. Refer to the file checking methods in Validator for more information. This method uses getCurrentRequest() to obtain the HttpServletRequest object

Parameters:
tempDir - the temp dir
finalDir - the final dir
Returns:
List of new File objects from upload
Throws:
ValidationException - the validation exception

decryptStateFromCookie

public java.util.Map decryptStateFromCookie()
                                     throws EncryptionException
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

Throws:
EncryptionException

killAllCookies

public void killAllCookies()
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 getCurrentRequest() to obtain the HttpServletRequest object This method uses getCurrentResponse() to obtain the HttpServletRequest object


killCookie

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

Parameters:
name - the cookie name

encryptStateInCookie

public void encryptStateInCookie(java.util.Map cleartext)
                          throws EncryptionException
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 getCurrentResponse() to obtain the HttpServletResponse object

Throws:
EncryptionException

safeSendRedirect

public void safeSendRedirect(java.lang.String context,
                             java.lang.String location)
                      throws java.io.IOException
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 getCurrentResponse() to obtain the HttpServletResponse object

Parameters:
context -
location - the URL to redirect to
Throws:
java.io.IOException - Signals that an I/O exception has occurred.

safeSendForward

public void safeSendForward(java.lang.String context,
                            java.lang.String location)
                     throws AccessControlException,
                            javax.servlet.ServletException,
                            java.io.IOException
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 getCurrentResponse() to obtain the HttpServletResponse object

Parameters:
context -
location -
Throws:
AccessControlException
javax.servlet.ServletException
java.io.IOException

safeSetContentType

public void safeSetContentType()
Sets the content type on each HTTP response, to help protect against cross-site scripting attacks and other types of injection into HTML documents. This method uses getCurrentResponse() to obtain the HttpServletResponse object


setNoCacheHeaders

public void setNoCacheHeaders()
Set headers to protect sensitive information against being cached in the browser. Developers should make this call for any HTTP responses that contain any sensitive data that should not be cached within the browser or any intermediate proxies or caches. Implementations should set headers for the expected browsers. The safest approach is to set all relevant headers to their most restrictive setting. These include:
 
 Cache-Control: no-store
Cache-Control: no-cache
Cache-Control: must-revalidate
Expires: -1
Note that the header "pragma: no-cache" is only useful in HTTP requests, not HTTP responses. So even though there are many articles recommending the use of this header, it is not helpful for preventing browser caching. For more information, please refer to the relevant standards: This method uses getCurrentResponse() to obtain the HttpServletResponse object


setCurrentHTTP

public 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)

Parameters:
request - the current request
response - the current response

getCurrentRequest

public javax.servlet.http.HttpServletRequest getCurrentRequest()
Retrieves the current HttpServletRequest

Returns:
the current request

getCurrentResponse

public javax.servlet.http.HttpServletResponse getCurrentResponse()
Retrieves the current HttpServletResponse

Returns:
the current response

logHTTPRequest

public void logHTTPRequest(Logger logger)
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 getCurrentRequest() to obtain the HttpServletRequest object

Parameters:
logger - the logger to write the request to

logHTTPRequest

public void logHTTPRequest(Logger logger,
                           java.util.List parameterNamesToObfuscate)
Format the Source IP address, URL, URL parameters, and all form parameters into a string suitable for the log file. The list of parameters to obfuscate should be specified in order to prevent sensitive information from being logged. If a null list is provided, then all parameters will be logged. If HTTP request logging is done in a central place, the parameterNamesToObfuscate could be made a configuration parameter. We include it here in case different parts of the application need to obfuscate different parameters. This method uses getCurrentResponse() to obtain the HttpServletResponse object

Parameters:
logger - the logger to write the request to
parameterNamesToObfuscate - the sensitive params