What is XSS and why so many libraries mention it?

Before I write this, I exploited two of my classmates' projects with XSS. I didn't expect it to work but it worked anyway. In many libraries and frameworks, there are usually documentations about XSS. Most of them usually say something similar to

Don't use X to display untrusted content to prevent XSS attack.

It usually appears when it is possible to display raw HTML from string or any input. Let's get into it.

What is XSS anyway?

XSS is about inserting script into someone's else website and browser just executes it. The code is executed the same way as code provided by the site. That means it can access sensitive information and use it. XSS can also use to perform unwanted actions such as making a request, changing HTML content and more.

Example

There is website called superforum.com. Superforum has code like this. I will use Django to explain this but it applies to other frameworks as well.

Request

def create_comment(request, thread_id):
    # The comment editor allows inserting HTML tag
    comment_body = request.POST['comment_body']
    # Insert comment saving logic here
    return redirect(reverse('forum:view', args=[thread_id]))

Template

 <!-- Insert other things here -->
<div class="comment-body">
   {{ comment.comment_body|safe }}
</div>

In Django, safe filter allows string to display as raw HTML. If the user comment this

I like this. <script>window.open("https://www.youtube.com/watch?v=dQw4w9WgXcQ", '_blank').focus()</script>

it would be executed right away when someone view the page with this comment. The script above is harmless rickroll. Real attackers would steal your identity, transfer your money, mine Bitcoin, and more.

How can I avoid it in my website?

Don't trust user input. Sanitize the input and escape it help. Common libraries usually have a way to deal with this. For example, Django escapes template by default (unless you use safe).

But, don't do it yourself. There is a terrifying long list of evasions. I don't even know if it is comprehensive or not. If there is a verified library, use it.

More information and references

Also, I informed my classmates about vulnerabilities. Both projects already fixed this.