Reputation: 1220
I'm playing with bypassSecurityTrust*
functions of Angular. Goal is to get a script
tag to execute on the page. But it either keeps sanitizing with the message
WARNING: sanitizing HTML stripped some content
or I see in the console a
SafeHtmlImpl {changingThisBreaksApplicationSecurity: "<script>alert(1)</script>
.
Goal is to get this working.
What I currently use and tried:
@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value: string): string {
console.log(this.sanitized.sanitize(SecurityContext.NONE, value))
return this.sanitized.sanitize(SecurityContext.NONE, value);
}
}
@Component({
selector: 'app-demo',
templateUrl: './demo.component.html',
styleUrls: ['./demo.component.css']
})
export class DemoComponent implements OnInit {
name: string;
html: string;
constructor(private sanitizer: DomSanitizer) {
this.name = 'Angular2';
this.html = "<script> alert(8) </script>";
}
ngOnInit() {
}
}
and the template html:
<div [innerHtml]="html | safeHtml"></div>
I tried both sanitize
with SecurityContext.NONE
which should work looking at the code and bypassSecurityTrustHtml(value)
. The above code was inspired by this answer.
Any ideas on how to execute that JavaScript?
Upvotes: 1
Views: 11635
Reputation: 1220
So yes, innerHtml can't insert script tags, but it doesn't stop it from one of the many other ways to inject JavaScript.
Working example:
import { Component, Pipe, PipeTransform, SecurityContext} from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser'
@Pipe({ name: 'safeHtml'})
export class SafeHtmlPipe implements PipeTransform {
constructor(private sanitized: DomSanitizer) {}
transform(value: string) {
console.log(this.sanitized.bypassSecurityTrustHtml(value));
return this.sanitized.bypassSecurityTrustHtml(value);
}
}
@Component({
selector: 'app-demo',
template: `
<div [innerHtml]="html | safeHtml">
</div>
`
})
export class DemoComponent {
html: string;
h_html: string;
constructor(private sanitizer: DomSanitizer) {
this.html = "<svg onload=\"alert(1)\"> blah </svg>"
this.h_html = sanitizer.sanitize(SecurityContext.HTML, "<svg onload=\"alert(2)\"> blah </svg>');
}
}
What doesn't work is
return this.sanitized.sanitize(SecurityContext.HTML, value);
or using
<div [innerHtml]="h_tmpl"></div>
Not sure why. Should behave the same afaiu.
Upvotes: 2