7. Prevention of XSS attacks

Call back to source and sink concepts Source: Accepst user input Sink: Displays that data

Most important aspect of preventing XSS vulnerabilities is proper input sanitization and validation of both front + backend

Front-end XSS prevention:

Input validation

function validateEmail(email) {
    const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test($("#login input[name=email]").val());
}

For what we did in the [[3. XSS Discovery]] section we saw the webapp would not submit if email format was invalid with the above code

Code is testing email field and returning t/f if it matches regex

Input sanitization In addition to input validation we should always ensure we're not allowing ANY input with Javascript code in it by escaping special characters

https://github.com/cure53/DOMPurify

<script type="text/javascript" src="dist/purify.min.js"></script>
let clean = DOMPurify.sanitize( dirty );

Escapes speciaol chars

Direct input

If user input goes into these fields it can inject malicious JS leading to xss

We should also avoid using JS funx that allow changing raw text of HTML fields

DOM.innerHTML
DOM.outerHTML
document.write()
document.writeln()
document.domain

Aswell as some jQuery functions:

html()
parseHTML()
add()
append()
prepend()
after()
insertAfter()
before()
insertBefore()
replaceAll()
replaceWith()

Since these fx write raw text to HTML - if any user input goes into them it may include malicious JS

Backend user input validation to prevent XSS

Similar to frontend Use Regex or library functions to ensure input fields are what they are expected to be

Example email validation

if (filter_var($_GET['email'], FILTER_VALIDATE_EMAIL)) {
    // do task
} else {
    // reject input - do not display it
}

For NodeJS backend we can use the same JS code mentioned earlier for frontend

Input sanitization