refactor(core): move sanitization into core (#22540)

This is in preparation of having Ivy have sanitization inline.

PR Close #22540
This commit is contained in:
Miško Hevery
2018-03-01 13:16:13 -08:00
committed by Kara Erickson
parent 065bcc5aad
commit 538f1d980f
17 changed files with 108 additions and 81 deletions

View File

@ -1,185 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {browserDetection} from '@angular/platform-browser/testing/src/browser_util';
import {getDOM} from '../../src/dom/dom_adapter';
import {sanitizeHtml} from '../../src/security/html_sanitizer';
{
describe('HTML sanitizer', () => {
let defaultDoc: any;
let originalLog: (msg: any) => any = null !;
let logMsgs: string[];
beforeEach(() => {
defaultDoc = getDOM().supportsDOMEvents() ? document : getDOM().createHtmlDocument();
logMsgs = [];
originalLog = getDOM().log; // Monkey patch DOM.log.
getDOM().log = (msg) => logMsgs.push(msg);
});
afterEach(() => { getDOM().log = originalLog; });
it('serializes nested structures', () => {
expect(sanitizeHtml(defaultDoc, '<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>'))
.toEqual('<div alt="x"><p>a</p>b<b>c<a alt="more">d</a></b>e</div>');
expect(logMsgs).toEqual([]);
});
it('serializes self closing elements', () => {
expect(sanitizeHtml(defaultDoc, '<p>Hello <br> World</p>'))
.toEqual('<p>Hello <br> World</p>');
});
it('supports namespaced elements',
() => { expect(sanitizeHtml(defaultDoc, 'a<my:hr/><my:div>b</my:div>c')).toEqual('abc'); });
it('supports namespaced attributes', () => {
expect(sanitizeHtml(defaultDoc, '<a xlink:href="something">t</a>'))
.toEqual('<a xlink:href="something">t</a>');
expect(sanitizeHtml(defaultDoc, '<a xlink:evil="something">t</a>')).toEqual('<a>t</a>');
expect(sanitizeHtml(defaultDoc, '<a xlink:href="javascript:foo()">t</a>'))
.toEqual('<a xlink:href="unsafe:javascript:foo()">t</a>');
});
it('supports HTML5 elements', () => {
expect(sanitizeHtml(defaultDoc, '<main><summary>Works</summary></main>'))
.toEqual('<main><summary>Works</summary></main>');
});
it('sanitizes srcset attributes', () => {
expect(sanitizeHtml(defaultDoc, '<img srcset="/foo.png 400px, javascript:evil() 23px">'))
.toEqual('<img srcset="/foo.png 400px, unsafe:javascript:evil() 23px">');
});
it('supports sanitizing plain text',
() => { expect(sanitizeHtml(defaultDoc, 'Hello, World')).toEqual('Hello, World'); });
it('ignores non-element, non-attribute nodes', () => {
expect(sanitizeHtml(defaultDoc, '<!-- comments? -->no.')).toEqual('no.');
expect(sanitizeHtml(defaultDoc, '<?pi nodes?>no.')).toEqual('no.');
expect(logMsgs.join('\n')).toMatch(/sanitizing HTML stripped some content/);
});
it('supports sanitizing escaped entities', () => {
expect(sanitizeHtml(defaultDoc, '&#128640;')).toEqual('&#128640;');
expect(logMsgs).toEqual([]);
});
it('does not warn when just re-encoding text', () => {
expect(sanitizeHtml(defaultDoc, '<p>Hellö Wörld</p>'))
.toEqual('<p>Hell&#246; W&#246;rld</p>');
expect(logMsgs).toEqual([]);
});
it('escapes entities', () => {
expect(sanitizeHtml(defaultDoc, '<p>Hello &lt; World</p>'))
.toEqual('<p>Hello &lt; World</p>');
expect(sanitizeHtml(defaultDoc, '<p>Hello < World</p>')).toEqual('<p>Hello &lt; World</p>');
expect(sanitizeHtml(defaultDoc, '<p alt="% &amp; &quot; !">Hello</p>'))
.toEqual('<p alt="% &amp; &#34; !">Hello</p>'); // NB: quote encoded as ASCII &#34;.
});
describe('should strip dangerous elements', () => {
const dangerousTags = [
'frameset', 'form', 'param', 'object', 'embed', 'textarea', 'input', 'button', 'option',
'select', 'script', 'style', 'link', 'base', 'basefont'
];
for (const tag of dangerousTags) {
it(`${tag}`,
() => { expect(sanitizeHtml(defaultDoc, `<${tag}>evil!</${tag}>`)).toEqual('evil!'); });
}
it(`swallows frame entirely`, () => {
expect(sanitizeHtml(defaultDoc, `<frame>evil!</frame>`)).not.toContain('<frame>');
});
});
describe('should strip dangerous attributes', () => {
const dangerousAttrs = ['id', 'name', 'style'];
for (const attr of dangerousAttrs) {
it(`${attr}`, () => {
expect(sanitizeHtml(defaultDoc, `<a ${attr}="x">evil!</a>`)).toEqual('<a>evil!</a>');
});
}
});
it('should not enter an infinite loop on clobbered elements', () => {
// Some browsers are vulnerable to clobbered elements and will throw an expected exception
// IE and EDGE does not seems to be affected by those cases
// Anyway what we want to test is that browsers do not enter an infinite loop which would
// result in a timeout error for the test.
try {
sanitizeHtml(defaultDoc, '<form><input name="parentNode" /></form>');
} catch (e) {
// depending on the browser, we might ge an exception
}
try {
sanitizeHtml(defaultDoc, '<form><input name="nextSibling" /></form>');
} catch (e) {
// depending on the browser, we might ge an exception
}
try {
sanitizeHtml(defaultDoc, '<form><div><div><input name="nextSibling" /></div></div></form>');
} catch (e) {
// depending on the browser, we might ge an exception
}
});
// See
// https://github.com/cure53/DOMPurify/blob/a992d3a75031cb8bb032e5ea8399ba972bdf9a65/src/purify.js#L439-L449
it('should not allow JavaScript execution when creating inert document', () => {
const output = sanitizeHtml(defaultDoc, '<svg><g onload="window.xxx = 100"></g></svg>');
const window = defaultDoc.defaultView;
if (window) {
expect(window.xxx).toBe(undefined);
window.xxx = undefined;
}
expect(output).toEqual('');
});
// See https://github.com/cure53/DOMPurify/releases/tag/0.6.7
it('should not allow JavaScript hidden in badly formed HTML to get through sanitization (Firefox bug)',
() => {
expect(sanitizeHtml(
defaultDoc, '<svg><p><style><img src="</style><img src=x onerror=alert(1)//">'))
.toEqual(
isDOMParserAvailable() ?
// PlatformBrowser output
'<p>&lt;img src=&#34;<img src="x"></p>' :
// PlatformServer output
'<p><img src="&lt;/style&gt;&lt;img src=x onerror=alert(1)//"></p>');
});
if (browserDetection.isWebkit) {
it('should prevent mXSS attacks', function() {
// In Chrome Canary 62, the ideographic space character is kept as a stringified HTML entity
expect(sanitizeHtml(defaultDoc, '<a href="&#x3000;javascript:alert(1)">CLICKME</a>'))
.toMatch(/<a href="unsafe:(&#12288;)?javascript:alert\(1\)">CLICKME<\/a>/);
});
}
});
}
/**
* We need to determine whether the DOMParser exists in the global context.
* The try-catch is because, on some browsers, trying to access this property
* on window can actually throw an error.
*
* @suppress {uselessCode}
*/
function isDOMParserAvailable() {
try {
return !!(window as any).DOMParser;
} catch (e) {
return false;
}
}

View File

@ -1,66 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as t from '@angular/core/testing/src/testing_internal';
import {getDOM} from '../../src/dom/dom_adapter';
import {sanitizeStyle} from '../../src/security/style_sanitizer';
{
t.describe('Style sanitizer', () => {
let logMsgs: string[];
let originalLog: (msg: any) => any;
t.beforeEach(() => {
logMsgs = [];
originalLog = getDOM().log; // Monkey patch DOM.log.
getDOM().log = (msg) => logMsgs.push(msg);
});
t.afterEach(() => { getDOM().log = originalLog; });
function expectSanitize(v: string) { return t.expect(sanitizeStyle(v)); }
t.it('sanitizes values', () => {
expectSanitize('').toEqual('');
expectSanitize('abc').toEqual('abc');
expectSanitize('50px').toEqual('50px');
expectSanitize('rgb(255, 0, 0)').toEqual('rgb(255, 0, 0)');
expectSanitize('expression(haha)').toEqual('unsafe');
});
t.it('rejects unblanaced quotes', () => { expectSanitize('"value" "').toEqual('unsafe'); });
t.it('accepts transform functions', () => {
expectSanitize('rotate(90deg)').toEqual('rotate(90deg)');
expectSanitize('rotate(javascript:evil())').toEqual('unsafe');
expectSanitize('translateX(12px, -5px)').toEqual('translateX(12px, -5px)');
expectSanitize('scale3d(1, 1, 2)').toEqual('scale3d(1, 1, 2)');
});
t.it('accepts gradients', () => {
expectSanitize('linear-gradient(to bottom, #fg34a1, #bada55)')
.toEqual('linear-gradient(to bottom, #fg34a1, #bada55)');
expectSanitize('repeating-radial-gradient(ellipse cover, black, red, black, red)')
.toEqual('repeating-radial-gradient(ellipse cover, black, red, black, red)');
});
t.it('accepts calc', () => { expectSanitize('calc(90%-123px)').toEqual('calc(90%-123px)'); });
t.it('accepts attr', () => {
expectSanitize('attr(value string)').toEqual('attr(value string)');
});
t.it('sanitizes URLs', () => {
expectSanitize('url(foo/bar.png)').toEqual('url(foo/bar.png)');
expectSanitize('url( foo/bar.png\n )').toEqual('url( foo/bar.png\n )');
expectSanitize('url(javascript:evil())').toEqual('unsafe');
expectSanitize('url(strangeprotocol:evil)').toEqual('unsafe');
});
t.it('accepts quoted URLs', () => {
expectSanitize('url("foo/bar.png")').toEqual('url("foo/bar.png")');
expectSanitize(`url('foo/bar.png')`).toEqual(`url('foo/bar.png')`);
expectSanitize(`url( 'foo/bar.png'\n )`).toEqual(`url( 'foo/bar.png'\n )`);
expectSanitize('url("javascript:evil()")').toEqual('unsafe');
expectSanitize('url( " javascript:evil() " )').toEqual('unsafe');
});
});
}

View File

@ -1,118 +0,0 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as t from '@angular/core/testing/src/testing_internal';
import {getDOM} from '../../src/dom/dom_adapter';
import {sanitizeSrcset, sanitizeUrl} from '../../src/security/url_sanitizer';
{
t.describe('URL sanitizer', () => {
let logMsgs: string[];
let originalLog: (msg: any) => any;
t.beforeEach(() => {
logMsgs = [];
originalLog = getDOM().log; // Monkey patch DOM.log.
getDOM().log = (msg) => logMsgs.push(msg);
});
t.afterEach(() => { getDOM().log = originalLog; });
t.it('reports unsafe URLs', () => {
t.expect(sanitizeUrl('javascript:evil()')).toBe('unsafe:javascript:evil()');
t.expect(logMsgs.join('\n')).toMatch(/sanitizing unsafe URL value/);
});
t.describe('valid URLs', () => {
const validUrls = [
'',
'http://abc',
'HTTP://abc',
'https://abc',
'HTTPS://abc',
'ftp://abc',
'FTP://abc',
'mailto:me@example.com',
'MAILTO:me@example.com',
'tel:123-123-1234',
'TEL:123-123-1234',
'#anchor',
'/page1.md',
'http://JavaScript/my.js',
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/', // Truncated.
'data:video/webm;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/',
'data:audio/opus;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/',
];
for (const url of validUrls) {
t.it(`valid ${url}`, () => t.expect(sanitizeUrl(url)).toEqual(url));
}
});
t.describe('invalid URLs', () => {
const invalidUrls = [
'javascript:evil()',
'JavaScript:abc',
'evilNewProtocol:abc',
' \n Java\n Script:abc',
'&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;',
'&#106&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;',
'&#106 &#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;',
'&#0000106&#0000097&#0000118&#0000097&#0000115&#0000099&#0000114&#0000105&#0000112&#0000116&#0000058',
'&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A;',
'jav&#x09;ascript:alert();',
'jav\u0000ascript:alert();',
'data:;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/',
'data:,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/',
'data:iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/',
'data:text/javascript;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/',
'data:application/x-msdownload;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/',
];
for (const url of invalidUrls) {
t.it(`valid ${url}`, () => t.expect(sanitizeUrl(url)).toMatch(/^unsafe:/));
}
});
t.describe('valid srcsets', () => {
const validSrcsets = [
'',
'http://angular.io/images/test.png',
'http://angular.io/images/test.png, http://angular.io/images/test.png',
'http://angular.io/images/test.png, http://angular.io/images/test.png, http://angular.io/images/test.png',
'http://angular.io/images/test.png 2x',
'http://angular.io/images/test.png 2x, http://angular.io/images/test.png 3x',
'http://angular.io/images/test.png 1.5x',
'http://angular.io/images/test.png 1.25x',
'http://angular.io/images/test.png 200w, http://angular.io/images/test.png 300w',
'https://angular.io/images/test.png, http://angular.io/images/test.png',
'http://angular.io:80/images/test.png, http://angular.io:8080/images/test.png',
'http://www.angular.io:80/images/test.png, http://www.angular.io:8080/images/test.png',
'https://angular.io/images/test.png, https://angular.io/images/test.png',
'//angular.io/images/test.png, //angular.io/images/test.png',
'/images/test.png, /images/test.png',
'images/test.png, images/test.png',
'http://angular.io/images/test.png?12345, http://angular.io/images/test.png?12345',
'http://angular.io/images/test.png?maxage, http://angular.io/images/test.png?maxage',
'http://angular.io/images/test.png?maxage=234, http://angular.io/images/test.png?maxage=234',
];
for (const srcset of validSrcsets) {
t.it(`valid ${srcset}`, () => t.expect(sanitizeSrcset(srcset)).toEqual(srcset));
}
});
t.describe('invalid srcsets', () => {
const invalidSrcsets = [
'ht:tp://angular.io/images/test.png',
'http://angular.io/images/test.png, ht:tp://angular.io/images/test.png',
];
for (const srcset of invalidSrcsets) {
t.it(`valid ${srcset}`, () => t.expect(sanitizeSrcset(srcset)).toMatch(/unsafe:/));
}
});
});
}