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

Commit 2df43c0

Browse files
committed
fix(jqLite): prevent possible XSS due to regex-based HTML replacement
This also splits the wrapping logic to one for modern browsers & one for IE 9 as IE 9 has restrictions that make it impossible to make it as secure.
1 parent 295213d commit 2df43c0

File tree

5 files changed

+177
-15
lines changed

5 files changed

+177
-15
lines changed

src/.eslintrc.json

+1
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@
100100
"VALIDITY_STATE_PROPERTY": false,
101101
"reloadWithDebugInfo": false,
102102
"stringify": false,
103+
"UNSAFE_restoreLegacyJqLiteXHTMLReplacement": false,
103104

104105
"NODE_TYPE_ELEMENT": false,
105106
"NODE_TYPE_ATTRIBUTE": false,

src/Angular.js

+21
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@
9393
hasOwnProperty,
9494
createMap,
9595
stringify,
96+
UNSAFE_restoreLegacyJqLiteXHTMLReplacement,
9697
9798
NODE_TYPE_ELEMENT,
9899
NODE_TYPE_ATTRIBUTE,
@@ -1949,6 +1950,26 @@ function bindJQuery() {
19491950
bindJQueryFired = true;
19501951
}
19511952

1953+
/**
1954+
* @ngdoc function
1955+
* @name angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement
1956+
* @module ng
1957+
* @kind function
1958+
*
1959+
* @description
1960+
* Restores the pre-1.8 behavior of jqLite that turns XHTML-like strings like
1961+
* `<div /><span />` to `<div></div><span></span>` instead of `<div><span></span></div>`.
1962+
* The new behavior is a security fix so if you use this method, please try to adjust
1963+
* to the change & remove the call as soon as possible.
1964+
1965+
* Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read
1966+
* [jQuery 3.5 upgrade guide](https://jquery.com/upgrade-guide/3.5/) for more details
1967+
* about the workarounds.
1968+
*/
1969+
function UNSAFE_restoreLegacyJqLiteXHTMLReplacement() {
1970+
JQLite.legacyXHTMLReplacement = true;
1971+
}
1972+
19521973
/**
19531974
* throw error if the argument is falsy.
19541975
*/

src/AngularPublic.js

+1
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ function publishExternalAPI(angular) {
156156
'callbacks': {$$counter: 0},
157157
'getTestability': getTestability,
158158
'reloadWithDebugInfo': reloadWithDebugInfo,
159+
'UNSAFE_restoreLegacyJqLiteXHTMLReplacement': UNSAFE_restoreLegacyJqLiteXHTMLReplacement,
159160
'$$minErr': minErr,
160161
'$$csp': csp,
161162
'$$encodeUriSegment': encodeUriSegment,

src/jqLite.js

+58-15
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,16 @@
9090
* - [`val()`](http://api.jquery.com/val/)
9191
* - [`wrap()`](http://api.jquery.com/wrap/)
9292
*
93+
* jqLite also provides a method restoring pre-1.8 insecure treatment of XHTML-like tags
94+
* that makes input like `<div /><span />` turned to `<div></div><span></span>` instead of
95+
* `<div><span></span></div>` like version 1.8 & newer do:
96+
* ```js
97+
* angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement();
98+
* ```
99+
* Note that this only patches jqLite. If you use jQuery 3.5.0 or newer, please read
100+
* [jQuery 3.5 upgrade guide](https://jquery.com/upgrade-guide/3.5/) for more details
101+
* about the workarounds.
102+
*
93103
* ## jQuery/jqLite Extras
94104
* AngularJS also provides the following additional methods and events to both jQuery and jqLite:
95105
*
@@ -169,20 +179,36 @@ var HTML_REGEXP = /<|&#?\w+;/;
169179
var TAG_NAME_REGEXP = /<([\w:-]+)/;
170180
var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
171181

182+
// Table parts need to be wrapped with `<table>` or they're
183+
// stripped to their contents when put in a div.
184+
// XHTML parsers do not magically insert elements in the
185+
// same way that tag soup parsers do, so we cannot shorten
186+
// this by omitting <tbody> or other required elements.
172187
var wrapMap = {
173-
'option': [1, '<select multiple="multiple">', '</select>'],
174-
175-
'thead': [1, '<table>', '</table>'],
176-
'col': [2, '<table><colgroup>', '</colgroup></table>'],
177-
'tr': [2, '<table><tbody>', '</tbody></table>'],
178-
'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
179-
'_default': [0, '', '']
188+
thead: ['table'],
189+
col: ['colgroup', 'table'],
190+
tr: ['tbody', 'table'],
191+
td: ['tr', 'tbody', 'table']
180192
};
181193

182-
wrapMap.optgroup = wrapMap.option;
183194
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
184195
wrapMap.th = wrapMap.td;
185196

197+
// Support: IE <10 only
198+
// IE 9 requires an option wrapper & it needs to have the whole table structure
199+
// set up up front; assigning `"<td></td>"` to `tr.innerHTML` doesn't work, etc.
200+
var wrapMapIE9 = {
201+
option: [1, '<select multiple="multiple">', '</select>'],
202+
_default: [0, '', '']
203+
};
204+
205+
for (var key in wrapMap) {
206+
var wrapMapValueClosing = wrapMap[key];
207+
var wrapMapValue = wrapMapValueClosing.slice().reverse();
208+
wrapMapIE9[key] = [wrapMapValue.length, '<' + wrapMapValue.join('><') + '>', '</' + wrapMapValueClosing.join('></') + '>'];
209+
}
210+
211+
wrapMapIE9.optgroup = wrapMapIE9.option;
186212

187213
function jqLiteIsTextNode(html) {
188214
return !HTML_REGEXP.test(html);
@@ -203,7 +229,7 @@ function jqLiteHasData(node) {
203229
}
204230

205231
function jqLiteBuildFragment(html, context) {
206-
var tmp, tag, wrap,
232+
var tmp, tag, wrap, finalHtml,
207233
fragment = context.createDocumentFragment(),
208234
nodes = [], i;
209235

@@ -214,13 +240,30 @@ function jqLiteBuildFragment(html, context) {
214240
// Convert html into DOM nodes
215241
tmp = fragment.appendChild(context.createElement('div'));
216242
tag = (TAG_NAME_REGEXP.exec(html) || ['', ''])[1].toLowerCase();
217-
wrap = wrapMap[tag] || wrapMap._default;
218-
tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, '<$1></$2>') + wrap[2];
243+
finalHtml = JQLite.legacyXHTMLReplacement ?
244+
html.replace(XHTML_TAG_REGEXP, '<$1></$2>') :
245+
html;
246+
247+
if (msie < 10) {
248+
wrap = wrapMapIE9[tag] || wrapMapIE9._default;
249+
tmp.innerHTML = wrap[1] + finalHtml + wrap[2];
250+
251+
// Descend through wrappers to the right content
252+
i = wrap[0];
253+
while (i--) {
254+
tmp = tmp.firstChild;
255+
}
256+
} else {
257+
wrap = wrapMap[tag] || [];
219258

220-
// Descend through wrappers to the right content
221-
i = wrap[0];
222-
while (i--) {
223-
tmp = tmp.lastChild;
259+
// Create wrappers & descend into them
260+
i = wrap.length;
261+
while (--i > -1) {
262+
tmp.appendChild(window.document.createElement(wrap[i]));
263+
tmp = tmp.firstChild;
264+
}
265+
266+
tmp.innerHTML = finalHtml;
224267
}
225268

226269
nodes = concat(nodes, tmp.childNodes);

test/jqLiteSpec.js

+96
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,13 @@ describe('jqLite', function() {
147147
expect(nodes[0].nodeName.toLowerCase()).toBe('option');
148148
});
149149

150+
it('should allow construction of multiple <option> elements', function() {
151+
var nodes = jqLite('<option></option><option></option>');
152+
expect(nodes.length).toBe(2);
153+
expect(nodes[0].nodeName.toLowerCase()).toBe('option');
154+
expect(nodes[1].nodeName.toLowerCase()).toBe('option');
155+
});
156+
150157

151158
// Special tests for the construction of elements which are restricted (in the HTML5 spec) to
152159
// being children of specific nodes.
@@ -169,6 +176,95 @@ describe('jqLite', function() {
169176
expect(nodes[0].nodeName.toLowerCase()).toBe(name);
170177
});
171178
});
179+
180+
describe('security', function() {
181+
it('shouldn\'t crash at attempts to close the table wrapper', function() {
182+
// jQuery doesn't pass this test yet.
183+
if (!_jqLiteMode) return;
184+
185+
// Support: IE <10
186+
// In IE 9 we still need to use the old-style innerHTML assignment
187+
// as that's the only one that works.
188+
if (msie < 10) return;
189+
190+
expect(function() {
191+
// This test case attempts to close the tags which wrap input
192+
// based on matching done in wrapMap, escaping the wrapper & thus
193+
// triggering an error when descending.
194+
var el = jqLite('<td></td></tr></tbody></table><td></td>');
195+
expect(el.length).toBe(2);
196+
expect(el[0].nodeName.toLowerCase()).toBe('td');
197+
expect(el[1].nodeName.toLowerCase()).toBe('td');
198+
}).not.toThrow();
199+
});
200+
201+
it('shouldn\'t unsanitize sanitized code', function(done) {
202+
// jQuery <3.5.0 fail those tests.
203+
if (isJQuery2x()) {
204+
done();
205+
return;
206+
}
207+
208+
var counter = 0,
209+
assertCount = 13,
210+
container = jqLite('<div></div>');
211+
212+
function donePartial() {
213+
counter++;
214+
if (counter === assertCount) {
215+
container.remove();
216+
delete window.xss;
217+
done();
218+
}
219+
}
220+
221+
jqLite(document.body).append(container);
222+
window.xss = jasmine.createSpy('xss');
223+
224+
// Thanks to Masato Kinugawa from Cure53 for providing the following test cases.
225+
// Note: below test cases need to invoke the xss function with consecutive
226+
// decimal parameters for the assertions to be correct.
227+
forEach([
228+
'<img alt="<x" title="/><img src=url404 onerror=xss(0)>">',
229+
'<img alt="\n<x" title="/>\n<img src=url404 onerror=xss(1)>">',
230+
'<style><style/><img src=url404 onerror=xss(2)>',
231+
'<xmp><xmp/><img src=url404 onerror=xss(3)>',
232+
'<title><title /><img src=url404 onerror=xss(4)>',
233+
'<iframe><iframe/><img src=url404 onerror=xss(5)>',
234+
'<noframes><noframes/><img src=url404 onerror=xss(6)>',
235+
'<noscript><noscript/><img src=url404 onerror=xss(7)>',
236+
'<foo" alt="" title="/><img src=url404 onerror=xss(8)>">',
237+
'<img alt="<x" title="" src="/><img src=url404 onerror=xss(9)>">',
238+
'<noscript/><img src=url404 onerror=xss(10)>',
239+
'<noembed><noembed/><img src=url404 onerror=xss(11)>',
240+
241+
'<option><style></option></select><img src=url404 onerror=xss(12)></style>'
242+
], function(htmlString, index) {
243+
var element = jqLite('<div></div>');
244+
245+
container.append(element);
246+
element.append(jqLite(htmlString));
247+
248+
window.setTimeout(function() {
249+
expect(window.xss).not.toHaveBeenCalledWith(index);
250+
donePartial();
251+
}, 1000);
252+
});
253+
});
254+
255+
it('should allow to restore legacy insecure behavior', function() {
256+
// jQuery doesn't have this API.
257+
if (!_jqLiteMode) return;
258+
259+
// eslint-disable-next-line new-cap
260+
angular.UNSAFE_restoreLegacyJqLiteXHTMLReplacement();
261+
262+
var elem = jqLite('<div/><span/>');
263+
expect(elem.length).toBe(2);
264+
expect(elem[0].nodeName.toLowerCase()).toBe('div');
265+
expect(elem[1].nodeName.toLowerCase()).toBe('span');
266+
});
267+
});
172268
});
173269

174270
describe('_data', function() {

0 commit comments

Comments
 (0)