1

Using Angular 13, I have a dynamic URL that loads into an iframe's SRC attribute. I need to sanitize this url (of course) before hand. I tried the following (pseudo code):

DomSanitizer.sanitize(SecurityContext.RESOURCE_URL, 'myurl')

This throws the following error:

unsafe value used in a resource URL context

I cannot use the bypassSecurityTrustResourceUrl as SonarQube marks it as a Security Hotspot. This is what I'm trying to fix.

Most of the examples I've found here recommend using the bypass and I wanted to know if there was a way not to do so.

Thanks in advance

2 Answers 2

1

SecurityContext.RESOURCE_URL throws error when input is unsafe, this is by design, it indicates error in your application because in this case URL is expected to always be safe. You have to understand why it complains, maybe your URL is really unsafe. If URL does not depend on user input in any way then you can actually use bypassSecurityTrustResourceUrl.

You can use SecurityContext.URL, but it can silently truncate your URL, potentially removing valuable information bits from URL because built-in sanitizer is relatively dumb.

You can use a more intelligent third party sanitizer like DOMPurify.

Sign up to request clarification or add additional context in comments.

Comments

0

Use SecurityContext.URL instead.

  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit() {
    console.log(
      this.sanitizer.sanitize(
        SecurityContext.URL,
        "javascript:alert('You've been hacked!');"
      )
    );
  }

Outputs:

WARNING: sanitizing unsafe URL value javascript:alert('You've been hacked!'); (see https://g.co/ng/security#xss)

unsafe:javascript:alert('You've been hacked!');

Example: https://stackblitz.com/edit/angular-qymboh?file=src/main.ts


From https://angular.io/guide/security#sanitization-and-security-contexts:

Angular defines the following security contexts:

SECURITY CONTEXTS DETAILS
HTML Used when interpreting a value as HTML, for example, when binding to innerHtml.
Style Used when binding CSS into the style property.
URL Used for URL properties, such as <a href>.
Resource URL A URL that is 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.