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

Commit bea9422

Browse files
committed
feat($sce): new $sce service for Strict Contextual Escaping.
$sce is a service that provides Strict Contextual Escaping services to AngularJS. Strict Contextual Escaping -------------------------- Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain contexts to result in a value that is marked as safe to use for that context One example of such a context is binding arbitrary html controlled by the user via ng-bind-html-unsafe. We refer to these contexts as privileged or SCE contexts. As of version 1.2, Angular ships with SCE enabled by default. Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows one to execute arbitrary javascript by the use of the expression() syntax. Refer http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx to learn more about them. You can ensure your document is in standards mode and not quirks mode by adding <!doctype html> to the top of your HTML document. SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for security vulnerabilities such as XSS, clickjacking, etc. a lot easier. Here's an example of a binding in a privileged context: <input ng-model="userHtml"> <div ng-bind-html-unsafe="{{userHtml}}"> Notice that ng-bind-html-unsafe is bound to {{userHtml}} controlled by the user. With SCE disabled, this application allows the user to render arbitrary HTML into the DIV. In a more realistic example, one may be rendering user comments, blog articles, etc. via bindings. (HTML is just one example of a context where rendering user controlled input creates security vulnerabilities.) For the case of HTML, you might use a library, either on the client side, or on the server side, to sanitize unsafe HTML before binding to the value and rendering it in the document. How would you ensure that every place that used these types of bindings was bound to a value that was sanitized by your library (or returned as safe for rendering by your server?) How can you ensure that you didn't accidentally delete the line that sanitized the value, or renamed some properties/fields and forgot to update the binding to the sanitized value? To be secure by default, you want to ensure that any such bindings are disallowed unless you can determine that something explicitly says it's safe to use a value for binding in that context. You can then audit your code (a simple grep would do) to ensure that this is only done for those values that you can easily tell are safe - because they were received from your server, sanitized by your library, etc. You can organize your codebase to help with this - perhaps allowing only the files in a specific directory to do this. Ensuring that the internal API exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task. In the case of AngularJS' SCE service, one uses $sce.trustAs (and shorthand methods such as $sce.trustAsHtml, etc.) to obtain values that will be accepted by SCE / privileged contexts. In privileged contexts, directives and code will bind to the result of $sce.getTrusted(context, value) rather than to the value directly. Directives use $sce.parseAs rather than $parse to watch attribute bindings, which performs the $sce.getTrusted behind the scenes on non-constant literals. As an example, ngBindHtmlUnsafe uses $sce.parseAsHtml(binding expression). Here's the actual code (slightly simplified): var ngBindHtmlUnsafeDirective = ['$sce', function($sce) { return function(scope, element, attr) { scope.$watch($sce.parseAsHtml(attr.ngBindHtmlUnsafe), function(value) { element.html(value || ''); }); }; }]; Impact on loading templates --------------------------- This applies both to the ng-include directive as well as templateUrl's specified by directives. By default, Angular only loads templates from the same domain and protocol as the application document. This is done by calling $sce.getTrustedResourceUrl on the template URL. To load templates from other domains and/or protocols, you may either either whitelist them or wrap it into a trusted value. *Please note*: The browser's Same Origin Policy and Cross-Origin Resource Sharing (CORS) policy apply in addition to this and may further restrict whether the template is successfully loaded. This means that without the right CORS policy, loading templates from a different domain won't work on all browsers. Also, loading templates from file:// URL does not work on some browsers. This feels like too much overhead for the developer? ---------------------------------------------------- It's important to remember that SCE only applies to interpolation expressions. If your expressions are constant literals, they're automatically trusted and you don't need to call $sce.trustAs on them. e.g. <div ng-html-bind-unsafe="'<b>implicitly trusted</b>'"></div> just works. Additionally, a[href] and img[src] automatically sanitize their URLs and do not pass them through $sce.getTrusted. SCE doesn't play a role here. The included $sceDelegate comes with sane defaults to allow you to load templates in ng-include from your application's domain without having to even know about SCE. It blocks loading templates from other domains or loading templates over http from an https served document. You can change these by setting your own custom whitelists and blacklists for matching such URLs. This significantly reduces the overhead. It is far easier to pay the small overhead and have an application that's secure and can be audited to verify that with much more ease than bolting security onto an application later.
1 parent fb7d891 commit bea9422

28 files changed

+1853
-110
lines changed

angularFiles.js

+5-4
Original file line numberDiff line numberDiff line change
@@ -18,19 +18,20 @@ angularFiles = {
1818
'src/ng/controller.js',
1919
'src/ng/document.js',
2020
'src/ng/exceptionHandler.js',
21+
'src/ng/http.js',
22+
'src/ng/httpBackend.js',
2123
'src/ng/interpolate.js',
24+
'src/ng/locale.js',
2225
'src/ng/location.js',
2326
'src/ng/log.js',
2427
'src/ng/parse.js',
2528
'src/ng/q.js',
2629
'src/ng/rootScope.js',
30+
'src/ng/sce.js',
2731
'src/ng/sniffer.js',
28-
'src/ng/window.js',
29-
'src/ng/http.js',
30-
'src/ng/httpBackend.js',
31-
'src/ng/locale.js',
3232
'src/ng/timeout.js',
3333
'src/ng/urlUtils.js',
34+
'src/ng/window.js',
3435

3536
'src/ng/filter.js',
3637
'src/ng/filter/filter.js',

docs/content/error/sce/icontext.ngdoc

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
@ngdoc error
2+
@name $sce:icontext
3+
@fullName Invalid / Unknown SCE context
4+
@description
5+
The context enum passed to {@link api/ng.$sce#trustAs $sce.trustAs} was not recognized. Refer the
6+
list of {@link api/ng.$sce#contexts supported Strict Contextual Escaping (SCE) contexts}.

docs/content/error/sce/iequirks.ngdoc

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
@ngdoc error
2+
@name $sce:iequirks
3+
@fullName IE8 in quirks mode is unsupported.
4+
@description
5+
You are using AngularJS with {@link api/ng.$sce#strictcontextualescaping Strict Contextual Escaping
6+
(SCE)} mode enabled (the default) on IE8 or lower in quirks mode. In this mode, IE8 allows one to
7+
execute arbitrary javascript by the use of the `expression()` syntax and is not supported. Refer
8+
{@link http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx MSDN Blogs > IEBlog >
9+
Ending Expressions} to learn more about them.
10+
11+
### Recommended solution
12+
Add the doctype
13+
14+
<!doctype html>
15+
16+
to the top of your HTML document. This switches the document from quirks mode to standards mode.

docs/content/error/sce/isecrurl.ngdoc

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
@ngdoc error
2+
@name $sce:isecrurl
3+
@fullName Blocked loading an untrusted resource
4+
@description
5+
6+
AngularJS' {@link api/ng.$sce#strictcontextualescaping Strict Contextual Escaping
7+
(SCE)} mode (enabled by default) has blocked loading a resource from an insecure URL.
8+
9+
Typically, this would occur if you're attempting to load an Angular template from a different
10+
domain. It's also possible that a custom directive threw this error for a similar reason.
11+
12+
Angular only loads templates from trusted URLs (by calling {@link api/ng.$sce#getTrustedResourceUrl
13+
$sce.getTrustedResourceUrl} on the template URL.).
14+
15+
By default, only URLs to the same domain with the same protocol as the application document are
16+
considered to be trusted.
17+
18+
The {@link api/ng.directive:ngInclude ng-include} directive and {@link guide/directive directives}
19+
that specify a `templateUrl` require a trusted resource URL.
20+
21+
To load templates from other domains and/or protocols, either adjust the {@link
22+
api/ng.$sceDelegateProvider#resourceUrlWhitelist whitelist}/ {@link
23+
api/ng.$sceDelegateProvider#resourceUrlBlacklist blacklist} or wrap the URL with a call to {@link
24+
api/ng.$sce#trustAsResourceUrl $sce.trustAsResourceUrl}.
25+
26+
**Note**: The browser's {@link
27+
https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest Same Origin
28+
Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (CORS)} policy apply
29+
that may further restrict whether the template is successfully loaded. (e.g. neither cross-domain
30+
requests won't work on all browsers nor `file://` requests on some browsers)

docs/content/error/sce/itype.ngdoc

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
@ngdoc error
2+
@name $sce:itype
3+
@fullName String value required for SCE trust call.
4+
@description
5+
{@link api/ng.$sce#trustAs $sce.trustAs} requires a string value. Read more about {@link
6+
api/ng.$sce#strictcontextualescaping Strict Contextual Escaping (SCE)} in AngularJS.

docs/content/error/sce/unsafe.ngdoc

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
@ngdoc error
2+
@name $sce:unsafe
3+
@fullName Require a safe/trusted value
4+
@description
5+
6+
The value provided for use in a specific context was not found to be safe/trusted for use.
7+
8+
Angular's {@link api/ng.$sce#strictcontextualescaping Strict Contextual Escaping (SCE)} mode
9+
(enabled by default), requires bindings in certain
10+
contexts to result in a value that is trusted as safe for use in such a context. (e.g. loading an
11+
Angular template from a URL requires that the URL is one considered safe for loading resources.)
12+
13+
This helps prevent XSS and other security issues. Read more at {@link
14+
api/ng.$sce#strictcontextualescaping Strict Contextual Escaping (SCE)}
15+

docs/content/guide/directive.ngdoc

+4-3
Original file line numberDiff line numberDiff line change
@@ -415,16 +415,17 @@ compiler}. The attributes are:
415415
{@link guide/directive#Components Creating Components} section below for more information.
416416

417417
You can specify `template` as a string representing the template or as a function which takes
418-
two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
419-
a string value representing the template.
418+
two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
419+
returns a string value representing the template.
420420

421421
* `templateUrl` - Same as `template` but the template is loaded from the specified URL. Because
422422
the template loading is asynchronous the compilation/linking is suspended until the template
423423
is loaded.
424424

425425
You can specify `templateUrl` as a string representing the URL or as a function which takes two
426426
arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
427-
a string value representing the url.
427+
a string value representing the url. In either case, the template URL is passed through {@link
428+
api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
428429

429430
* `replace` - if set to `true` then the template will replace the current element, rather than
430431
append the template to the element.

docs/src/example.js

+3
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ exports.Example = function(scenarios) {
2020
this.html = [];
2121
this.css = [];
2222
this.js = [];
23+
this.json = [];
2324
this.unit = [];
2425
this.scenario = [];
2526
this.scenarios = scenarios;
@@ -88,6 +89,7 @@ exports.Example.prototype.toHtmlEdit = function() {
8889
out.push(' source-edit-html="' + ids(this.html) + '"');
8990
out.push(' source-edit-css="' + ids(this.css) + '"');
9091
out.push(' source-edit-js="' + ids(this.js) + '"');
92+
out.push(' source-edit-json="' + ids(this.json) + '"');
9193
out.push(' source-edit-unit="' + ids(this.unit) + '"');
9294
out.push(' source-edit-scenario="' + ids(this.scenario) + '"');
9395
out.push('></div>\n');
@@ -102,6 +104,7 @@ exports.Example.prototype.toHtmlTabs = function() {
102104
htmlTabs(this.html);
103105
htmlTabs(this.css);
104106
htmlTabs(this.js);
107+
htmlTabs(this.json);
105108
htmlTabs(this.unit);
106109
htmlTabs(this.scenario);
107110
out.push('</div>');

docs/src/templates/js/docs.js

+2-1
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,7 @@ docsApp.directive.sourceEdit = function(getEmbeddedTemplate) {
216216
html: read($attrs.sourceEditHtml),
217217
css: read($attrs.sourceEditCss),
218218
js: read($attrs.sourceEditJs),
219+
json: read($attrs.sourceEditJson),
219220
unit: read($attrs.sourceEditUnit),
220221
scenario: read($attrs.sourceEditScenario)
221222
};
@@ -358,7 +359,7 @@ docsApp.serviceFactory.formPostData = function($document) {
358359

359360
docsApp.serviceFactory.openPlunkr = function(templateMerge, formPostData, angularUrls) {
360361
return function(content) {
361-
var allFiles = [].concat(content.js, content.css, content.html);
362+
var allFiles = [].concat(content.js, content.css, content.html, content.json);
362363
var indexHtmlContent = '<!doctype html>\n' +
363364
'<html ng-app="{{module}}">\n' +
364365
' <head>\n' +

src/AngularPublic.js

+2
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,8 @@ function publishExternalAPI(angular){
122122
$parse: $ParseProvider,
123123
$rootScope: $RootScopeProvider,
124124
$q: $QProvider,
125+
$sce: $SceProvider,
126+
$sceDelegate: $SceDelegateProvider,
125127
$sniffer: $SnifferProvider,
126128
$templateCache: $TemplateCacheProvider,
127129
$timeout: $TimeoutProvider,

src/ng/compile.js

+6-6
Original file line numberDiff line numberDiff line change
@@ -274,9 +274,9 @@ function $CompileProvider($provide) {
274274

275275
this.$get = [
276276
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
277-
'$controller', '$rootScope', '$document', '$$urlUtils',
277+
'$controller', '$rootScope', '$document', '$sce', '$$urlUtils',
278278
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
279-
$controller, $rootScope, $document, $$urlUtils) {
279+
$controller, $rootScope, $document, $sce, $$urlUtils) {
280280

281281
var Attributes = function(element, attr) {
282282
this.$$element = element;
@@ -1095,7 +1095,7 @@ function $CompileProvider($provide) {
10951095

10961096
$compileNode.html('');
10971097

1098-
$http.get(templateUrl, {cache: $templateCache}).
1098+
$http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
10991099
success(function(content) {
11001100
var compileNode, tempTemplateAttrs, $template;
11011101

@@ -1203,12 +1203,12 @@ function $CompileProvider($provide) {
12031203
}
12041204

12051205

1206-
function isTrustedContext(node, attrNormalizedName) {
1206+
function getTrustedContext(node, attrNormalizedName) {
12071207
// maction[xlink:href] can source SVG. It's not limited to <maction>.
12081208
if (attrNormalizedName == "xlinkHref" ||
12091209
(nodeName_(node) != "IMG" && (attrNormalizedName == "src" ||
12101210
attrNormalizedName == "ngSrc"))) {
1211-
return true;
1211+
return $sce.RESOURCE_URL;
12121212
}
12131213
}
12141214

@@ -1238,7 +1238,7 @@ function $CompileProvider($provide) {
12381238

12391239
// we need to interpolate again, in case the attribute value has been updated
12401240
// (e.g. by another directive's compile function)
1241-
interpolateFn = $interpolate(attr[name], true, isTrustedContext(node, name));
1241+
interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
12421242

12431243
// if attribute was updated so that there is no interpolation going on we don't want to
12441244
// register any observers

src/ng/directive/ngBind.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -129,10 +129,10 @@ var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
129129
* @element ANY
130130
* @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
131131
*/
132-
var ngBindHtmlUnsafeDirective = [function() {
132+
var ngBindHtmlUnsafeDirective = ['$sce', function($sce) {
133133
return function(scope, element, attr) {
134134
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
135-
scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
135+
scope.$watch($sce.parseAsHtml(attr.ngBindHtmlUnsafe), function ngBindHtmlUnsafeWatchAction(value) {
136136
element.html(value || '');
137137
});
138138
};

src/ng/directive/ngInclude.js

+17-6
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,20 @@
88
* @description
99
* Fetches, compiles and includes an external HTML fragment.
1010
*
11-
* Keep in mind that Same Origin Policy applies to included resources
12-
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for
13-
* file:// access on some browsers).
11+
* Keep in mind that:
12+
*
13+
* - by default, the template URL is restricted to the same domain and protocol as the
14+
* application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
15+
* $sce.getTrustedResourceUrl} on it. To load templates from other domains and/or protocols,
16+
* you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
17+
* {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. Refer Angular's {@link
18+
* ng.$sce Strict Contextual Escaping}.
19+
* - in addition, the browser's
20+
* {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
21+
* Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing
22+
* (CORS)} policy apply that may further restrict whether the template is successfully loaded.
23+
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for `file://`
24+
* access on some browsers)
1425
*
1526
* Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**
1627
* and **leave** effects.
@@ -132,8 +143,8 @@
132143
* @description
133144
* Emitted every time the ngInclude content is reloaded.
134145
*/
135-
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animator',
136-
function($http, $templateCache, $anchorScroll, $compile, $animator) {
146+
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animator', '$sce',
147+
function($http, $templateCache, $anchorScroll, $compile, $animator, $sce) {
137148
return {
138149
restrict: 'ECA',
139150
terminal: true,
@@ -155,7 +166,7 @@ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile'
155166
animate.leave(element.contents(), element);
156167
};
157168

158-
scope.$watch(srcExp, function ngIncludeWatchAction(src) {
169+
scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
159170
var thisChangeId = ++changeCounter;
160171

161172
if (src) {

src/ng/interpolate.js

+16-11
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ function $InterpolateProvider() {
5454
};
5555

5656

57-
this.$get = ['$parse', '$exceptionHandler', function($parse, $exceptionHandler) {
57+
this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
5858
var startSymbolLength = startSymbol.length,
5959
endSymbolLength = endSymbol.length;
6060

@@ -64,6 +64,7 @@ function $InterpolateProvider() {
6464
* @function
6565
*
6666
* @requires $parse
67+
* @requires $sce
6768
*
6869
* @description
6970
*
@@ -84,20 +85,18 @@ function $InterpolateProvider() {
8485
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
8586
* embedded expression in order to return an interpolation function. Strings with no
8687
* embedded expression will return null for the interpolation function.
87-
* @param {boolean=} isTrustedContext when true, requires that the interpolation string does not
88-
* contain any concatenations - i.e. the interpolation string is a single expression.
89-
* Interpolations for *[src] and *[ng-src] (except IMG, since itwhich sanitizes its value)
90-
* pass true for this parameter. This helps avoid hunting through the template code to
91-
* figure out of some iframe[src], object[src], etc. was interpolated with a concatenation
92-
* that ended up introducing a XSS.
88+
* @param {string=} trustedContext when provided, the returned function passes the interpolated
89+
* result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
90+
* trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
91+
* provides Strict Contextual Escaping for details.
9392
* @returns {function(context)} an interpolation function which is used to compute the interpolated
9493
* string. The function has these parameters:
9594
*
9695
* * `context`: an object against which any expressions embedded in the strings are evaluated
9796
* against.
9897
*
9998
*/
100-
function $interpolate(text, mustHaveExpression, isTrustedContext) {
99+
function $interpolate(text, mustHaveExpression, trustedContext) {
101100
var startIndex,
102101
endIndex,
103102
index = 0,
@@ -135,10 +134,11 @@ function $InterpolateProvider() {
135134
// is assigned or constructed by some JS code somewhere that is more testable or make it
136135
// obvious that you bound the value to some user controlled value. This helps reduce the load
137136
// when auditing for XSS issues.
138-
if (isTrustedContext && parts.length > 1) {
137+
if (trustedContext && parts.length > 1) {
139138
throw $interpolateMinErr('noconcat',
140-
"Error while interpolating: {0}\nYou may not use multiple expressions when " +
141-
"interpolating this expression.", text);
139+
"Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
140+
"interpolations that concatenate multiple expressions when a trusted value is " +
141+
"required. See http://docs.angularjs.org/api/ng.$sce", text);
142142
}
143143

144144
if (!mustHaveExpression || hasInterpolation) {
@@ -148,6 +148,11 @@ function $InterpolateProvider() {
148148
for(var i = 0, ii = length, part; i<ii; i++) {
149149
if (typeof (part = parts[i]) == 'function') {
150150
part = part(context);
151+
if (trustedContext) {
152+
part = $sce.getTrusted(trustedContext, part);
153+
} else {
154+
part = $sce.valueOf(part);
155+
}
151156
if (part == null || part == undefined) {
152157
part = '';
153158
} else if (typeof part != 'string') {

0 commit comments

Comments
 (0)