From 0b51380798ed7cc0432e7d5b71aada82b6bc9e35 Mon Sep 17 00:00:00 2001 From: Maksim Ryzhikov Date: Sat, 11 Nov 2017 16:18:17 +0300 Subject: [PATCH 1/3] feat($sanitize): support enhancing white-list --- src/ngSanitize/sanitize.js | 90 ++++++++++++++++++++++++++++----- test/ngSanitize/sanitizeSpec.js | 50 ++++++++++++++++++ 2 files changed, 128 insertions(+), 12 deletions(-) diff --git a/src/ngSanitize/sanitize.js b/src/ngSanitize/sanitize.js index b08850fba065..afb4dc9cf086 100644 --- a/src/ngSanitize/sanitize.js +++ b/src/ngSanitize/sanitize.js @@ -16,6 +16,8 @@ var bind; var extend; var forEach; var isDefined; +var isArray; +var isObject; var lowercase; var noop; var nodeContains; @@ -145,8 +147,10 @@ var htmlSanitizeWriter; */ function $SanitizeProvider() { var svgEnabled = false; + var hasBeenInstantiated = false; this.$get = ['$$sanitizeUri', function($$sanitizeUri) { + hasBeenInstantiated = true; if (svgEnabled) { extend(validElements, svgElements); } @@ -199,6 +203,56 @@ function $SanitizeProvider() { } }; + + /** + * @ngdoc method + * @name $sanitizeProvider#addValidElements + * @kind function + * + * @param {Array|Object} elements List of valid elements. + * + * Object properties: + * + * - `svgElements` – `{string[]=}` – An array of SVG elements' names. + * - `htmlVoidElements` – `{string[]=}` – An array of void elements' names. + * - `htmlElements` – `{string[]=}` – An array of html elements' names. + */ + this.addValidElements = function(elements) { + if (hasBeenInstantiated) return this; + + if (isArray(elements)) { + addElementsTo(validElements, elements); + return this; + } + + if (isObject(elements)) { + addElementsTo(svgElements, elements['svgElements']); + addElementsTo(voidElements, elements['htmlVoidElements']); + addElementsTo(validElements, elements['htmlVoidElements']); + addElementsTo(validElements, elements['htmlElements']); + } + + return this; + }; + + + /** + * @ngdoc method + * @name $sanitizeProvider#addValidAttrs + * @kind function + * + * @description + * The added attributes will not be treated as URI attributes, which means their values will + * not sanitized as URIs using the aHrefSanitizationWhitelist and imgSrcSanitizationWhitelist of {@link ng.$compileProvider $compileProvider}. + * + * @param {Array} attrs List of valid attributes + */ + this.addValidAttrs = function(attrs) { + if (hasBeenInstantiated) return this; + extend(validAttrs, arrayToMap(attrs, true)); + return this; + }; + ////////////////////////////////////////////////////////////////////////////////////////////////// // Private stuff ////////////////////////////////////////////////////////////////////////////////////////////////// @@ -207,6 +261,8 @@ function $SanitizeProvider() { extend = angular.extend; forEach = angular.forEach; isDefined = angular.isDefined; + isArray = angular.isArray; + isObject = angular.isObject; lowercase = angular.$$lowercase; noop = angular.noop; @@ -230,23 +286,23 @@ function $SanitizeProvider() { // Safe Void Elements - HTML5 // http://dev.w3.org/html5/spec/Overview.html#void-elements - var voidElements = toMap('area,br,col,hr,img,wbr'); + var voidElements = stringToMap('area,br,col,hr,img,wbr'); // Elements that you can, intentionally, leave open (and which close themselves) // http://dev.w3.org/html5/spec/Overview.html#optional-tags - var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'), - optionalEndTagInlineElements = toMap('rp,rt'), + var optionalEndTagBlockElements = stringToMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'), + optionalEndTagInlineElements = stringToMap('rp,rt'), optionalEndTagElements = extend({}, optionalEndTagInlineElements, optionalEndTagBlockElements); // Safe Block Elements - HTML5 - var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' + + var blockElements = extend({}, optionalEndTagBlockElements, stringToMap('address,article,' + 'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' + 'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul')); // Inline Elements - HTML5 - var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' + + var inlineElements = extend({}, optionalEndTagInlineElements, stringToMap('a,abbr,acronym,b,' + 'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' + 'samp,small,span,strike,strong,sub,sup,time,tt,u,var')); @@ -254,12 +310,12 @@ function $SanitizeProvider() { // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements // Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted. // They can potentially allow for arbitrary javascript to be executed. See #11290 - var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' + + var svgElements = stringToMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' + 'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' + 'radialGradient,rect,stop,svg,switch,text,title,tspan'); // Blocked Elements (will be stripped) - var blockedElements = toMap('script,style'); + var blockedElements = stringToMap('script,style'); var validElements = extend({}, voidElements, @@ -268,9 +324,9 @@ function $SanitizeProvider() { optionalEndTagElements); //Attributes that have href and hence need to be sanitized - var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href,xml:base'); + var uriAttrs = stringToMap('background,cite,href,longdesc,src,xlink:href,xml:base'); - var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + + var htmlAttrs = stringToMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' + 'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' + 'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' + 'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' + @@ -278,7 +334,7 @@ function $SanitizeProvider() { // SVG attributes (without "id" and "name" attributes) // https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes - var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + + var svgAttrs = stringToMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' + 'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' + 'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' + 'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' + @@ -299,14 +355,24 @@ function $SanitizeProvider() { svgAttrs, htmlAttrs); - function toMap(str, lowercaseKeys) { - var obj = {}, items = str.split(','), i; + function stringToMap(str, lowercaseKeys) { + return arrayToMap(str.split(','), lowercaseKeys); + } + + function arrayToMap(items, lowercaseKeys) { + var obj = {}, i; for (i = 0; i < items.length; i++) { obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true; } return obj; } + function addElementsTo(elementsMap, newElements) { + if (newElements && newElements.length) { + extend(elementsMap, arrayToMap(newElements)); + } + } + /** * Create an inert document that contains the dirty HTML that needs sanitizing * Depending upon browser support we use one of three strategies for doing this. diff --git a/test/ngSanitize/sanitizeSpec.js b/test/ngSanitize/sanitizeSpec.js index 69cb6abc9fda..a047be989642 100644 --- a/test/ngSanitize/sanitizeSpec.js +++ b/test/ngSanitize/sanitizeSpec.js @@ -293,10 +293,56 @@ describe('HTML', function() { expect(doc).toEqual('

'); })); + describe('Custom white-list support', function() { + + var $sanitizeProvider; + beforeEach(module(function(_$sanitizeProvider_) { + $sanitizeProvider = _$sanitizeProvider_; + + $sanitizeProvider.addValidElements(['foo']); + $sanitizeProvider.addValidElements({ + htmlElements: ['foo-button', 'foo-video'], + htmlVoidElements: ['foo-input'], + svgElements: ['foo-svg'] + }); + $sanitizeProvider.addValidAttrs(['foo']); + })); + + it('should allow custom white-listed element', function() { + expectHTML('').toEqual(''); + expectHTML('').toEqual(''); + expectHTML('').toEqual(''); + }); + + it('should allow custom white-listed void element', function() { + expectHTML('').toEqual(''); + }); + + it('should allow custom white-listed void element to be used with closing tag', function() { + expectHTML('').toEqual(''); + }); + + it('should allow custom white-listed attribute', function() { + expectHTML('').toEqual(''); + }); + + it('should ignore custom white-listed SVG element if SVG disabled', function() { + expectHTML('').toEqual(''); + }); + + it('should not allow add custom element after service has been instantiated', inject(function($sanitize) { + $sanitizeProvider.addValidElements(['bar']); + expectHTML('').toEqual(''); + })); + }); + describe('SVG support', function() { beforeEach(module(function($sanitizeProvider) { $sanitizeProvider.enableSvg(true); + $sanitizeProvider.addValidElements({ + svgElements: ['font-face-uri'] + }); })); it('should accept SVG tags', function() { @@ -314,6 +360,10 @@ describe('HTML', function() { }); + it('should allow custom white-listed SVG element', function() { + expectHTML('').toEqual(''); + }); + it('should sanitize SVG xlink:href attribute values', function() { expectHTML('') .toBeOneOf('', From 19204204e57487fde16cccd02dbd21e1f70593b6 Mon Sep 17 00:00:00 2001 From: George Kalpakas Date: Mon, 5 Feb 2018 15:40:51 +0200 Subject: [PATCH 2/3] fixup! feat($sanitize): support enhancing white-list --- src/ngSanitize/sanitize.js | 86 +++++++++++++++++++++++++++----------- 1 file changed, 62 insertions(+), 24 deletions(-) diff --git a/src/ngSanitize/sanitize.js b/src/ngSanitize/sanitize.js index afb4dc9cf086..ffb9d6567cde 100644 --- a/src/ngSanitize/sanitize.js +++ b/src/ngSanitize/sanitize.js @@ -15,8 +15,8 @@ var $sanitizeMinErr = angular.$$minErr('$sanitize'); var bind; var extend; var forEach; -var isDefined; var isArray; +var isDefined; var isObject; var lowercase; var noop; @@ -146,8 +146,8 @@ var htmlSanitizeWriter; * Creates and configures {@link $sanitize} instance. */ function $SanitizeProvider() { - var svgEnabled = false; var hasBeenInstantiated = false; + var svgEnabled = false; this.$get = ['$$sanitizeUri', function($$sanitizeUri) { hasBeenInstantiated = true; @@ -191,7 +191,7 @@ function $SanitizeProvider() { * * * @param {boolean=} flag Enable or disable SVG support in the sanitizer. - * @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called + * @returns {boolean|$sanitizeProvider} Returns the currently configured value if called * without an argument or self for chaining otherwise. */ this.enableSvg = function(enableSvg) { @@ -209,27 +209,51 @@ function $SanitizeProvider() { * @name $sanitizeProvider#addValidElements * @kind function * - * @param {Array|Object} elements List of valid elements. + * @description + * Extends the built-in lists of valid HTML/SVG elements, i.e. elements that are considered safe + * and are not stripped off during sanitization. You can extend the following lists: + * + * - `htmlElements`: A list of elements (tag names) to extend the current list of safe HTML + * elements. HTML elements considered safe will not be removed during sanitization. All other + * elements will be stripped off. + * + * - `htmlVoidElements`: This is similar to `htmlElements`, but in addition allows the specified + * elements to have no end tag (similar to HTML + * [void elements](https://rawgit.com/w3c/html/html5.1-2/single-page.html#void-elements)). + * + * - `svgElements`: This is similar to `htmlElements`, but for SVG elements. This list is only + * taken into account if SVG is {@link ngSanitize.$sanitizeProvider#enableSvg enabled} for + * `$sanitize`. + * + *
+ * This method must be called during the {@link angular.Module#config config} phase. Once the + * `$sanitize` service has been instantiated, this method has no effect. + *
+ * + * @param {Array|Object} elements - A list of valid HTML elements or an object with one or + * more of the following properties: + * - **htmlElements** - `{Array}` - A list of elements to extend the current list of + * HTML elements. + * - **htmlVoidElements** - `{Array}` - A list of elements to extend the current list of + * void HTML elements; i.e. elements that do not have an end tag. + * - **svgElements** - `{Array}` - A list of elements to extend the current list of SVG + * elements. The list of SVG elements is only taken into account if SVG is + * {@link ngSanitize.$sanitizeProvider#enableSvg enabled} for `$sanitize`. * - * Object properties: + * Passing an array (`[...]`) is equivalent to passing `{htmlElements: [...]}`. * - * - `svgElements` – `{string[]=}` – An array of SVG elements' names. - * - `htmlVoidElements` – `{string[]=}` – An array of void elements' names. - * - `htmlElements` – `{string[]=}` – An array of html elements' names. + * @return {$sanitizeProvider} Returns self for chaining. */ this.addValidElements = function(elements) { - if (hasBeenInstantiated) return this; - - if (isArray(elements)) { - addElementsTo(validElements, elements); - return this; - } + if (!hasBeenInstantiated) { + if (isArray(elements)) { + elements = {htmlElements: elements}; + } - if (isObject(elements)) { - addElementsTo(svgElements, elements['svgElements']); - addElementsTo(voidElements, elements['htmlVoidElements']); - addElementsTo(validElements, elements['htmlVoidElements']); - addElementsTo(validElements, elements['htmlElements']); + addElementsTo(svgElements, elements.svgElements); + addElementsTo(voidElements, elements.htmlVoidElements); + addElementsTo(validElements, elements.htmlVoidElements); + addElementsTo(validElements, elements.htmlElements); } return this; @@ -242,14 +266,28 @@ function $SanitizeProvider() { * @kind function * * @description - * The added attributes will not be treated as URI attributes, which means their values will - * not sanitized as URIs using the aHrefSanitizationWhitelist and imgSrcSanitizationWhitelist of {@link ng.$compileProvider $compileProvider}. + * Extends the built-in list of valid attributes, i.e. attributes that are considered safe and are + * not stripped off during sanitization. + * + * **Note**: + * The new attributes will not be treated as URI attributes, which means their values will not be + * sanitized as URIs using `$compileProvider`'s + * {@link ng.$compileProvider#aHrefSanitizationWhitelist aHrefSanitizationWhitelist} and + * {@link ng.$compileProvider#imgSrcSanitizationWhitelist imgSrcSanitizationWhitelist}. * - * @param {Array} attrs List of valid attributes + *
+ * This method must be called during the {@link angular.Module#config config} phase. Once the + * `$sanitize` service has been instantiated, this method has no effect. + *
+ * + * @param {Array} attrs - A list of valid attributes. + * + * @returns {$sanitizeProvider} Returns self for chaining. */ this.addValidAttrs = function(attrs) { - if (hasBeenInstantiated) return this; - extend(validAttrs, arrayToMap(attrs, true)); + if (!hasBeenInstantiated) { + extend(validAttrs, arrayToMap(attrs, true)); + } return this; }; From fc05208a628c8d7f6277ef16fdbecd4410871ba0 Mon Sep 17 00:00:00 2001 From: George Kalpakas Date: Tue, 6 Feb 2018 14:05:11 +0200 Subject: [PATCH 3/3] fixup! fixup! feat($sanitize): support enhancing white-list --- src/ngSanitize/sanitize.js | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/ngSanitize/sanitize.js b/src/ngSanitize/sanitize.js index ffb9d6567cde..5d2f36616b85 100644 --- a/src/ngSanitize/sanitize.js +++ b/src/ngSanitize/sanitize.js @@ -211,25 +211,31 @@ function $SanitizeProvider() { * * @description * Extends the built-in lists of valid HTML/SVG elements, i.e. elements that are considered safe - * and are not stripped off during sanitization. You can extend the following lists: + * and are not stripped off during sanitization. You can extend the following lists of elements: * * - `htmlElements`: A list of elements (tag names) to extend the current list of safe HTML * elements. HTML elements considered safe will not be removed during sanitization. All other * elements will be stripped off. * - * - `htmlVoidElements`: This is similar to `htmlElements`, but in addition allows the specified - * elements to have no end tag (similar to HTML - * [void elements](https://rawgit.com/w3c/html/html5.1-2/single-page.html#void-elements)). + * - `htmlVoidElements`: This is similar to `htmlElements`, but marks the elements as + * "void elements" (similar to HTML + * [void elements](https://rawgit.com/w3c/html/html5.1-2/single-page.html#void-elements)). These + * elements have no end tag and cannot have content. * * - `svgElements`: This is similar to `htmlElements`, but for SVG elements. This list is only * taken into account if SVG is {@link ngSanitize.$sanitizeProvider#enableSvg enabled} for * `$sanitize`. * - *
+ *
* This method must be called during the {@link angular.Module#config config} phase. Once the * `$sanitize` service has been instantiated, this method has no effect. *
* + *
+ * Keep in mind that extending the built-in lists of elements may expose your app to XSS or + * other vulnerabilities. Be very mindful of the elements you add. + *
+ * * @param {Array|Object} elements - A list of valid HTML elements or an object with one or * more of the following properties: * - **htmlElements** - `{Array}` - A list of elements to extend the current list of @@ -275,11 +281,16 @@ function $SanitizeProvider() { * {@link ng.$compileProvider#aHrefSanitizationWhitelist aHrefSanitizationWhitelist} and * {@link ng.$compileProvider#imgSrcSanitizationWhitelist imgSrcSanitizationWhitelist}. * - *
+ *
* This method must be called during the {@link angular.Module#config config} phase. Once the * `$sanitize` service has been instantiated, this method has no effect. *
* + *
+ * Keep in mind that extending the built-in list of attributes may expose your app to XSS or + * other vulnerabilities. Be very mindful of the attributes you add. + *
+ * * @param {Array} attrs - A list of valid attributes. * * @returns {$sanitizeProvider} Returns self for chaining.