4

How can I only retain id part of the div when it sanitized, removing script part.

Stackblitz

Angular XSS

import { OnInit, Component, Input, SecurityContext } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'hello',
  template: `{{unsafe}}
    <br/>
    <br/>
    <div [innerHtml]="unsafe">
    </div>`,
  styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent implements OnInit  {
  @Input() name: string;

  constructor(private sanitizer: DomSanitizer){}

  output = 'heyo <div class="someclass" id="someid">sbang</div> <script>alert("bang");</script>';
  unsafe = this.output;


  ngOnInit(){
    console.log(this.sanitizer.sanitize(SecurityContext.NONE, this.unsafe));
    // heyo <div class="someclass" id="someid">sbang</div> <script>alert("bang");</script>
    console.log(this.sanitizer.sanitize(SecurityContext.HTML, this.unsafe));
    // heyo <div class="someclass">sbang</div> 
    console.log(this.sanitizer.sanitize(SecurityContext.STYLE, this.unsafe));
    // unsafe
    console.log(this.sanitizer.sanitize(SecurityContext.URL, this.unsafe));
    // heyo <div class="someclass" id="someid">sbang</div> <script>alert("bang");</script>
    console.log(this.sanitizer.sanitize(SecurityContext.RESOURCE_URL,this.unsafe));
    // error
  }
}

Result: Imgur

Chenna
  • 2,383
  • 3
  • 20
  • 36

2 Answers2

4

I don't think it's possible. From looking at the source, the id attribute is not included in the array of approved attributes for sanitization:

The call to the sanitization for HTML is made here:

It appears that you have to accept the defaults or disable with bypassSecurityTrustHtml. Guess you could record the id attributes before the sanitization and add them back afterwards

Drenai
  • 11,315
  • 9
  • 48
  • 82
0

I'm not super fluent with the DomSanitizer but from what I found this seems to work:

console.log(this.sanitizer.bypassSecurityTrustHtml(this.unsafe));

Also, I found this other SO question which seemed to expand on it more: Duplicate?