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 period of time on the client. 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 Cookies are an essential part of any web application and can be used for a number of different purposes such as user authentication. A cookie is a small piece of data that is set by a web server's response that will be stored for a certain period of time on the requesting user's computer. After a cookie has been set, all of the information within it will be sent in all subsequent requests to the cookie domain. Because of this, the information within a cookie is not secure and can be retrieved through a variety of cross-site scripting (XSS) attacks. As a result, it is important that the server does not set a cookie that contains excess or sensitive information about a user. This includes, but is not limited to, 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 non compliant noncompliant code example, we can see that the login servlet stores the user name and password in the cookie to identify the user for authentication purposes.subsequent requests:
Code Block | ||
---|---|---|
| ||
privateprotected Stringvoid logindoPost(HttpServletRequest request, HttpServletResponse response) { List<String>// errorsValidate = newinput ArrayList<String>(omitted); String username = request.setAttributegetParameter("errorsusername", errors); Â Â Â Â Â Â Â char[] Stringpassword username = request.getParameter("usernamepassword").toCharArray(); Stringboolean passwordrememberMe = Boolean.valueOf(request.getParameter("passwordrememberme")); Â Â Â Â Â Â // Basic input validation if(username.matches("[\\w]*")) errors.add("Incorrect user name format."); if(password.matches("[\\w]*")) errors.add("Incorrect password format."); Â Â Â Â Â Â if(errors.size() > 0) return "error.jsp"; Â Â Â Â Â Â UserBean dbUser = this.userDAO.lookup(username); if(!dbUser.checkPassword(password)) { errors.add("Passwords do not match."); return "error.jsp"; } Â Â Â Â Â Â Cookie userCookie = new Cookie("user", username); // Create a cookie that contains the username response.addCookie(userCookie); // Send the cookie information to the client return "welcome.jsp"; } |
Note that the above non compliant code example stores the user name within the cookie for authentication purposes. This particular code example is insecure because an attacker could possibly perform a cross-site scripting attack or sniff packets to find the user name within the cookie. If an attacker had the user name of a particular individual, they could forget their own cookie containing the user name and easily gain access to their account within the web application assuming that the application uses the cookie to identify a user.
Compliant Solution
LoginService loginService = new LoginServiceImpl();
if (rememberMe) {
if (request.getCookies()[0] != null &&
request.getCookies()[0].getValue() != null) {
String[] value = request.getCookies()[0].getValue().split(";");
if (!loginService.isUserValid(value[0], value[1].toCharArray())) {
// Set error and return
} else {
// Forward to welcome page
}
} else {
boolean validated = loginService.isUserValid(username, password);
if (validated) {
Cookie loginCookie = new Cookie("rememberme", username
+ ";" + new String(password));
response.addCookie(loginCookie);
// ... Forward to welcome page
} else {
// Set error and return
}
}
} else {
// No remember-me functionality selected
// Proceed with regular authentication;
// if it fails set error and return
}
Arrays.fill(password, ' ');
}
|
However, the attempt to implement the remember-me functionality is insecure because an attacker 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
The non compliant example above can be resolved by using the HttpSession class to store user information as opposes to cookies. Since HttpSession objects are server-side, it is impossible for an attacker to gain access to the session information directly through cross-site scripting attacks. Instead, the session id of the user is stored within the cookie as opposed to any excess or sensitive information. As a result, the attacker must first gain access to the session id and only then do they have a chance of gaining access to a user's account details.
Code Block | ||
---|---|---|
| ||
privateprotected Stringvoid logindoPost(HttpServletRequest request, HttpServletResponse response) { List<String> errors// =Validate newinput ArrayList<String>(omitted); String username = request.setAttributegetParameter("errorsusername", errors); Stringchar[] usernamepassword = request.getParameter("usernamepassword").toCharArray(); Stringboolean passwordrememberMe = Boolean.valueOf(request.getParameter("passwordrememberme")); LoginService loginService = new LoginServiceImpl(); boolean validated // Basic input validation= false; if (rememberMe) { if (usernamerequest.matchesgetCookies(")[\\w]*")) errors.add("Incorrect username format."); if(password.matches("[\\w]*")) errors.add("Incorrect password format."); if(errors.size() > 0) return "error.jsp"; UserBean dbUser = this.userDAO.lookup(username); if(!dbUser.checkPassword(password)) { errors.add("Passwords do not match."); return "error.jsp"; } 0] != null && request.getCookies()[0].getValue() != null) { String[] value = request.getCookies()[0].getValue().split(";"); if (value.length != 2) { // Set error and return } if (!loginService.mappingExists(value[0], value[1])) { // (username, random) pair is checked // Set error and return } } else { validated = loginService.isUserValid(username, password); if (!validated) { // Set error and return } } String newRandom = loginService.getRandomString(); // Reset the random every time loginService.mapUserForRememberMe(username, newRandom); HttpSession session = request.getSession(); session.invalidate(); // Invalidate old session id session = request.getSession(true); // Generate new session idSet session timeout to 15 minutes session.setMaxInactiveInterval(2*60 *60 15); // Set session timeout to two hoursStore user attribute and a random attribute in session scope session.setAttribute("user", dbUser); // Store user bean within the session return "welcome.jsp"; } |
In the above solution, we have switched from a cookie to a session to store user information. Additionally, the current session is invalidated and a new session is created in order to avoid session fixation attacks as noted by The Open Web Application Security Project (OWASP 2009). The timeout of the session has also been set to two hours to minimize the window that an attacker has to perform any a session hijacking attack.
Risk Assessment
Noncompliance may lead to sensitive information being stored within a cookie, which may be accessible via packet sniffing or cross-site scripting attacks.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
FIO14-J | medium | probable | medium | P8 | L2 |
Bibliography
loginService.getUsername());
Cookie loginCookie =
new Cookie("rememberme", username + ";" + newRandom);
loginCookie.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
...
\[OWASP 2009\] [Session Fixation in Java|http://www.owasp.org/index.php/Session_Fixation_in_Java]
\[OWASP 2010\] [Cross-site Scripting|http://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29]
\[Oracle 2010\] [javax.servlet.http Package API|http://download.oracle.com/javaee/6/api/javax/servlet/http/package-summary.html]
[The World Wide Web Security FAQ|http://www.w3.org/Security/Faq/wwwsf2.html] Wiki Markup