Difference between revisions of "Session Management"

From OWASP
Jump to: navigation, search
(Ensuring That Session Re-writing is Off)
(Page and Form Tokens: AUTOCOMPLETE=OFF)
(32 intermediate revisions by 3 users not shown)
Line 4: Line 4:
  
 
To ensure that:
 
To ensure that:
* authenticated users have a robust and cryptographically secure association with their session
+
* authenticated users have a robust and cryptographically secure association with their session.
* applications enforce authorization checks
+
* applications avoid or prevent common web attacks, such as replay, request forging and man-in-the-middle
+
  
 
==Environments Affected==
 
==Environments Affected==
Line 17: Line 15:
  
 
==Architectural Goals==
 
==Architectural Goals==
All applications should take into account the following architectural and detailed design goals:
+
===Things To Do===
 +
All applications in your organization should be developed following these design goals:
  
* All applications within your organization should share a well-debugged and trusted session management mechanism.
+
* All applications should share a well-debugged and trusted session management mechanism.
 
* All session identifiers should be sufficiently randomized so as to not be guessable.
 
* All session identifiers should be sufficiently randomized so as to not be guessable.
 
* All session identifiers should use a key space of at least XXXX bits.  
 
* All session identifiers should use a key space of at least XXXX bits.  
Line 28: Line 27:
 
* All applications SHOULD use a cryptographically secure page or form nonce in a hidden form field.
 
* All applications SHOULD use a cryptographically secure page or form nonce in a hidden form field.
 
* Each form or page nonce SHOULD be removed from the active list as soon as it is submitted.
 
* Each form or page nonce SHOULD be removed from the active list as soon as it is submitted.
* Applications should force users to re-authenticate before viewing high-value resources or complete high-value transactions.
+
* Session ID values submitted by the client should undergo the same validation checks as other request parameters.
* Session tokens should be regenerated prior to any significant transaction
+
* High value applications SHOULD force users to re-authenticate before viewing high-value resources or complete high-value transactions.
* Session tokens should be regenerated after a certain number of requests
+
* Session tokens should be regenerated prior to any significant high value transaction.
* Session tokens should be regenerated after a certain period of time
+
* In high-value applications, session tokens should be regenerated after a certain number of requests.
 +
* In high-value applications, session tokens should be regenerated after a certain period of time.
 +
* For all applications, session tokens should be regenerated after a change in user privilege.
 
* Applications should log attempts to continue sessions based on invalid session identifiers.
 
* Applications should log attempts to continue sessions based on invalid session identifiers.
* Applications should, if possible, conduct all traffic over HTTPS. Applications MUST use an additional session identifier for HTTPS communications  
+
* Applications should, if possible, conduct all traffic over HTTPS.  
 +
* If applications use both HTTP and HTTPS, they MUST regenerate the identifier or use an additional session identifier for HTTPS communications.
  
Things not to do:
+
===Things Not To Do===
* Applications should NOT use as variables any user personal information (user name, password, home address, etc.)
+
* Applications should NOT use as variables any user personal information (user name, password, home address, etc.).
 
* Highly protected applications should not implement mechanisms that make automated requests to prevent session timeouts.
 
* Highly protected applications should not implement mechanisms that make automated requests to prevent session timeouts.
 
* Highly protected applications should not implement "remember me" functionality.
 
* Highly protected applications should not implement "remember me" functionality.
 +
* Highly protected applications should not use URL rewriting to maintain state when cookies are turned off on the client.
 
* Applications should NOT use session identifiers for encrypted HTTPS transport that have once been used over HTTP.
 
* Applications should NOT use session identifiers for encrypted HTTPS transport that have once been used over HTTP.
 +
 
==Use Only the Framework's Session Manager==
 
==Use Only the Framework's Session Manager==
  
The ability to restrict and maintain user actions within unique sessions is critical to web security.  Most users of this guide will be using an application framework with built in session management capabilities. others will use languages such as Perl CGI that do not. They are at an immediate disadvantage as the developers may be forced to create a session management scheme from scratch. These implementations are often weak and breakable.  Developers are strongly discouraged from implementing their own Session Management.  Leading web frameworks have undergone rounds of testing and fixing that leave them using secure methods of token generation.  There is no value in re-writing such basic building blocks.
+
The ability to restrict and maintain user actions within unique sessions is critical to web security.  Most users of this guide will be using an application framework with built in session management capabilities. Others will use languages such as Perl CGI that do not. Those without a built in session management system and those who override the existing session management systems are at an immediate disadvantage. Implementations built from scratch are often weak and breakable.  Developers are strongly discouraged from implementing their own Session Management.  Leading web frameworks have undergone rounds of testing and fixing that leave them using secure methods of token generation.  There is no value in re-writing such basic building blocks.
  
Another common mistake is to implement a weak session management scheme on top of a strong one.  
+
In spite of the maturity of many of these frameworks, research continues into making them more secure.  Therefore, application developers and web masters must maintain the latest versions and patches to application frameworks to ensure that the newest and most secure version is in use.
  
A session handler must issue tokens which are unpredictable and large enough to be unguessable. Session tokens should be user unique, non-predictable, and resistant to reverse engineering.
+
===Cryptographically Strong===
 +
 
 +
A key feature of any session handler is the cryptographic strength of the session token or session ID.  A session handler must issue tokens which are unpredictable and large enough to be unguessable. Session tokens should be user unique, non-predictable, and resistant to reverse engineering. A trusted source of randomness must be used to generate the session tokens.
 +
 
 +
===Appropriate Key Space===
 +
 
 +
Even cryptographically secure algorithms allow an active session token to be easily determined if the keyspace of the token is not sufficiently large. Attackers can essentially "grind" through most possibilities in the token's key space with automated brute-force scripts. A token's key space should be sufficiently large enough to prevent these types of brute force attacks, keeping in mind that computation and bandwidth capacity increases will make these requirements change over time.
 +
 
 +
===Session Identifier Entropy===
 +
 
 +
The session identifier should use the largest character set available to it. If a session identifier is made up of say 8 characters of 7 bits the effective key length is 56 bits. However if the character set is made up of only integers that can be represented in 4 bits giving a key space of only 32 bits. A good session identifier should use as many characters as possible. Exceptions to this can be made, however, for special control characters that would require escaping and thus complicate development. Most application frameworks use the characters A-Z and 0-9 and some add case sensitivity by including a-z.
 +
 
 +
==Validate SessionID values coming from clients==
 +
All input from clients should be encoded and validated.  Many frameworks validate and encode GET and POST parameters, but fail to adequately encode sessionID values inside of cookies as submitted from the client.
 +
The ESAPI code uses an ESAPI method to clean sessionID values:
 +
public String getRequestedSessionId() {
 +
      String id = request.getRequestedSessionId();
 +
      String clean = "";
 +
      try {
 +
        clean = ESAPI.validator().getValidInput( "Requested cookie: " + id, id, "HTTPJSESSIONID", 50, false );
 +
      } catch (ValidationException e ) {
 +
        // already logged
 +
      }
 +
        return clean;
 +
  }
  
 
==Ensure Idle, absolute timeouts are as short as practical==
 
==Ensure Idle, absolute timeouts are as short as practical==
 +
 +
Sessions must have a limited lifetime and expire after a period of time based on business and usability requirements balanced with security considerations.  The application should be able to measure the period of inactivity for a session and expire it, destroying the session and overwriting the session cookie.  (See the logout section).
 +
 
==Store privileged State only on Trusted Devices==
 
==Store privileged State only on Trusted Devices==
 
A trusted device is defined as...
 
A trusted device is defined as...
Line 82: Line 113:
 
  }
 
  }
  
==Rotate Session IDs==
+
==Rotate Session Identifiers==
For high value sites, session IDs or tokens should be regenerated prior to any significant transaction, after a certain period of time and after a certain number of requests.
+
For high value sites, session identifiers should be regenerated prior to any significant transaction, after a certain period of time and after a certain number of requests.
For medium and low value sites,  Token regeneration should be performed after a change in user privilege, such as moving from an anonymous visitor to a logged in user or moving from a logged in user to an administrator.
+
For medium and low value sites,  Token regeneration should be performed after a change in user privilege, such as moving from an anonymous visitor to a logged in user or moving from a logged in user to an administrator
 +
If a user is moving from an insecure page on the site to a more secure section of the site that uses HTTPS, the session ID should also be regenerated so that the secure session ID has never been transmitted in an unencrypted state.  An additional session ID might be used instead of regenerating the original session ID.
 
Unless this capability is built in to the application framework, it must implemented in addition to the application framework session controls. The prior recommendations about first leveraging platform security mechanisms still apply – because this control measure often includes writing additional custom code for an application the application should require the application framework session management features to be in operation as well as this additional rotating session identifier.   
 
Unless this capability is built in to the application framework, it must implemented in addition to the application framework session controls. The prior recommendations about first leveraging platform security mechanisms still apply – because this control measure often includes writing additional custom code for an application the application should require the application framework session management features to be in operation as well as this additional rotating session identifier.   
 
   
 
   
A code example from ESAPI for regenerating session tokens:
+
===Using ESAPI reference code to regenerate session identifiers===
  
 
  public HttpSession changeSessionIdentifier(HttpServletRequest request) throws AuthenticationException {
 
  public HttpSession changeSessionIdentifier(HttpServletRequest request) throws AuthenticationException {
Line 116: Line 148:
 
  }
 
  }
  
==Protect Session Tokens==
+
==Protect Session Identifiers==
 
If possible, the application should conduct all web traffic using HTTPS. If this is not possible, the application should, at minimum protect sensitive content and pages used to engage in sensitive transactions with HTTPS. If HTTPS is not used to protect the entire web session an additional session identifier should be incorporated that is only transferred over HTTPS. Additional application level checks for HTTPS pages should verify that this session identifier has been provided and matches the normal session being managed by the web or application server.
 
If possible, the application should conduct all web traffic using HTTPS. If this is not possible, the application should, at minimum protect sensitive content and pages used to engage in sensitive transactions with HTTPS. If HTTPS is not used to protect the entire web session an additional session identifier should be incorporated that is only transferred over HTTPS. Additional application level checks for HTTPS pages should verify that this session identifier has been provided and matches the normal session being managed by the web or application server.
  
If URL parameters must be used to store and transmit session identifiers, use POST requests for all requests to the server. This can make seemingly simple operations such as linking to pages in an application complicated so the use of browser cookies is typically preferable for session state maintenance tokens.
+
If URL parameters must be used to store and transmit session identifiers, use POST requests for all requests to the server. This can make seemingly simple operations such as linking to pages in an application complicated so the use of browser cookies is typically preferable for session state maintenance identifiers.
 +
 
 +
If Cookies are used to store and transmit session identifiers over HTTPS they should be marked as 'Secure' so that they are not served over non-SSL tunnels.
  
 
Provide an explicit way for users to log out of the application and ensure that this log out routine explicitly expires and destroys the session. See the logout section for more detail.
 
Provide an explicit way for users to log out of the application and ensure that this log out routine explicitly expires and destroys the session. See the logout section for more detail.
  
 
==Associating Session Information With IP Address==
 
==Associating Session Information With IP Address==
Associating web application sessions with IP addresses would increase security for many applications. Request handlers could be added to applications that would check the IP address of incoming requests and either invalidate the session or at least log the anomaly if the IP address associated with the session changes. It should be noted that depending on the network infrastructure between the web application client and server this may not be an acceptable solution. Some Internet service providers route traffic on their network such that the apparent client IP address might change during the course of a valid session. In addition, NAT firewalls and other technologies might mask when a host performing attacks has attempted to hijack a session. These concerns limit the utility and applicability of IP to session binding for Internet-accessible web applications.  
+
Associating web application sessions with IP addresses would increase security for many applications. Request handlers could be added to applications that would check the IP address of incoming requests and either invalidate the session or at least log the anomaly if the IP address associated with the session changes. It should be noted that depending on the network infrastructure between the web application client and server this may not be an acceptable solution. The following cases might make this feature either difficult to implement because of their impact to users or, even, irrelevant:
 +
 
 +
<ul>
 +
 
 +
<li>Some Internet service providers route traffic on their network such that the apparent client IP address might change during the course of a valid session.
 +
 
 +
<li>Some Internet service providers users access the Internet through clusters of transparent proxies such that the client IP address could change if a user is load balanced to a different proxy through its session.
 +
 
 +
<li>Some mobile users might vary their IP address when switching from wireless to wired connections and viceversa.
 +
 
 +
<li>NAT firewalls, proxies and other technologies might mask when a host performing attacks has attempted to hijack a session.  
 +
</ul>
 +
 
 +
These concerns limit the utility and applicability of IP to session binding for Internet-accessible web applications.
 +
 
 +
==Associating Session Information with SSL information==
 +
 
 +
To increase the security of sessions the session information can also be associated with information related to a SSL session so that reuse of the identifier would be rejected if this information changed. This can be done by using the client's public certificate or the client SSL identifier:
 +
 
 +
<ul>
 +
<li>Client public certificate: this solution is only possible for applications that require the use of client certificates. Since this value should never vary throughout a session (even if the user changed IP addresses or renegotiated the SSL tunnel) the reuse of session information would only be possible if a malicious attacker also were in possession of the client's SSL certificate.
 +
 
 +
<li>SSL identifier: this solution is possible for all SSL-enable applications and prevents session reuse. However, some browsers (notably, old ones) might renegotiate SSL tunnels throughout a user session which would automatically make the user session invalid.
 +
 
 +
<!-- Note: The case described above is IE 5.x in Windows NT 4.0 and other (old) Windows platforms, which regenerate SSL tunnels every two minutes for more information see http://support.microsoft.com/kb/265369/en-us -->
 +
 
 +
</ul>
  
 
==Ensuring That Session Re-writing is Off==
 
==Ensuring That Session Re-writing is Off==
Many web application frameworks fall back on rewriting URLs to include session IDs in the URL when session cookies are not allowed.  If URL parameters must be used to store and transmit session identifiers, use POST requests for all requests to the server. This can make seemingly simple operations such as linking to pages in an application complicated so the use of browser cookies is typically preferable for session state maintenance tokens. For high value sites, application developers MUST ensure that session rewriting is turned off.  Session re-writing is acceptable only for low value sites.
+
Many web application frameworks fall back on rewriting URLs to include session Identifiers in the URL when session cookies are not allowed.  If URL parameters must be used to store and transmit session identifiers, use POST requests for all requests to the server. This can make seemingly simple operations such as linking to pages in an application complicated.  Therefore, the use of browser cookies is typically preferable for session state maintenance. For high value sites, application developers MUST ensure that session rewriting is turned off.  Session re-writing is acceptable only for low value sites.
 +
ESAPI code overwrites the URLEncode and URLRedirectEncode methods of the HTTPServletRequest class to prevent this default behavior:
 +
public String encodeRedirectURL(String url) {
 +
    return url;
 +
}
  
 
==Ensure That Session Failures are properly logged==
 
==Ensure That Session Failures are properly logged==
 
Many web applications have restrictions against unrestrained password guessing. Incorrect attempts at a login will be logged.  It is much less common for web applications or network infrastructure to detect and log repeated attempts to continue sessions based on guessed session identifiers. Application servers rarely log or audit attempts to continue sessions based on invalid session identifiers and network intrusion detection systems rarely have signatures to look for this sort of traffic.  Consider adding handlers to the application that would validate that log when certain IP addresses make excessive attempts to continue sessions based on invalid or expired session identifiers.
 
Many web applications have restrictions against unrestrained password guessing. Incorrect attempts at a login will be logged.  It is much less common for web applications or network infrastructure to detect and log repeated attempts to continue sessions based on guessed session identifiers. Application servers rarely log or audit attempts to continue sessions based on invalid session identifiers and network intrusion detection systems rarely have signatures to look for this sort of traffic.  Consider adding handlers to the application that would validate that log when certain IP addresses make excessive attempts to continue sessions based on invalid or expired session identifiers.
  
==Ensure That Session Ids are never logged==
+
==Ensure That Session Identifiers are never logged==
 +
 
 +
==Page and Form Tokens==
 +
 
 +
Page specific tokens or "nonces" may be used in conjunction with session specific tokens to provide a measure of authenticity when dealing with client requests. Used in conjunction with transport layer security mechanisms, page tokens can aide in ensuring that the client on the other end of the session is indeed the same client that requested the last page in a given session. Page tokens can be stored in cookies or more likely in query strings and should be completely random. It is possible to avoid sending session token information to the client entirely through the use of page tokens, by creating a mapping between them on the server side, this technique should further increase the difficulty in brute forcing session authentication tokens.
 +
 
 +
==Prevent Sensitive Data from Being Cached on Client Side==
 +
Caching of form fields is present in most browsers. For form fields containing sensitive information - like credit card numbers - autocomplete should be disabled using AUTOCOMPLETE=OFF attribute that can be used in every INPUT tag[http://msdn.microsoft.com/en-us/library/ms533486%28VS.85%29.aspx]. This feature will fail validation against current versions of HTML specifications, it's now supported by most browsers though.
 +
 
 +
<INPUT TYPE="password" AUTOCOMPLETE="off">
  
 
==References==
 
==References==
Line 139: Line 212:
 
* OWASP Testing Guide [[Testing for Session Management]]
 
* OWASP Testing Guide [[Testing for Session Management]]
 
* OWASP Code Review Guide [[Reviewing Code for Session Integrity issues]]
 
* OWASP Code Review Guide [[Reviewing Code for Session Integrity issues]]
* David Endler, "Brute-Force Exploitation of Web Application Session IDs" [http://downloads.securityfocus.com/library/SessionIDs.pdf]
+
* David Endler, "Brute-Force Exploitation of Web Application Session IDs" [http://downloads.securityfocus.com/library/SessionIDs.pdf]  [[category:FIXME|broken link]]
 
* Ruby CGI::Session creates session files insecurely [http://www.securityfocus.com/advisories/7143]
 
* Ruby CGI::Session creates session files insecurely [http://www.securityfocus.com/advisories/7143]
 
* Ollmann, Gunter, “Web Based Session Management: Best Practices in Managing HTTP Based Client Sessions” [http://www.technicalinfo.net/papers/WebBasedSessionManagement.html]
 
* Ollmann, Gunter, “Web Based Session Management: Best Practices in Managing HTTP Based Client Sessions” [http://www.technicalinfo.net/papers/WebBasedSessionManagement.html]
Line 159: Line 232:
 
===How to Test for Session Management Vulnerabilities===
 
===How to Test for Session Management Vulnerabilities===
  
See the [[:Category:OWASP Testing Project|OWASP Testing Guide]] article on how to [[Testing for Session Management Schema|Test for Session Management]] Vulnerabilities.
+
See the [[:Category:OWASP Testing Project|OWASP Testing Guide]] article on how to [[Testing for Session Management|Test for Session Management]] Vulnerabilities.
  
 
===How to Review Code for Session Management| Vulnerabilities===
 
===How to Review Code for Session Management| Vulnerabilities===

Revision as of 04:19, 9 October 2009

Development Guide Table of Contents

Contents


Objective

To ensure that:

  • authenticated users have a robust and cryptographically secure association with their session.

Environments Affected

All.

Relevant COBIT Topics

  • PO8 – All sections should be reviewed
  • PO8.4 – Privacy, Intellectual property and data flow

Architectural Goals

Things To Do

All applications in your organization should be developed following these design goals:

  • All applications should share a well-debugged and trusted session management mechanism.
  • All session identifiers should be sufficiently randomized so as to not be guessable.
  • All session identifiers should use a key space of at least XXXX bits.
  • All session identifiers should use the largest character set available to it.
  • Sessions SHOULD timeout after 5 minutes for high-value applications, 10 minutes for medium value applications, and 20 minutes for low risk applications.
  • All session tokens in high value applications SHOULD be tied to a specific HTTP client instance (session identifier and IP address).
  • Application servers SHOULD use private temporary file areas per client/application to store session data.
  • All applications SHOULD use a cryptographically secure page or form nonce in a hidden form field.
  • Each form or page nonce SHOULD be removed from the active list as soon as it is submitted.
  • Session ID values submitted by the client should undergo the same validation checks as other request parameters.
  • High value applications SHOULD force users to re-authenticate before viewing high-value resources or complete high-value transactions.
  • Session tokens should be regenerated prior to any significant high value transaction.
  • In high-value applications, session tokens should be regenerated after a certain number of requests.
  • In high-value applications, session tokens should be regenerated after a certain period of time.
  • For all applications, session tokens should be regenerated after a change in user privilege.
  • Applications should log attempts to continue sessions based on invalid session identifiers.
  • Applications should, if possible, conduct all traffic over HTTPS.
  • If applications use both HTTP and HTTPS, they MUST regenerate the identifier or use an additional session identifier for HTTPS communications.

Things Not To Do

  • Applications should NOT use as variables any user personal information (user name, password, home address, etc.).
  • Highly protected applications should not implement mechanisms that make automated requests to prevent session timeouts.
  • Highly protected applications should not implement "remember me" functionality.
  • Highly protected applications should not use URL rewriting to maintain state when cookies are turned off on the client.
  • Applications should NOT use session identifiers for encrypted HTTPS transport that have once been used over HTTP.

Use Only the Framework's Session Manager

The ability to restrict and maintain user actions within unique sessions is critical to web security. Most users of this guide will be using an application framework with built in session management capabilities. Others will use languages such as Perl CGI that do not. Those without a built in session management system and those who override the existing session management systems are at an immediate disadvantage. Implementations built from scratch are often weak and breakable. Developers are strongly discouraged from implementing their own Session Management. Leading web frameworks have undergone rounds of testing and fixing that leave them using secure methods of token generation. There is no value in re-writing such basic building blocks.

In spite of the maturity of many of these frameworks, research continues into making them more secure. Therefore, application developers and web masters must maintain the latest versions and patches to application frameworks to ensure that the newest and most secure version is in use.

Cryptographically Strong

A key feature of any session handler is the cryptographic strength of the session token or session ID. A session handler must issue tokens which are unpredictable and large enough to be unguessable. Session tokens should be user unique, non-predictable, and resistant to reverse engineering. A trusted source of randomness must be used to generate the session tokens.

Appropriate Key Space

Even cryptographically secure algorithms allow an active session token to be easily determined if the keyspace of the token is not sufficiently large. Attackers can essentially "grind" through most possibilities in the token's key space with automated brute-force scripts. A token's key space should be sufficiently large enough to prevent these types of brute force attacks, keeping in mind that computation and bandwidth capacity increases will make these requirements change over time.

Session Identifier Entropy

The session identifier should use the largest character set available to it. If a session identifier is made up of say 8 characters of 7 bits the effective key length is 56 bits. However if the character set is made up of only integers that can be represented in 4 bits giving a key space of only 32 bits. A good session identifier should use as many characters as possible. Exceptions to this can be made, however, for special control characters that would require escaping and thus complicate development. Most application frameworks use the characters A-Z and 0-9 and some add case sensitivity by including a-z.

Validate SessionID values coming from clients

All input from clients should be encoded and validated. Many frameworks validate and encode GET and POST parameters, but fail to adequately encode sessionID values inside of cookies as submitted from the client. The ESAPI code uses an ESAPI method to clean sessionID values:

public String getRequestedSessionId() {
     String id = request.getRequestedSessionId();
     String clean = "";
     try {
        clean = ESAPI.validator().getValidInput( "Requested cookie: " + id, id, "HTTPJSESSIONID", 50, false );
     } catch (ValidationException e ) {
        // already logged
     }
       return clean;
 }

Ensure Idle, absolute timeouts are as short as practical

Sessions must have a limited lifetime and expire after a period of time based on business and usability requirements balanced with security considerations. The application should be able to measure the period of inactivity for a session and expire it, destroying the session and overwriting the session cookie. (See the logout section).

Store privileged State only on Trusted Devices

A trusted device is defined as...

Destroy Sessions on Logout

Applications should invalidate and ideally remove the session identification token after a user logout. Cookies are often associated with the life of a browser window. If a user logs out of your application on a shared workstation such as an Internet kiosk and a subsequent user attempts to access the same application, the second user must not get the same session identifier token as the first. To implement this, the application should over write session cookies and explicitly expire and destroy the session on logout.

Destroying sessions on logout using ESAPI reference code

public void logout() {
     ESAPI.httpUtilities().killCookie( ESAPI.currentRequest(), ESAPI.currentResponse(), HTTPUtilities.REMEMBER_TOKEN_COOKIE_NAME );
               
     HttpSession session = ESAPI.currentRequest().getSession(false);
     if (session != null) {
          session.invalidate();
     }
     ESAPI.httpUtilities().killCookie(ESAPI.currentRequest(), ESAPI.currentResponse(), "JSESSIONID");
     loggedIn = false;
     logger.info(Logger.SECURITY, "Logout successful" );
     ESAPI.authenticator().setCurrentUser(User.ANONYMOUS);
}

The killCookie method properly overwrites the existing cookie:

public void killCookie(HttpServletRequest request, HttpServletResponse response, String name) {
     String path = "//";
     String domain="";
     Cookie cookie = ESAPI.httpUtilities().getCookie(request, name);
     if ( cookie != null ) {
          path = cookie.getPath();
          domain = cookie.getDomain();
     }
     SafeResponse safeResponse = new SafeResponse( response );
     safeResponse.addCookie(name, "deleted", 0, domain, path);
}

Rotate Session Identifiers

For high value sites, session identifiers should be regenerated prior to any significant transaction, after a certain period of time and after a certain number of requests. For medium and low value sites, Token regeneration should be performed after a change in user privilege, such as moving from an anonymous visitor to a logged in user or moving from a logged in user to an administrator. If a user is moving from an insecure page on the site to a more secure section of the site that uses HTTPS, the session ID should also be regenerated so that the secure session ID has never been transmitted in an unencrypted state. An additional session ID might be used instead of regenerating the original session ID. Unless this capability is built in to the application framework, it must implemented in addition to the application framework session controls. The prior recommendations about first leveraging platform security mechanisms still apply – because this control measure often includes writing additional custom code for an application the application should require the application framework session management features to be in operation as well as this additional rotating session identifier.

Using ESAPI reference code to regenerate session identifiers

public HttpSession changeSessionIdentifier(HttpServletRequest request) throws AuthenticationException {
                
     // get the current session
     HttpSession session = request.getSession();
               
     // make a copy of the session content
     Map temp = new HashMap();
     Enumeration e = session.getAttributeNames();
     while (e != null && e.hasMoreElements()) {
          String name = (String) e.nextElement();
          Object value = session.getAttribute(name);
          temp.put(name, value);
     }

     // kill the old session and create a new one
     session.invalidate();
     HttpSession newSession = request.getSession();

     // copy back the session content
     Iterator i = temp.entrySet().iterator();
     while (i.hasNext()) {
          Map.Entry entry = (Map.Entry) i.next();
          newSession.setAttribute((String) entry.getKey(), entry.getValue());
     }
     return newSession;
}

Protect Session Identifiers

If possible, the application should conduct all web traffic using HTTPS. If this is not possible, the application should, at minimum protect sensitive content and pages used to engage in sensitive transactions with HTTPS. If HTTPS is not used to protect the entire web session an additional session identifier should be incorporated that is only transferred over HTTPS. Additional application level checks for HTTPS pages should verify that this session identifier has been provided and matches the normal session being managed by the web or application server.

If URL parameters must be used to store and transmit session identifiers, use POST requests for all requests to the server. This can make seemingly simple operations such as linking to pages in an application complicated so the use of browser cookies is typically preferable for session state maintenance identifiers.

If Cookies are used to store and transmit session identifiers over HTTPS they should be marked as 'Secure' so that they are not served over non-SSL tunnels.

Provide an explicit way for users to log out of the application and ensure that this log out routine explicitly expires and destroys the session. See the logout section for more detail.

Associating Session Information With IP Address

Associating web application sessions with IP addresses would increase security for many applications. Request handlers could be added to applications that would check the IP address of incoming requests and either invalidate the session or at least log the anomaly if the IP address associated with the session changes. It should be noted that depending on the network infrastructure between the web application client and server this may not be an acceptable solution. The following cases might make this feature either difficult to implement because of their impact to users or, even, irrelevant:

  • Some Internet service providers route traffic on their network such that the apparent client IP address might change during the course of a valid session.
  • Some Internet service providers users access the Internet through clusters of transparent proxies such that the client IP address could change if a user is load balanced to a different proxy through its session.
  • Some mobile users might vary their IP address when switching from wireless to wired connections and viceversa.
  • NAT firewalls, proxies and other technologies might mask when a host performing attacks has attempted to hijack a session.

These concerns limit the utility and applicability of IP to session binding for Internet-accessible web applications.

Associating Session Information with SSL information

To increase the security of sessions the session information can also be associated with information related to a SSL session so that reuse of the identifier would be rejected if this information changed. This can be done by using the client's public certificate or the client SSL identifier:

  • Client public certificate: this solution is only possible for applications that require the use of client certificates. Since this value should never vary throughout a session (even if the user changed IP addresses or renegotiated the SSL tunnel) the reuse of session information would only be possible if a malicious attacker also were in possession of the client's SSL certificate.
  • SSL identifier: this solution is possible for all SSL-enable applications and prevents session reuse. However, some browsers (notably, old ones) might renegotiate SSL tunnels throughout a user session which would automatically make the user session invalid.

Ensuring That Session Re-writing is Off

Many web application frameworks fall back on rewriting URLs to include session Identifiers in the URL when session cookies are not allowed. If URL parameters must be used to store and transmit session identifiers, use POST requests for all requests to the server. This can make seemingly simple operations such as linking to pages in an application complicated. Therefore, the use of browser cookies is typically preferable for session state maintenance. For high value sites, application developers MUST ensure that session rewriting is turned off. Session re-writing is acceptable only for low value sites. ESAPI code overwrites the URLEncode and URLRedirectEncode methods of the HTTPServletRequest class to prevent this default behavior:

public String encodeRedirectURL(String url) {
    return url;
}

Ensure That Session Failures are properly logged

Many web applications have restrictions against unrestrained password guessing. Incorrect attempts at a login will be logged. It is much less common for web applications or network infrastructure to detect and log repeated attempts to continue sessions based on guessed session identifiers. Application servers rarely log or audit attempts to continue sessions based on invalid session identifiers and network intrusion detection systems rarely have signatures to look for this sort of traffic. Consider adding handlers to the application that would validate that log when certain IP addresses make excessive attempts to continue sessions based on invalid or expired session identifiers.

Ensure That Session Identifiers are never logged

Page and Form Tokens

Page specific tokens or "nonces" may be used in conjunction with session specific tokens to provide a measure of authenticity when dealing with client requests. Used in conjunction with transport layer security mechanisms, page tokens can aide in ensuring that the client on the other end of the session is indeed the same client that requested the last page in a given session. Page tokens can be stored in cookies or more likely in query strings and should be completely random. It is possible to avoid sending session token information to the client entirely through the use of page tokens, by creating a mapping between them on the server side, this technique should further increase the difficulty in brute forcing session authentication tokens.

Prevent Sensitive Data from Being Cached on Client Side

Caching of form fields is present in most browsers. For form fields containing sensitive information - like credit card numbers - autocomplete should be disabled using AUTOCOMPLETE=OFF attribute that can be used in every INPUT tag[1]. This feature will fail validation against current versions of HTML specifications, it's now supported by most browsers though.

<INPUT TYPE="password" AUTOCOMPLETE="off">

References

Old Version

Development Guide Table of Contents

Related Security Activities

See the OWASP articles on Session Management Vulnerabilities.

Description of Session Management Countermeasures

See the OWASP articles on Session Management Countermeasures.

How to Test for Session Management Vulnerabilities

See the OWASP Testing Guide article on how to Test for Session Management Vulnerabilities.

How to Review Code for Session Management| Vulnerabilities

See the OWASP Code Review Guide article on how to Review Code for Session Management Vulnerabilities.


Objective

To ensure that:

  • authenticated users have a robust and cryptographically secure association with their session
  • applications enforce authorization checks
  • applications avoid or prevent common web attacks, such as replay, request forging and man-in-the-middle

Environments Affected

All.

Relevant COBIT Topics

  • PO8 – All sections should be reviewed
  • PO8.4 – Privacy, Intellectual property and data flow

Description

Thick client applications innately store local data ("state") in memory allocated by the operating system for the duration of the program's run. With web applications, the web server serves pages in response to thin-client browser requests. By design, HTTP and HTTPS are stateless protocols that do not natively maintain a consistent connection between the client browser and the server software.

This is acceptable in situations where the web server needs only serve static content such as a brochure or image. However, non-trivial web applications do require that user state be maintained over the course of a user session so that subsequent requests can be processed based on previous actions. A basic example is an e-commerce application where the user must maintain a shopping cart across multiple requests to select items for purchase and then enter the information necessary to “check out” and complete the order.

In order to allow the construction of dynamic, data-driven applications all modern web application frameworks (such as J2EE and ASP.NET) provide facilities to maintain the identity of a user across multiple requests. This is typically implemented by the use of browser cookies; the server generates what should be a unique and difficult-to-guess identity value for the user session and returns that to the user in the form of a browser cookie. When the browser returns this cookie value in subsequent requests, the server is able to associate those requests with all others in the session. Once users have authenticated themselves to the application, their identities can also be associated with the user session and used to make authorization decisions when accessing resources or actions. The ability to restrict and maintain user actions within unique sessions is critical to web security.

Although most users of this Development Guide will be using an application framework with built in session management capabilities, others will use languages such as Perl CGI that do not. They are at an immediate disadvantage as the developers may be forced to create a session management scheme from scratch. These implementations are often weak and breakable – as always it is preferable to use well-tested framework code versus custom code written specifically for a project. It is theoretically possible to write and use a cryptographically secure session management scheme, which is the focus of this chapter. However, for almost all applications, it cannot be stressed highly enough to use an application framework which has adequate session management built in.

Application frameworks such as J2EE, PHP, ASP and ASP.NET take care of much of the low level session management details and allow fine level control at a programmatic level, rather than at a server configuration level. These application frameworks have facilities for generating unique, hard-to-guess session identifiers as well as built-in capabilities to expire sessions after periods of inactivity.for more information Related to Session in asp.net visit Media:http://msdn2.microsoft.com/en-us/library/aa479041.aspx

Best practices

For session management the best practice is to use a robust, well-known session manager built in to a web application framework. Most popular web application frameworks contain a suitable implementation. It should be noted that these session management facilities evolve over time and early versions may be built with significant weaknesses. Application developers should always strive to use the most up to date versions of application frameworks and should monitor security mailing lists and vendor security announcements in order to determine if any weaknesses have been discovered in the application framework’s session management facilities.

When dealing with stateful application data, consider:

  • Authorization and role data should be stored on the server side only unless properly protected by strong encryption during round trips between clients and the server. For security purposes, server-side-only storage is preferable.
  • Data used to make non-security critical decisions such as a stored theme or a language may be stored in client-side data such as cookies or URL parameters.
  • Hidden fields should not be used to store sensitive state information information. Although these are hidden from the general view and would not be modified by unsophisticated users, hidden fields are easily modified using web proxies or other tools.

When in doubt, developers should not take chances and should store sensitive state information in server-side sessions.

Misconceptions

Server-side sessions have an undeserved poor reputation with some developers due to concerns about scalability and correctness in clustered environments. However this is incorrect from a security perspective as state stored on the server side is safer from tampering from malicious users. The alternative - storing all state within each request - can lead to extensive use of client-side hidden fields and server-side database queries. In addition, unless properly protected against tampering via cryptographic techniques applications relying on client-provided data are susceptible to forgery attacks. Also, client-side state data storage can require the use of code that is complex relative to the use of standard, proven server-side sessions.

Exposed Session Variables

Some frameworks use shared areas of the web server’s disk to store session data. In particular, PHP uses /tmp on Unix and c:\windows\temp on Windows by default. Unless properly secured these areas provide little protection for session data, and may lead to compromise of the application if the web server is shared or compromised.

How to determine if you are vulnerable

  • Investigate the configuration of the application framework. Determine if the application framework stores session data in memory, on disk, or in a database. If session information is stored on disk or in a database, determine who else might have access to this information.

How to protect yourself

  • Ensure the application server is configured to use private temporary file areas per client / application. Use filesystem permissions to protect these files from observation or modification by users other than the accounts required to operate the web and application servers.
  • If this is not possible, the session data needs to be encrypted or contain only non-sensitive data.

Page and Form Tokens

Page specific tokens or "nonces" may be used in conjunction with session specific tokens to provide a measure of authenticity when dealing with client requests. Used in conjunction with transport layer security mechanisms, page tokens can aide in ensuring that the client on the other end of the session is indeed the same client that requested the last page in a given session. Page tokens can be stored in cookies or more likely in query strings and should be completely random. It is possible to avoid sending session token information to the client entirely through the use of page tokens, by creating a mapping between them on the server side, this technique should further increase the difficulty in brute forcing session authentication tokens.

How to determine if you are vulnerable

Does your application:

  • Require the back button to be hidden?
  • Suffer from preset session attacks?

How to protect yourself

  • Incorporate a hidden field with a cryptographically secure page or form nonce
  • The nonce should be removed from the active list as soon as it is submitted to prevent page or form re-submission

Weak Session Cryptographic Algorithms

If a session handler issues tokens which are predictable, an attacker does not need to capture session variables from the remote users – they can simply guess a number of session identifiers and over time will most likely find a valid identifier after a sufficient number of attempts. Session tokens should be user unique, non-predictable, and resistant to reverse engineering and a failure to have these properties leaves the session management facilities open to exploitation.

How to determine if you are vulnerable

  • Ask for 1000 or more session identifiers and see if they are predictable. Take note of the format of the identifier and the characters that are valid in valid identifiers. Identifiers should not be sequential. See How to test session identifier strength with WebScarab.
  • If possible, investigate the source code of the session handler to understand how session identifiers are generated. They should be created from high quality random sources.

How to protect yourself

  • A trusted source of randomness should be used to create the session identifiers (like a pseudo-random number generator, Yarrow, EGADS, etc.).
  • Ideally session tokens could be tied in some way to a specific HTTP client instance (session identifier and IP address) to prevent hijacking and replay attacks. However it should be noted that a number of Internet service providers’ network infrastructures are configured in such a way that web client addresses might not appear the same to the server application. Depending on the intended audience for the web application it may not be possible to implement IP-based controls such as these. In addition, NAT and other network traffic shaping technologies might reduce the efficacy of IP based session management controls.

In general, a session token algorithm should never be based on or use as variables any user personal information (user name, password, home address, etc.)

Appropriate Key Space

Even cryptographically secure algorithms allow an active session token to be easily determined if the keyspace of the token is not sufficiently large. Attackers can essentially "grind" through most possibilities in the token's key space with automated brute-force scripts. A token's key space should be sufficiently large enough to prevent these types of brute force attacks, keeping in mind that computation and bandwidth capacity increases will make these requirements change over time.

Session Token Entropy

The session token should use the largest character set available to it. If a session token is made up of say 8 characters of 7 bits the effective key length is 56 bits. However if the character set is made up of only integers that can be represented in 4 bits giving a key space of only 32 bits. A good session token should use as many characters as possible. Exceptions to this can be made, however, for special control characters that would require escaping and thus complicate development. Most application frameworks use the characters A-Z and 0-9 and some add case sensitivity by including a-z.

Session Time-out

Session tokens that do not expire on the HTTP server can allow an attacker unlimited time to guess or brute-force a valid authenticated session token. An example is the "Remember Me" option on many retail websites. If a user's cookie file is captured or brute-forced, then an attacker can use these static-session tokens to gain access to that user's web accounts. This problem is particularly severe in shared environments, where multiple users have access to individual workstations. Additionally, session tokens can be potentially logged and cached in proxy servers that, if broken into by an attacker, could be exploited if the particular session has not been expired on the HTTP server.

How to determine if you are vulnerable

Idle “Protection”

  • Does the application use an HTML meta-refresh or similar JavaScript trick to make automated requests to the server? If so the server session might never time out. Look at IFRAME and other AJAX implementation features of the application because automated background requests could be occurring without the explicit knowledge of ordinary users. If the application has features such that sessions will never expire on their own then the application is vulnerable.

Remember me?

  • Does the application have a “remember me” feature? If so, the application is potentially vulnerable. Application developers must be careful when designing and implementing such functionality and make explicit decisions about what information the application will store and reveal to “remembered” users as well as what functionality “remembered” users are allowed to access. See the Authorization chapter for more discussion about this topic.

Faulty idle timeout

  • Login to the application, wait for an extended period of time such as two hours and then attempt to continue using the application. If the application does not force another login then the idle timeout might not be operating properly, proper authentication controls might not be in place, or the timeout might be set too high. Application timeouts should be carefully selected for applications based on the sensitivity and value of the business transactions they implement.

How to protect yourself

Set the idle timeout to 5 minutes for highly protected applications through to no more than 20 minutes for low risk applications

For highly protected applications:

  • Do not implement idle defeat mechanisms
  • Do not implement “remember me” functionality or severely constrain the information retained and revealed by the application. Force the user to re-log in before viewing any high value resources or engaging in any high value transactions.

Regeneration of Session Tokens

To reduce the risk from session hijacking and brute force attacks, the HTTP server can seamlessly expire and regenerate tokens. This decreases the window of opportunity for a replay or brute force attack.

How to determine if you are vulnerable

  • Conduct a lengthy session with your application. Note the session identifier at the start of the session as well as before and after high value transactions. If the session identifier never changes then it might be possible to increase security by implementing a session identifier regeneration scheme.

How to protect yourself

This control measure is suitable for highly protected sites. Token regeneration should be performed:

  • prior to any significant transaction
  • after a certain number of requests
  • after a period of time, for example every 20 minutes.
  • It should be noted that unless this capability is built in to the application framework it must implemented in addition to the application framework session controls. The prior recommendations about first leveraging platform security mechanisms still apply – because this control measure often includes writing additional custom code for an application the application should require the application framework session management features to be in operation as well as this additional rotating session identifier.

Session Forging/Brute-Forcing Detection and/or Lockout

Many web applications have prohibitions against unrestrained password guessing. After a certain number of incorrect attempts at a login they will temporarily lock the account or block traffic from the requesting IP address. However it is much less common for web applications or network infrastructure to detect many attempts to continue sessions based on guesses session identifiers. Application servers rarely log or audit attempts to continue sessions based on invalid session identifiers and network intrusion detection systems rarely have signatures to look for this sort of traffic.

How to determine if you are vulnerable

  • Write a script to make multiple attempts to continue sessions based on guessed session identifiers. If the application logs and network infrastructure systems do not log or respond to this activity then the application and the network infrastructure may be vulnerable to brute force attacks.

How to protect yourself

  • Consider adding handlers to the application that would validate that session identifiers in a request map to valid, active sessions. Log or potentially take corrective action when certain IP addresses make excessive attempts to continue sessions based on invalid or expired session identifiers.
  • Consider upgrading or modifying the web and application server environment. There are Apache web server modules, such as mod_dosevasive and mod_security, that could be used for this kind of protection. Although mod_dosevasive is used to lessen the effect of DoS attacks, it could be rewritten for other purposes as well

Session Token Capture and Session Hijacking

If a session token can be captured in transit through network interception, a web application is then prone to session hijacking attacks. This is often the case for applications that only use unencrypted HTTP transport for all traffic. However, it can also be the case for applications that use encrypted HTTPS transport for viewing certain resources or engaging in certain transactions. If the application depends solely on a session identifier that was originally transmitted in the clear via HTTP, the HTTPS session can potentially still be hijacked. Implementing common web encryption technologies such as Secure Sockets Layer (SSLv3) and Transport Layer Security (TLS v1) in order to safeguard the session identifier token can help, but this session identifier must never be transmitted in the clear or an additional session identifier token must be used for secure areas of the web application.

If the session identifier is transmitted via a URL parameter rather than a browser cookie, GET requests can potentially be stored in browser history, cache and bookmarks. For shared workstations or in cases where access to a workstation is compromised this can lead to the capture of session identifier. The use of POST requests can help to alleviate this issue.

How to determine if you are vulnerable

  • Access a web application via unencrypted HTTP and note the session token. Log in to the application under a given user account. Using a web proxy or other tool, simulate a request to the web application using the original session identifier. If the web application responds to the request as if it were provided by the original authenticated use then the web application is vulnerable. This test should be performed for resources accessed by both HTTP and HTTPS.
  • Use a web application and observe how the session identifiers are transmitted. If they are submitted as URL parameters, then GET requests might cause this session identifier to be stored in an insecure manner on shared or private workstations.
  • It should be noted that because of spyware, viruses, Trojans, keyloggers and other security threats that all browsers are potentially vulnerable to having session identifier tokens stolen.

How to protect yourself

If possible, conduct all traffic to the web application over HTTPS to prevent network sniffing of session identification tokens. If this is not possible, at least protect sensitive content and pages used to engage in sensitive transactions with HTTPS. If HTTPS is not used to protect the entire web session an additional session identifier should be incorporated that is only transferred over HTTPS. Additional application level checks for HTTPS pages should verify that this session identifier has been provided and matches the normal session being managed by the web or application server.

If URL parameters must be used to store and transmit session identifiers, use POST requests for all requests to the server. This can make seemingly simple operations such as linking to pages in an application complicated so the use of browser cookies is typically preferable for session state maintenance tokens.

Provide an explicit way for users to log out of the application and ensure that this log out routine explicitly expires and destroys the session. See the following section for more detail.

There have been suggestions that associating web application sessions with IP addresses would increase security. Request handlers could be added to applications that would check the IP address of incoming requests and either invalidate the session or at least log the anomaly if the IP address associated with the session changes. This would increase security for a number of applications, but it should be noted that depending on the network infrastructure between the web application client and server this may not be an acceptable solution. Some Internet service providers route traffic on their network such that the apparent client IP address might change during the course of a valid session. In addition, NAT firewalls and other technologies might mask when a host performing attacks has attempted to hijack a session. These concerns limit the utility and applicability of IP to session binding for Internet-accessible web applications.

Session Tokens on Logout

Applications should invalidate and ideally remove the session identification token after a user logout. Often cookies are associated with the life of a browser window, so if a user logs out of an application on a shared workstation such as an Internet kiosk and a subsequent user attempts to access the same application, the second user will have the same session identifier token as the first. If the application framework and web application do not protect against this it can result in the leakage of sensitive information or the bypass of proper authentication and authorization controls.

How to determine if you are vulnerable

  • Log in to the application, note the session identifier and then log out. Using the same browser window, attempt to access a sensitive resource. If the application will successfully serve the resource without requiring another login then the session management facilities of the application are vulnerable.
  • Log in to the application, note the session identifier and then log out. Attempt to log in to the application and observe the session identifier used in the request attempting the login. If the session identifier has not changed then the application framework and web application might be vulnerable. From this point check to see if it is possible to view sensitive data from the previous session. The definition of senstivie data will be application specific – the goal is to see if session variables from the previous logged in session have survived the subsequent log out and log in operations.

How to protect yourself

When the user logs out of the application:

  • Explicitly expire and destroy the session
  • Overwrite session cookies.

Session Validation Attacks

Just like any data, the session variable must be validated to ensure that is of the right form, contains no unexpected characters, and is in the valid session table. In one penetration test the author conducted, it was possible to use null bytes to truncate session objects and due to coding errors in the session handler, it only compared the length of the shortest string. Therefore, a one-character session variable was matched and allowed the tester to break session handling. During another test, the session handling code allowed any characters.

How to determine if you are vulnerable

  • Use a web proxy to tamper with the session identifier. Suggested modifications are inserting invalid characters, increasing the length to a very large value or croping the length to zero. If the web application framework or web application shows any behavior other than starting the browser with a new session, they may be vulnerable.

How to protect yourself

Configure the web application framework to enforce session identifier constraints to the degree possible. Also track information sources such as security mailing lists and vendor security announcements in order to know when to upgrade the application framework to fix newly discovered security issues.

PHP

Sessions

Sessions in PHP is a way of saving user specific variables or “state" across subsequent page requests. This is achieved by handing a unique session ID to the browser which the browser submits with every new request. The session is alive as long as the browser keeps sending the ID with every new request and not to long time passes between requests. The session ID is generally implemented as a cookie but it could also be a value passed in the URL. Session variables are saved to files in a directory specified in php.ini, the filenames in this directory are based on the session IDs. Each file will contain the variables for that session in clear text. First we are going to look at the old and insecure way of working with sessions; unfortunately this way of working with sessions is still widely used.

// first.php 
// Initalize session management 	
session_start(); 
// Authenticate user 	
if ( ... ) 	{ 	  
$bIsAuthenticated = true; 	
} else { 	   
$bIsAuthenticated = false; 	
}
// Register $bIsAuthenticated as a session variable session_register('bIsAuthenticated'); 
echo '<a href= “second.php “>To second page</a>'; 
// second.php 
// Initalize session management 	
session_start();
// $bIsAuthenticated is automatically set by PHP 	
if ( $bIsAuthenticated ) 	{ 
	   // Display sensitive information 	  ... 
} 	  

Why is this insecure? It is insecure because a simple second.php?bIsAuthenticated=1 would bypass the authentication in first.php. session_start() is called implicitly by session_register() or by PHP if the session.auto_start directive is set in php.ini (defaults to off). However to be consistent and not to rely on configuration settings we always call it for ourselves. The recommend way of working with sessions:

// first.php
// Initalize session management
session_start();
// Authenticate user 
if ( ... ) {
$_SESSION['bIsAuthenticated'] = true;
} else {
$_SESSION['bIsAuthenticated'] = false;
} 
echo '<a href= “second.php”>To second page</a>';
// second.php 
// Initalize session management 	
session_start(); 
if ($_SESSION['bIsAuthenticated'] ) { 
// Display sensitive information 
... 
} 

Not only is the above code more secure it is also, in my opinion, much cleaner and easier to understand. Note: On multi host systems, remember to secure the directory containing the session files (typically held in /tmp), otherwise users might be able to create custom session files for other sites.

ColdFusion Session Management

The term session has two meanings for web applications. At the server-level, session refers to the connections between a client (browser) and the server. At the application-level session refers to the activities of an individual user within a given application. ColdFusion uses tokens to identify unique browser sessions to the server. It will also use these same tokens to identify user sessions within an application. ColdFusion has two types of session management: ColdFusion (CFID/CFToken ) and J2EE (JSESSIONID). CFID – a sequential four-digit integer. CFToken – a random eight-digit integer by default. It can also be generated as a ColdFusion UUID (a 32-character, alphanumeric string) for greater security. (See Configuration section) JSESSIONID – a secure, random alphanumeric string

The two types cannot be used simultaneously. However, ColdFusion session management must be enabled in order to enable J2EE session management. When either type is enabled, client data is persisted in the Session-scope in ColdFusion’s memory space. In order to use Session-scope variables in application code, you must set the initialization variable to true in Application.cfc (This.sessionManagement) or to true

ColdFusion Session Management

ColdFusion session management is enabled by default. It utilizes CFID and CFToken as session identifiers. It sends them to the browser as persistent cookies with every request. If cookies are disabled, developers must pass these values in the URL. Session variables are automatically cleared when the session timeout is reached – but not when the browser closes.

Best Practices

  • Use session timeout values of 20 minutes or less.
  • For J2EE sessions, ensure the session-timeout parameter in cf_root/WEB-INF/web.xml is greater-than-or equal-to ColdFusion’s Maximum Session Timeout.
  • Only enable J2EE Session Variables if all applications on the server will be using it. Do not enable if applications require Client Management.
  • Create CFID and CFToken as non-persistent cookies.
  • See ColdFusion TechNote 17915: How to write CFID and CFTOKEN as per-session cookies at http://www.macromedia.com/go/tn_17915 .
  • Enable UUID CFToken for stronger ColdFusion session identifiers.
  • See ColdFusion TechNote 18133: How to guarantee unique CFToken values at http://www.macromedia.com/go/tn_18133 .
  • Avoid passing session identifiers (CFID/CFToken or JESSIONID) on the URL.
  • Use cookies whenever possible.
  • If cookies are not available use the URLSessionFormat function for links.
  • Only use one unnamed application per ColdFusion server instance.
  • Always use the SESSION prefix when accessing session variables.
  • Lock read/write access to Session variables which may cause race conditions.
  • Do not overwrite the default Session variables.
  • Loop over StructDelete(Session.variable) instead of using StructClear(Session) to remove variables from the Session scope.
  • Use <cflogout> to remove login information from the Session scope when using loginStorage=Session.
  • If clientManagement = “Yes” and clientStorage=”Cookie”, do not store sensitive information in the client’s cookie. Any information that could aid in identity theft if revealed to a third-party should not be included in a cookie. For example, passwords, phone numbers, or SSN.

Default Session-scope variables:

Variable Description Session.CFID The value of CFID client identifier Session.CFToken The value of the CFToken security token Session.URLToken A combination of CFID and CFToken in URL format: CFID=cfid_number&CFTOKEN=cftoken_num Session.SessionID A combination of the application name and the session token that uniquely identifies the session: applicationName_cfid_cftoken.

Pros

  • Compatible with all versions of ColdFusion
  • Uses same session identifiers as ColdFusion’s Client Management.
  • Enabled by default.

Cons

  • CFID and CFToken are created as persistent cookies.
  • Can only use one unnamed application per server instance.
  • Sessions persist when browser closes.
  • ColdFusion Session-scope is not serializable.

ColdFusion J2EE Session Management

J2EE session management is disabled by default. J2EE sessions utilize JESSIONID as the session identifier. ColdFusion sends JESSIONID as a non-persistent (or in-memory) cookie to the browser. If cookies are disabled, developers must pass the value in the URL. Session variables are automatically cleared when the session timeout is reached and when the browser closes.

Default Session-scope variables:

Variable Description

Session.URLToken A combination of CFID, CFToken, and JESSIONID in URL format: CFID=cfid_number&CFTOKEN=cftoken_num&JESSIONID=SessionID

Session.SessionID The JESSIONID value that uniquely identifies the session.

Pros ColdFusion sessions data is shareable with JSP pages and Java servlets Uses session specific JESSIONID identifier Can use multiple unnamed sessions Sessions automatically expires when the browser is closed ColdFusion Session-scope is serializable

Cons Must be enabled manually Not backwards compatible with earlier versions of ColdFusion JESSIONID is not used for Client Management When enabled ColdFusion Session Management cannot be used

Configuring Session Management

Session management must be enabled in two places in order to use session variables: The ColdFusion Administrator (See Configuration section) Application initialization code

Application Code Application initialization code is created in the pseudo-constructor area (section above the application event handlers) of the Application.cfc or the <cfapplication> in the Application.cfm. You should only use one of these application files, and ColdFusion will ignore the Application.cfm if it finds an Application.cfc in the same directory tree.

Application.cfc Add the following code right below the opening cfcomponent tag: Set This.sessionManagement equalto a positive ColdFusion Boolean value – e.g. this.sessionManagement=true Set This.sessionTimeout equal to a valid time value using the CreateTimeSpan function – e.g. This.sessionTimeout=CreateTimeSpan(0,0,20,0) Optionally provide the application name by using the This.name variable

Application.cfm Add the following attributes to the <cfapplication> Set sessionManagement equalto a positive ColdFusion Boolean value – e.g.sessionManagement=true Set sessionTimeout equal to a valid time value using the CreateTimeSpan function – e.g. sessionTimeout=CreateTimeSpan(0,0,20,0) Optionally provide an application name using the name attribute

Note: Unnamed applications can facilitate session integration with JSPs and Java servlets for J2EE Session Management. However, they should not be used with ColdFusion Session Management because the application name is used to create the Session.SessionID variable.

Further Reading

  • David Endler, "Brute-Force Exploitation of Web Application Session IDs" [6]
  • Ruby CGI::Session creates session files insecurely [7]
  • Ollmann, Gunter, “Web Based Session Management: Best Practices in Managing HTTP Based Client Sessions” [8]

Development Guide Table of Contents