Skip to content
This repository was archived by the owner on Apr 12, 2024. It is now read-only.

Commit ee8e05c

Browse files
maksimrgkalpak
authored andcommitted
feat($sanitize): support enhancing elements/attributes white-lists
Fixes #5900 Closes #16326
1 parent 9509feb commit ee8e05c

File tree

2 files changed

+176
-13
lines changed

2 files changed

+176
-13
lines changed

src/ngSanitize/sanitize.js

+126-13
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ var $sanitizeMinErr = angular.$$minErr('$sanitize');
1515
var bind;
1616
var extend;
1717
var forEach;
18+
var isArray;
1819
var isDefined;
1920
var lowercase;
2021
var noop;
@@ -145,9 +146,11 @@ var htmlSanitizeWriter;
145146
* Creates and configures {@link $sanitize} instance.
146147
*/
147148
function $SanitizeProvider() {
149+
var hasBeenInstantiated = false;
148150
var svgEnabled = false;
149151

150152
this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
153+
hasBeenInstantiated = true;
151154
if (svgEnabled) {
152155
extend(validElements, svgElements);
153156
}
@@ -188,7 +191,7 @@ function $SanitizeProvider() {
188191
* </div>
189192
*
190193
* @param {boolean=} flag Enable or disable SVG support in the sanitizer.
191-
* @returns {boolean|ng.$sanitizeProvider} Returns the currently configured value if called
194+
* @returns {boolean|$sanitizeProvider} Returns the currently configured value if called
192195
* without an argument or self for chaining otherwise.
193196
*/
194197
this.enableSvg = function(enableSvg) {
@@ -200,13 +203,113 @@ function $SanitizeProvider() {
200203
}
201204
};
202205

206+
207+
/**
208+
* @ngdoc method
209+
* @name $sanitizeProvider#addValidElements
210+
* @kind function
211+
*
212+
* @description
213+
* Extends the built-in lists of valid HTML/SVG elements, i.e. elements that are considered safe
214+
* and are not stripped off during sanitization. You can extend the following lists of elements:
215+
*
216+
* - `htmlElements`: A list of elements (tag names) to extend the current list of safe HTML
217+
* elements. HTML elements considered safe will not be removed during sanitization. All other
218+
* elements will be stripped off.
219+
*
220+
* - `htmlVoidElements`: This is similar to `htmlElements`, but marks the elements as
221+
* "void elements" (similar to HTML
222+
* [void elements](https://rawgit.com/w3c/html/html5.1-2/single-page.html#void-elements)). These
223+
* elements have no end tag and cannot have content.
224+
*
225+
* - `svgElements`: This is similar to `htmlElements`, but for SVG elements. This list is only
226+
* taken into account if SVG is {@link ngSanitize.$sanitizeProvider#enableSvg enabled} for
227+
* `$sanitize`.
228+
*
229+
* <div class="alert alert-info">
230+
* This method must be called during the {@link angular.Module#config config} phase. Once the
231+
* `$sanitize` service has been instantiated, this method has no effect.
232+
* </div>
233+
*
234+
* <div class="alert alert-warning">
235+
* Keep in mind that extending the built-in lists of elements may expose your app to XSS or
236+
* other vulnerabilities. Be very mindful of the elements you add.
237+
* </div>
238+
*
239+
* @param {Array<String>|Object} elements - A list of valid HTML elements or an object with one or
240+
* more of the following properties:
241+
* - **htmlElements** - `{Array<String>}` - A list of elements to extend the current list of
242+
* HTML elements.
243+
* - **htmlVoidElements** - `{Array<String>}` - A list of elements to extend the current list of
244+
* void HTML elements; i.e. elements that do not have an end tag.
245+
* - **svgElements** - `{Array<String>}` - A list of elements to extend the current list of SVG
246+
* elements. The list of SVG elements is only taken into account if SVG is
247+
* {@link ngSanitize.$sanitizeProvider#enableSvg enabled} for `$sanitize`.
248+
*
249+
* Passing an array (`[...]`) is equivalent to passing `{htmlElements: [...]}`.
250+
*
251+
* @return {$sanitizeProvider} Returns self for chaining.
252+
*/
253+
this.addValidElements = function(elements) {
254+
if (!hasBeenInstantiated) {
255+
if (isArray(elements)) {
256+
elements = {htmlElements: elements};
257+
}
258+
259+
addElementsTo(svgElements, elements.svgElements);
260+
addElementsTo(voidElements, elements.htmlVoidElements);
261+
addElementsTo(validElements, elements.htmlVoidElements);
262+
addElementsTo(validElements, elements.htmlElements);
263+
}
264+
265+
return this;
266+
};
267+
268+
269+
/**
270+
* @ngdoc method
271+
* @name $sanitizeProvider#addValidAttrs
272+
* @kind function
273+
*
274+
* @description
275+
* Extends the built-in list of valid attributes, i.e. attributes that are considered safe and are
276+
* not stripped off during sanitization.
277+
*
278+
* **Note**:
279+
* The new attributes will not be treated as URI attributes, which means their values will not be
280+
* sanitized as URIs using `$compileProvider`'s
281+
* {@link ng.$compileProvider#aHrefSanitizationWhitelist aHrefSanitizationWhitelist} and
282+
* {@link ng.$compileProvider#imgSrcSanitizationWhitelist imgSrcSanitizationWhitelist}.
283+
*
284+
* <div class="alert alert-info">
285+
* This method must be called during the {@link angular.Module#config config} phase. Once the
286+
* `$sanitize` service has been instantiated, this method has no effect.
287+
* </div>
288+
*
289+
* <div class="alert alert-warning">
290+
* Keep in mind that extending the built-in list of attributes may expose your app to XSS or
291+
* other vulnerabilities. Be very mindful of the attributes you add.
292+
* </div>
293+
*
294+
* @param {Array<String>} attrs - A list of valid attributes.
295+
*
296+
* @returns {$sanitizeProvider} Returns self for chaining.
297+
*/
298+
this.addValidAttrs = function(attrs) {
299+
if (!hasBeenInstantiated) {
300+
extend(validAttrs, arrayToMap(attrs, true));
301+
}
302+
return this;
303+
};
304+
203305
//////////////////////////////////////////////////////////////////////////////////////////////////
204306
// Private stuff
205307
//////////////////////////////////////////////////////////////////////////////////////////////////
206308

207309
bind = angular.bind;
208310
extend = angular.extend;
209311
forEach = angular.forEach;
312+
isArray = angular.isArray;
210313
isDefined = angular.isDefined;
211314
lowercase = angular.lowercase;
212315
noop = angular.noop;
@@ -231,36 +334,36 @@ function $SanitizeProvider() {
231334

232335
// Safe Void Elements - HTML5
233336
// http://dev.w3.org/html5/spec/Overview.html#void-elements
234-
var voidElements = toMap('area,br,col,hr,img,wbr');
337+
var voidElements = stringToMap('area,br,col,hr,img,wbr');
235338

236339
// Elements that you can, intentionally, leave open (and which close themselves)
237340
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
238-
var optionalEndTagBlockElements = toMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'),
239-
optionalEndTagInlineElements = toMap('rp,rt'),
341+
var optionalEndTagBlockElements = stringToMap('colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr'),
342+
optionalEndTagInlineElements = stringToMap('rp,rt'),
240343
optionalEndTagElements = extend({},
241344
optionalEndTagInlineElements,
242345
optionalEndTagBlockElements);
243346

244347
// Safe Block Elements - HTML5
245-
var blockElements = extend({}, optionalEndTagBlockElements, toMap('address,article,' +
348+
var blockElements = extend({}, optionalEndTagBlockElements, stringToMap('address,article,' +
246349
'aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5,' +
247350
'h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,section,table,ul'));
248351

249352
// Inline Elements - HTML5
250-
var inlineElements = extend({}, optionalEndTagInlineElements, toMap('a,abbr,acronym,b,' +
353+
var inlineElements = extend({}, optionalEndTagInlineElements, stringToMap('a,abbr,acronym,b,' +
251354
'bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s,' +
252355
'samp,small,span,strike,strong,sub,sup,time,tt,u,var'));
253356

254357
// SVG Elements
255358
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Elements
256359
// Note: the elements animate,animateColor,animateMotion,animateTransform,set are intentionally omitted.
257360
// They can potentially allow for arbitrary javascript to be executed. See #11290
258-
var svgElements = toMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' +
361+
var svgElements = stringToMap('circle,defs,desc,ellipse,font-face,font-face-name,font-face-src,g,glyph,' +
259362
'hkern,image,linearGradient,line,marker,metadata,missing-glyph,mpath,path,polygon,polyline,' +
260363
'radialGradient,rect,stop,svg,switch,text,title,tspan');
261364

262365
// Blocked Elements (will be stripped)
263-
var blockedElements = toMap('script,style');
366+
var blockedElements = stringToMap('script,style');
264367

265368
var validElements = extend({},
266369
voidElements,
@@ -269,17 +372,17 @@ function $SanitizeProvider() {
269372
optionalEndTagElements);
270373

271374
//Attributes that have href and hence need to be sanitized
272-
var uriAttrs = toMap('background,cite,href,longdesc,src,xlink:href,xml:base');
375+
var uriAttrs = stringToMap('background,cite,href,longdesc,src,xlink:href,xml:base');
273376

274-
var htmlAttrs = toMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
377+
var htmlAttrs = stringToMap('abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,' +
275378
'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,' +
276379
'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,' +
277380
'scope,scrolling,shape,size,span,start,summary,tabindex,target,title,type,' +
278381
'valign,value,vspace,width');
279382

280383
// SVG attributes (without "id" and "name" attributes)
281384
// https://wiki.whatwg.org/wiki/Sanitization_rules#svg_Attributes
282-
var svgAttrs = toMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
385+
var svgAttrs = stringToMap('accent-height,accumulate,additive,alphabetic,arabic-form,ascent,' +
283386
'baseProfile,bbox,begin,by,calcMode,cap-height,class,color,color-rendering,content,' +
284387
'cx,cy,d,dx,dy,descent,display,dur,end,fill,fill-rule,font-family,font-size,font-stretch,' +
285388
'font-style,font-variant,font-weight,from,fx,fy,g1,g2,glyph-name,gradientUnits,hanging,' +
@@ -300,14 +403,24 @@ function $SanitizeProvider() {
300403
svgAttrs,
301404
htmlAttrs);
302405

303-
function toMap(str, lowercaseKeys) {
304-
var obj = {}, items = str.split(','), i;
406+
function stringToMap(str, lowercaseKeys) {
407+
return arrayToMap(str.split(','), lowercaseKeys);
408+
}
409+
410+
function arrayToMap(items, lowercaseKeys) {
411+
var obj = {}, i;
305412
for (i = 0; i < items.length; i++) {
306413
obj[lowercaseKeys ? lowercase(items[i]) : items[i]] = true;
307414
}
308415
return obj;
309416
}
310417

418+
function addElementsTo(elementsMap, newElements) {
419+
if (newElements && newElements.length) {
420+
extend(elementsMap, arrayToMap(newElements));
421+
}
422+
}
423+
311424
/**
312425
* Create an inert document that contains the dirty HTML that needs sanitizing
313426
* Depending upon browser support we use one of three strategies for doing this.

test/ngSanitize/sanitizeSpec.js

+50
Original file line numberDiff line numberDiff line change
@@ -293,10 +293,56 @@ describe('HTML', function() {
293293
expect(doc).toEqual('<p><img src="x"></p>');
294294
}));
295295

296+
describe('Custom white-list support', function() {
297+
298+
var $sanitizeProvider;
299+
beforeEach(module(function(_$sanitizeProvider_) {
300+
$sanitizeProvider = _$sanitizeProvider_;
301+
302+
$sanitizeProvider.addValidElements(['foo']);
303+
$sanitizeProvider.addValidElements({
304+
htmlElements: ['foo-button', 'foo-video'],
305+
htmlVoidElements: ['foo-input'],
306+
svgElements: ['foo-svg']
307+
});
308+
$sanitizeProvider.addValidAttrs(['foo']);
309+
}));
310+
311+
it('should allow custom white-listed element', function() {
312+
expectHTML('<foo></foo>').toEqual('<foo></foo>');
313+
expectHTML('<foo-button></foo-button>').toEqual('<foo-button></foo-button>');
314+
expectHTML('<foo-video></foo-video>').toEqual('<foo-video></foo-video>');
315+
});
316+
317+
it('should allow custom white-listed void element', function() {
318+
expectHTML('<foo-input/>').toEqual('<foo-input>');
319+
});
320+
321+
it('should allow custom white-listed void element to be used with closing tag', function() {
322+
expectHTML('<foo-input></foo-input>').toEqual('<foo-input>');
323+
});
324+
325+
it('should allow custom white-listed attribute', function() {
326+
expectHTML('<foo-input foo="foo"/>').toEqual('<foo-input foo="foo">');
327+
});
328+
329+
it('should ignore custom white-listed SVG element if SVG disabled', function() {
330+
expectHTML('<foo-svg></foo-svg>').toEqual('');
331+
});
332+
333+
it('should not allow add custom element after service has been instantiated', inject(function($sanitize) {
334+
$sanitizeProvider.addValidElements(['bar']);
335+
expectHTML('<bar></bar>').toEqual('');
336+
}));
337+
});
338+
296339
describe('SVG support', function() {
297340

298341
beforeEach(module(function($sanitizeProvider) {
299342
$sanitizeProvider.enableSvg(true);
343+
$sanitizeProvider.addValidElements({
344+
svgElements: ['font-face-uri']
345+
});
300346
}));
301347

302348
it('should accept SVG tags', function() {
@@ -314,6 +360,10 @@ describe('HTML', function() {
314360

315361
});
316362

363+
it('should allow custom white-listed SVG element', function() {
364+
expectHTML('<font-face-uri></font-face-uri>').toEqual('<font-face-uri></font-face-uri>');
365+
});
366+
317367
it('should sanitize SVG xlink:href attribute values', function() {
318368
expectHTML('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a xlink:href="javascript:alert()"></a></svg>')
319369
.toBeOneOf('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><a></a></svg>',

0 commit comments

Comments
 (0)