In order to demonstrate how the HttpOnly flag works two files were created. An HTML file, welcome.html consisting of a form and a PHP file, cookieWelcome.php that echoes user input from the form and contains two cookies.
The code for welcome.html can be found below:
<html> <body> <form action="cookieWelcome.php" method="post"> Name: <input type="text" name="name" size="50" ><br> E-mail: <input type="text" name="email" size="50" ><br> <input type="submit"> </form> </body> </html>
Below is the code for cookieWelcome.php:
<html> <body><?php setcookie("sessionId","261957163849573", time() + (86400 * 30), "/", null, null, true); setcookie("Missing_HttpOnly","482749185763514", time() + (86400 * 30), "/", null, null, false); ?>Welcome <?php echo $_POST["name"]; ?><br> Your email address is: <?php echo $_POST["email"];?> </body> </html>
In PHP, a cookie is set with the following values:
setcookie($name, $value, $expirationTime, $path, $domain, $secure, $HttpOnly);
Cookie “sessionId” has the HttpOnly flag set.
setcookie("sessionId","261957163849573", time() + (86400 * 30), "/", null, null, true);
Use the following values as input in the form:
The script was successfully run in the application.
Use the following input:
An alert box exposing the value of Missing_HttpOnly is returned. An attacker could use this cookie to impersonate a user.
XSS enables an attacker to steal sensitive information like cookie values. While this example uses reflected XSS if the XSS was stored any visitor to the application could potentially have cookies, session tokens, or other private information compromised.
In conclusion, HttpOnly is necessary when the values contained in a sensitive cookie need to remain confidential.