...
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
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 | ||
---|---|---|
| ||
private String login(HttpServletRequest request, HttpServletResponse response) {
List<String> errors = new ArrayList<String>();
request.setAttribute("errors", errors);
String username = request.getParameter("username");
String password = request.getParameter("password");
if(username.matches("[\\w]*")) errors.add("Incorrect username format.");
if(password.matches("[\\w]*")) errors.add("Incorrect password format.");
if(errors.size() > 0) return "error.do";
UserBean dbUser = this.userDAO.lookup(username);
if(!dbUser.checkPassword(password)) {
errors.add("Passwords do not match.");
return "error.do";
}
HttpSession session = request.getSession();
session.invalidate();
session = request.getSession(true);
session.setMaxInactiveInterval(2*60*60);
session.setAttribute("user", dbUser);
return "welcome.do";
}
|
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. The timeout of the session has also been set to two hours so that if an attacker were to gain access to the session id of a user, it is unlikely that they have much time to hijack the session.