# Intro
- As discussed previously, XSS vulnerabilities are mainly linked to two parts of the web application:
- A `Source` like a user input field; and
- A `Sink` that displays the input data. These are the main two points that we should focus on securing, both in the front-end and in the back-end
- The most important aspect of preventing XSS vulnerabilities is proper input sanitization and validation on both the front and back end
- In addition to that, other security measures can be taken to help prevent XSS attacks
# Front-end
- As the front-end of the web application is where most (but not all) of the user input is taken from, it is essential to sanitize and validate the user input on the front-end using JavaScript
## Input Validation
- Email field - invalid email javascript code
- tTis code is testing the `email` input field and returning `true` or `false` whether it matches the Regex validation of an email format
```javascript
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());
}
```
## Input Sanitization
- In addition to input validation, we should always ensure that we do not allow any input with JavaScript code in it, by escaping any special characters
- Example javascript code for special character escaping
```javascript
<script type="text/javascript" src="dist/purify.min.js"></script>
let clean = DOMPurify.sanitize( dirty );
```
## Direct Input
- We should always ensure that we never use user input directly within certain HTML tags, like:
1. JavaScript code `<script></script>`
2. CSS Style Code `<style></style>`
3. Tag/Attribute Fields `<div name='INPUT'></div>`
4. HTML Comments `<!-- -->`
- Avoid using JavaScript functions that allow changing raw text of HTML fields, like:
- `DOM.innerHTML`
- `DOM.outerHTML`
- `document.write()`
- `document.writeln()`
- `document.domain`
- Avoid the following jQuery functions:
- `html()`
- `parseHTML()`
- `add()`
- `append()`
- `prepend()`
- `after()`
- `insertAfter()`
- `before()`
- `insertBefore()`
- `replaceAll()`
- `replaceWith()`
# Back-end
- We should also ensure that we prevent XSS vulnerabilities with measures on the back-end to prevent Stored and Reflected XSS vulnerabilities
- As seen in the `XSS Discovery` section exercise, even though it had front-end input validation, this was not enough to prevent us from injecting a malicious payload into the form
- So, we should have XSS prevention measures on the back-end as well
- This can be achieved with Input and Output Sanitization and Validation, Server Configuration, and Back-end Tools that help prevent XSS vulnerabilities
## Input Validation
- Input validation in the back-end is quite similar to the front-end, and it uses Regex or library functions to ensure that the input field is what is expected
- If it does not match, then the back-end server will reject it and not display it
- Example php code for back-end email validation
```php
if (filter_var($_GET['email'], FILTER_VALIDATE_EMAIL)) {
// do task
} else {
// reject input - do not display it
}
```
## Input Sanitization
- When it comes to input sanitization, then the back-end plays a vital role, as front-end input sanitization can be easily bypassed by sending custom `GET` or `POST` requests
- Use the `addlashes` function to sanitize user input by escaping special characters with a backslash
```php
addslashes($_GET['email'])
```
## Output HTML Encoding
- Another important aspect to pay attention to in the back-end is `Output Encoding`
- This means that we have to encode any special characters into their HTML codes, which is helpful if we need to display the entire user input without introducing an XSS vulnerability
- For a PHP back-end, we can use the `htmlspecialchars` or the `htmlentities` functions, which would encode certain special characters into their HTML codes (e.g. `<` into `<`), so the browser will display them correctly, but they will not cause any injection of any sort
- Example `htmlentities` php code
```php
htmlentities($_GET['email']);
```
## Server Config
- In addition to the above, there are certain back-end web server configurations that may help in preventing XSS attacks, such as:
- Using HTTPS across the entire domain.
- Using XSS prevention headers.
- Using the appropriate Content-Type for the page, like `X-Content-Type-Options=nosniff`.
- Using `Content-Security-Policy` options, like `script-src 'self'`, which only allows locally hosted scripts.
- Using the `HttpOnly` and `Secure` cookie flags to prevent JavaScript from reading cookies and only transport them over HTTPS.
- In addition to the above, having a good `Web Application Firewall (WAF)` can significantly reduce the chances of XSS exploitation, as it will automatically detect any type of injection going through HTTP requests and will automatically reject such requests
- Also, some frameworks provide built-in XSS protection, like [ASP.NET](https://learn.microsoft.com/en-us/aspnet/core/security/cross-site-scripting?view=aspnetcore-7.0)