Preventing Cross-Site Scripting (XSS) attacks in Angular Single Page Applications: A Detailed Guide

Preventing Cross-Site Scripting (XSS) attacks in Angular Single Page Applications: A Detailed Guide

By Vikipediaaa , Website: Vikas Saraf

An Angular application can be 10/10 in terms of UI/UX, functionality, performance, etc, but if it is not secure, it's of no use.

4xqo0j.jpg

In this article, we are going to talk about Securing Angular Application :
--> The best practices you can follow to make your angular application safe and secure.
--> What Cross-Site Scripting (XSS) Attack is.
--> Angular's built-in protections against common web-application vulnerabilities and attacks.
--> Sanitization (not to be confused with hand-sanitizing :D)
--> Server-side XSS protection and much more

3 must-haves habits that every angular developer needs to be aware of :

  1. Keep current with the latest Angular library releases
    • Angular team regularly updates their libraries which may fix security defects in previous versions.
  2. Don't modify or customize your copy of Angular
    • Private, customized versions of Angular tend to fall behind the current version and may not include important security fixes and enhancements. Instead, send a pull request if you find any bug and want it fixed.
  3. Avoid Angular APIs marked as “Security Risk”

Cross-Site Scripting (XSS) attack :

Cross-site scripting (XSS) enables hackers to inject malicious code into web pages. Such code can then, for example, steal user data (in particular, login data) or perform actions to impersonate the user. This is one of the most common attacks on the web.

Angular’s cross-site scripting security model :

All the values are untrusted by default. When a value is inserted into the DOM from a template binding or interpolation, Angular sanitizes and escapes untrusted values. Angular templates are considered trusted by default and should be treated as executable code. Never generate templates by concatenating user input and template syntax. Doing this would enable attackers to inject arbitrary code into your application. To prevent these vulnerabilities, always use the default AOT template compiler in production deployments.

Sanitization and security contexts :

Sanitization is the inspection of an untrusted value, turning it into a value that's safe to insert into the DOM. Sanitization depends on context: a value that's harmless in CSS is potentially dangerous in a URL. Angular defines the following security contexts:

  • HTML is used when interpreting a value as HTML, for example, when binding to innerHtml.
  • Style is used when binding CSS into the style property.
  • URL is used for URL properties, such as .
  • Resource URL is a URL that will be loaded and executed as code, for example, in
    <script src>
    

Angular sanitizes untrusted values for HTML, styles, and URLs. Sanitizing resource URLs isn't possible because they contain arbitrary code. In development mode, Angular prints a console warning when it has to change a value during sanitization.

Sanitization example :

Example 1 : dom.png

Behind the scenes, Angular will sanitize the HTML input and escape the unsafe code, so in this case, the script will not run, only display on the screen as text i.e DomSanitizer will be displayed.

Example 2: Try to bind the src property of an Iframe (or a video)

dom2.png

We get the error: “unsafe value used in a resource URL context.”

Angular is throwing this error because the iframe src attribute is a resource URL security context, and because an untrusted source can, for example, smuggle in file downloads that unsuspecting users could execute.

Direct use of the DOM APIs and explicit sanitization calls:

Avoid directly interacting with the DOM and instead use Angular templates where possible. Unless you enforce Trusted Types, the built-in browser DOM APIs don't automatically protect you from security vulnerabilities. For example, document, the node available through ElementRef, and many third-party APIs contain unsafe methods. In the same way, if you interact with other libraries that manipulate the DOM, you likely won't have the same automatic sanitization as with Angular interpolations.

For cases where this is unavoidable, use the built-in Angular sanitization functions. Sanitize untrusted values with the DomSanitizer.sanitize method and the appropriate SecurityContext. That function also accepts values that were marked as trusted using the bypassSecurityTrust... functions, and will not sanitize them.

Trusting safe values :

There will be times when applications genuinely need to include executable code, display an iframe from some URL, or construct potentially dangerous URLs. Automatic Sanitization by angular can be prevented by telling Angular that you inspected a value, checked how it was generated, and made sure it will always be secure. But be careful.

Also, you are introducing a security vulnerability into your application If you are trusting a value that might be malicious.

To mark a value as trusted, inject DomSanitizer and call one of the following methods:

  • bypassSecurityTrustHtml
  • bypassSecurityTrustScript
  • bypassSecurityTrustStyle
  • bypassSecurityTrustUrl
  • bypassSecurityTrustResourceUrl

NOTE: Whether a value is safe depends on context, so choose the right context for your intended use of the value.

Example 1: The following template needs to bind a URL to a javascript: alert(...) call:

san1.png

In normal scenarios, Angular automatically sanitizes the URL, disables the dangerous code, and in development mode, logs this action to the console. To prevent this, mark the URL value as a trusted URL using the bypassSecurityTrustUrl call:

san3.png

Content security policy :

Content Security Policy (CSP) is a defense-in-depth technique to prevent XSS. To enable CSP, configure your webserver to return an appropriate Content-Security-Policy HTTP header. What this means is :

Use the AOT template compiler :

The AOT template compiler prevents a whole class of vulnerabilities called template injection and greatly improves application performance. The AOT template compiler is the default compiler used by Angular CLI applications, and you should use it in all production deployments.

An alternative to the AOT compiler is the JIT compiler which compiles templates to executable template code within the browser at runtime. Angular trusts template code, so dynamically generating templates and compiling them, in particular templates containing user data, circumvents Angular's built-in protections and is a security anti-pattern.

Server-side XSS protection :

HTML constructed on the server is vulnerable to injection attacks. Injecting template code into an Angular application is the same as injecting executable code into the application: it gives the attacker full control over the application. To prevent this, use a templating language that automatically escapes values to prevent XSS vulnerabilities on the server. Don't generate Angular templates on the server-side using a templating language; doing this carries a high risk of introducing template-injection vulnerabilities.

4xqoxk.jpg

If you enjoyed this article, please feel free to share it and help others find it. Follow me on Twitter : Vikipediaaaa for more articles. Happy coding folks!! ☕️