Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

When building an application that uses a client-server model, storing sensitive information, such as user credentials, on the client side may result in its unauthorized disclosure if the client is vulnerable to attack.

For web applications, the most common mitigation to this problem is to provide the client with a cookie and store the sensitive information on the server. Cookies are created by a web server and are stored for a Cookies are an essential part of any web application; they are used for many purposes, including user authentication. A cookie is a small piece of data that is set by a web server's response that is stored for a certain period of time on the client's computer. After a cookie has been set, all of the information within is sent in all subsequent requests to the . When the client reconnects to the server, it provides the cookie, which identifies the client to the server, and the server then provides the sensitive information.

Cookies do not protect sensitive information against cookie domain. Consequently, the information within a cookie is insecure; it is vulnerable to cross-site scripting (XSS) or man-in-the-middle attacks (among others). Servers must ensure that cookies lack excess or sensitive information about users. A partial list of such information includes user names, passwords, password hashes, credit cards, and any . An attacker who is able to obtain a cookie either through an XSS attack or directly by attacking the client can obtain the sensitive information from the server using the cookie. This risk is timeboxed if the server invalidates the session after a limited time has elapsed, such as 15 minutes.

A cookie is typically a short string. If it contains sensitive information, that information should be encrypted. Sensitive information includes passwords, credit card numbers, social security numbers, and any other personally identifiable information about the user. For more details about managing passwords, see MSC62-J. Store passwords using a hash function. For more information about securing the memory that holds sensitive information, see MSC59-J. Limit the lifetime of sensitive data.

Noncompliant Code Example

In this noncompliant code example, the login servlet stores the user name and password in the cookie to identify the user for authentication purposes.subsequent requests:

Code Block
bgColor#FFcccc

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.*;
import com.insecure.model.UserDAO;
import com.insecure.databeans.UserBean;

public class InsecureServlet extends HttpServlet {
  private UserDAO userDAO;

  // ...

  private String login(HttpServletRequest request, HttpServletResponse response) {
    List<String> errors = new ArrayList<String>();
    request.setAttribute("errors", errors);
protected void doPost(HttpServletRequest request,
    HttpServletResponse response) {

  // Validate input (omitted)

  String username = request.getParameter("username");
  char[] password = request.getParameter("password").toCharArray();
  boolean rememberMe = Boolean.valueOf(request.getParameter("rememberme"));
  
  LoginService loginService = new LoginServiceImpl();
        
  if (rememberMe) {
    if (request.getCookies()[0] != null && 
    String username = request.getParameter("username");getCookies()[0].getValue() != null) {
    char  String[] passwordvalue = request.getParameter("password").toCharArray(.getCookies()[0].getValue().split(";");
  
    //
 Basic input validation
    if (!usernameloginService.matchesisUserValid("value[\\w]*") || !password.toString().matches("[\\w]*"0], value[1].toCharArray())) {
         errors.add("Incorrect user name or password format.");// Set error and return
      } else {
      return "error.jsp";  // Forward to welcome page
      }
    } else {
        UserBeanboolean dbUservalidated = thisloginService.userDAO.lookupisUserValid(username, password);
      
        if (!dbUser.checkPassword(password))validated) {
          Cookie loginCookie  errors.add("Passwords do not match.")= new Cookie("rememberme", username
                             + ";" + new String(password));
      return "error.jsp";
    response.addCookie(loginCookie);
     }
 
    // Create a cookie that contains the username
    Cookie userCookie = new Cookie("username", username);
 ... Forward to welcome page
        } else {
          // Create a cookie that contains the password Set error and return
        }
    Cookie }
 passCookie = new Cookie("password", password);} else {
     // No Addremember-me thefunctionality cookieselected
 information to the response that// theProceed clientwith willregular receiveauthentication;
     response.addCookie(userCookie);
    response.addCookie(passCookie);

    // Clear password char array
  // if it fails set error and return
   }
    
  Arrays.fill(password, ' ');

    return "welcome.jsp";
  }
}

Note that the noncompliant code example stores the user name and password within two cookie objects, which are sent to the client to be stored in a cookie. This code example However, the attempt to implement the remember-me functionality is insecure because an attacker can discover this information by performing a cross-site scripting attack or by sniffing packets. Once the attacker gains access to the user name and password, he or she can freely log in to the user's account. Even if the application had stored only the user name within the cookie for authentication purposes, an attacker could still use the user name to forge his or her own cookie and bypass the authentication system.

Compliant Solution

with access to the client machine can obtain this information directly on the client. This code also violates MSC62-J. Store passwords using a hash function. The client may also have transmitted the password in clear unless it encrypted the password or uses HTTPS.

Compliant Solution (Session)

This compliant solution implements the remember-me functionality by storing the user name and a secure random string in the cookie. It also maintains state in the session using HttpSession.This compliant solution stores user information using the HttpSesssion class within the javax.servlet.http package. Because HttpSession objects are server-side, an attacker cannot use cross-site scripting or man-in-the-middle attacks to directly gain access to the session information. Rather, the cookie stores a session id that refers to the user's HttpSession object stored on the server. Consequently, the attacker cannot gain access to the user's account details without first gaining access to the session id.

Code Block
bgColor#ccccff

public class InsecureServlet extends HttpServletprotected void doPost(HttpServletRequest request,
    HttpServletResponse response) {
  
  // privateValidate UserDAO userDAO;input (omitted)

  String username //= request.getParameter("username");
  char[] password = request.getParameter("password").toCharArray();

  boolean privaterememberMe String= loginBoolean.valueOf(HttpServletRequest request) {request.getParameter("rememberme"));
  LoginService loginService = new LoginServiceImpl();
  boolean validated List<String>= errorsfalse;
 = newif ArrayList<String>(rememberMe); {
    if (request.setAttribute("errors", errors);

getCookies()[0] != null &&
     String username = request.getParameter("username");
getCookies()[0].getValue() != null) {
                             
      charString[] passwordvalue = request.getParameter("password"getCookies()[0].getValue().toCharArraysplit(";");
             
      if (value.length != 2) {
        // Basic input validationSet error and return
      }
             
      if (!usernameloginService.matchesmappingExists("value[\\w]*") || !password.toString().matches("[\\w]*"0], value[1])) { 
       errors.add("Incorrect user name or password format.");
  // (username, random) pair is checked
        // returnSet "error.jsp";
error and return
      }
    } else {
    UserBean  dbUservalidated = thisloginService.userDAO.lookupisUserValid(username, password);

     if if (!dbUser.checkPassword(passwordvalidated)) {
      errors.add("Passwords do not match.");  // Set error and return
      return "error.jsp";}
    }
        
    HttpSessionString sessionnewRandom = requestloginService.getSessiongetRandomString();
    // InvalidateReset the oldrandom sessionevery idtime
    sessionloginService.invalidatemapUserForRememberMe(username, newRandom);
    // Generate new session id HttpSession session = request.getSession();
    session.invalidate();
    session = request.getSession(true);
    // Set session timeout to one15 hourminutes
    session.setMaxInactiveInterval(60 *60 15);
    // Store user bean within the session attribute and a random attribute in session scope
    session.setAttribute("user", dbUserloginService.getUsername());
    Cookie loginCookie = 
    // Clear password char array  new Cookie("rememberme", username + ";" + newRandom);
    ArraysloginCookie.fill(password, ' ');

    return "welcome.jsp";
  }
}

Wiki Markup
This solution also invalidates the current session and creates a new session to avoid session fixation attacks; see \[SD:OWASP 2009\].  The solution also reduces the window in which an attacker could perform a session hijacking attack by setting the session timeout to one.

Risk Assessment

Violation of this rule places sensitive information within cookies, making the information vulnerable to packet sniffing or cross-site scripting attacks.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

FIO15-J

medium

probable

medium

P8

L2

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="68a83be5-0cdc-4b07-8daf-c8c56624d70e"><ac:plain-text-body><![CDATA[

[SD:OWASP 2009]

[Session Fixation in Java

http://www.owasp.org/index.php/Session_Fixation_in_Java]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="b87c196f-7da8-4eba-bf96-7111c3bd85bd"><ac:plain-text-body><![CDATA[

[SD:OWASP 2010]

[Cross-site Scripting

http://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29]

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="fb3d346f-4c14-46cf-af54-420766305549"><ac:plain-text-body><![CDATA[

[SD:Oracle 2010]

[javax.servlet.http Package API

http://download.oracle.com/javaee/6/api/javax/servlet/http/package-summary.html]

]]></ac:plain-text-body></ac:structured-macro>

The World Wide Web Security FAQ

setHttpOnly(true);
    loginCookie.setSecure(true);
    response.addCookie(loginCookie);
    // ... Forward to welcome page
  } else {
    // No remember-me functionality selected
    // ... Authenticate using isUserValid() and if failed, set error
  }
  Arrays.fill(password, ' ');
}

The server maintains a mapping between user names and secure random strings. When a user selects “Remember me,” the doPost() method checks whether the supplied cookie contains a valid user name and random string pair. If the mapping contains a matching pair, the server authenticates the user and forwards him or her to the welcome page. If not, the server returns an error to the client. If the user selects “Remember me” but the client fails to supply a valid cookie, the server requires the user to authenticate using his or her credentials. If the authentication is successful, the server issues a new cookie with remember-me characteristics.

This solution avoids session-fixation attacks by invalidating the current session and creating a new session. It also reduces the window during which an attacker could perform a session-hijacking attack by setting the session timeout to 15 minutes between client accesses.

Applicability

Storing unencrypted sensitive information on the client makes this information available to anyone who can attack the client.

Bibliography

 

...

Image Added Image Added Image AddedImage Removed      12. Input Output (FIO)      FIO15-J. Perform proper cleanup at program termination