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

Commit

Permalink
feat($sce): new $sce service for Strict Contextual Escaping.
Browse files Browse the repository at this point in the history
$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.
  • Loading branch information
chirayuk committed Jul 25, 2013
1 parent fb7d891 commit bea9422
Show file tree
Hide file tree
Showing 28 changed files with 1,853 additions and 110 deletions.
9 changes: 5 additions & 4 deletions angularFiles.js
Expand Up @@ -18,19 +18,20 @@ angularFiles = {
'src/ng/controller.js',
'src/ng/document.js',
'src/ng/exceptionHandler.js',
'src/ng/http.js',
'src/ng/httpBackend.js',
'src/ng/interpolate.js',
'src/ng/locale.js',
'src/ng/location.js',
'src/ng/log.js',
'src/ng/parse.js',
'src/ng/q.js',
'src/ng/rootScope.js',
'src/ng/sce.js',
'src/ng/sniffer.js',
'src/ng/window.js',
'src/ng/http.js',
'src/ng/httpBackend.js',
'src/ng/locale.js',
'src/ng/timeout.js',
'src/ng/urlUtils.js',
'src/ng/window.js',

'src/ng/filter.js',
'src/ng/filter/filter.js',
Expand Down
6 changes: 6 additions & 0 deletions docs/content/error/sce/icontext.ngdoc
@@ -0,0 +1,6 @@
@ngdoc error
@name $sce:icontext
@fullName Invalid / Unknown SCE context
@description
The context enum passed to {@link api/ng.$sce#trustAs $sce.trustAs} was not recognized. Refer the
list of {@link api/ng.$sce#contexts supported Strict Contextual Escaping (SCE) contexts}.
16 changes: 16 additions & 0 deletions docs/content/error/sce/iequirks.ngdoc
@@ -0,0 +1,16 @@
@ngdoc error
@name $sce:iequirks
@fullName IE8 in quirks mode is unsupported.
@description
You are using AngularJS with {@link api/ng.$sce#strictcontextualescaping Strict Contextual Escaping
(SCE)} mode enabled (the default) on IE8 or lower in quirks mode. In this mode, IE8 allows one to
execute arbitrary javascript by the use of the `expression()` syntax and is not supported. Refer
{@link http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx MSDN Blogs > IEBlog >
Ending Expressions} to learn more about them.

### Recommended solution
Add the doctype

<!doctype html>

to the top of your HTML document. This switches the document from quirks mode to standards mode.
30 changes: 30 additions & 0 deletions docs/content/error/sce/isecrurl.ngdoc
@@ -0,0 +1,30 @@
@ngdoc error
@name $sce:isecrurl
@fullName Blocked loading an untrusted resource
@description

AngularJS' {@link api/ng.$sce#strictcontextualescaping Strict Contextual Escaping
(SCE)} mode (enabled by default) has blocked loading a resource from an insecure URL.

Typically, this would occur if you're attempting to load an Angular template from a different
domain. It's also possible that a custom directive threw this error for a similar reason.

Angular only loads templates from trusted URLs (by calling {@link api/ng.$sce#getTrustedResourceUrl
$sce.getTrustedResourceUrl} on the template URL.).

By default, only URLs to the same domain with the same protocol as the application document are
considered to be trusted.

The {@link api/ng.directive:ngInclude ng-include} directive and {@link guide/directive directives}
that specify a `templateUrl` require a trusted resource URL.

To load templates from other domains and/or protocols, either adjust the {@link
api/ng.$sceDelegateProvider#resourceUrlWhitelist whitelist}/ {@link
api/ng.$sceDelegateProvider#resourceUrlBlacklist blacklist} or wrap the URL with a call to {@link
api/ng.$sce#trustAsResourceUrl $sce.trustAsResourceUrl}.

**Note**: The browser's {@link
https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest Same Origin
Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (CORS)} policy apply
that may further restrict whether the template is successfully loaded. (e.g. neither cross-domain
requests won't work on all browsers nor `file://` requests on some browsers)
6 changes: 6 additions & 0 deletions docs/content/error/sce/itype.ngdoc
@@ -0,0 +1,6 @@
@ngdoc error
@name $sce:itype
@fullName String value required for SCE trust call.
@description
{@link api/ng.$sce#trustAs $sce.trustAs} requires a string value. Read more about {@link
api/ng.$sce#strictcontextualescaping Strict Contextual Escaping (SCE)} in AngularJS.
15 changes: 15 additions & 0 deletions docs/content/error/sce/unsafe.ngdoc
@@ -0,0 +1,15 @@
@ngdoc error
@name $sce:unsafe
@fullName Require a safe/trusted value
@description

The value provided for use in a specific context was not found to be safe/trusted for use.

Angular's {@link api/ng.$sce#strictcontextualescaping Strict Contextual Escaping (SCE)} mode
(enabled by default), requires bindings in certain
contexts to result in a value that is trusted as safe for use in such a context. (e.g. loading an
Angular template from a URL requires that the URL is one considered safe for loading resources.)

This helps prevent XSS and other security issues. Read more at {@link
api/ng.$sce#strictcontextualescaping Strict Contextual Escaping (SCE)}

7 changes: 4 additions & 3 deletions docs/content/guide/directive.ngdoc
Expand Up @@ -415,16 +415,17 @@ compiler}. The attributes are:
{@link guide/directive#Components Creating Components} section below for more information.

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

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

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

* `replace` - if set to `true` then the template will replace the current element, rather than
append the template to the element.
Expand Down
3 changes: 3 additions & 0 deletions docs/src/example.js
Expand Up @@ -20,6 +20,7 @@ exports.Example = function(scenarios) {
this.html = [];
this.css = [];
this.js = [];
this.json = [];
this.unit = [];
this.scenario = [];
this.scenarios = scenarios;
Expand Down Expand Up @@ -88,6 +89,7 @@ exports.Example.prototype.toHtmlEdit = function() {
out.push(' source-edit-html="' + ids(this.html) + '"');
out.push(' source-edit-css="' + ids(this.css) + '"');
out.push(' source-edit-js="' + ids(this.js) + '"');
out.push(' source-edit-json="' + ids(this.json) + '"');
out.push(' source-edit-unit="' + ids(this.unit) + '"');
out.push(' source-edit-scenario="' + ids(this.scenario) + '"');
out.push('></div>\n');
Expand All @@ -102,6 +104,7 @@ exports.Example.prototype.toHtmlTabs = function() {
htmlTabs(this.html);
htmlTabs(this.css);
htmlTabs(this.js);
htmlTabs(this.json);
htmlTabs(this.unit);
htmlTabs(this.scenario);
out.push('</div>');
Expand Down
3 changes: 2 additions & 1 deletion docs/src/templates/js/docs.js
Expand Up @@ -216,6 +216,7 @@ docsApp.directive.sourceEdit = function(getEmbeddedTemplate) {
html: read($attrs.sourceEditHtml),
css: read($attrs.sourceEditCss),
js: read($attrs.sourceEditJs),
json: read($attrs.sourceEditJson),
unit: read($attrs.sourceEditUnit),
scenario: read($attrs.sourceEditScenario)
};
Expand Down Expand Up @@ -358,7 +359,7 @@ docsApp.serviceFactory.formPostData = function($document) {

docsApp.serviceFactory.openPlunkr = function(templateMerge, formPostData, angularUrls) {
return function(content) {
var allFiles = [].concat(content.js, content.css, content.html);
var allFiles = [].concat(content.js, content.css, content.html, content.json);
var indexHtmlContent = '<!doctype html>\n' +
'<html ng-app="{{module}}">\n' +
' <head>\n' +
Expand Down
2 changes: 2 additions & 0 deletions src/AngularPublic.js
Expand Up @@ -122,6 +122,8 @@ function publishExternalAPI(angular){
$parse: $ParseProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sce: $SceProvider,
$sceDelegate: $SceDelegateProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
Expand Down
12 changes: 6 additions & 6 deletions src/ng/compile.js
Expand Up @@ -274,9 +274,9 @@ function $CompileProvider($provide) {

this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
'$controller', '$rootScope', '$document', '$$urlUtils',
'$controller', '$rootScope', '$document', '$sce', '$$urlUtils',
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
$controller, $rootScope, $document, $$urlUtils) {
$controller, $rootScope, $document, $sce, $$urlUtils) {

var Attributes = function(element, attr) {
this.$$element = element;
Expand Down Expand Up @@ -1095,7 +1095,7 @@ function $CompileProvider($provide) {

$compileNode.html('');

$http.get(templateUrl, {cache: $templateCache}).
$http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;

Expand Down Expand Up @@ -1203,12 +1203,12 @@ function $CompileProvider($provide) {
}


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

Expand Down Expand Up @@ -1238,7 +1238,7 @@ function $CompileProvider($provide) {

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

// if attribute was updated so that there is no interpolation going on we don't want to
// register any observers
Expand Down
4 changes: 2 additions & 2 deletions src/ng/directive/ngBind.js
Expand Up @@ -129,10 +129,10 @@ var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
* @element ANY
* @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
*/
var ngBindHtmlUnsafeDirective = [function() {
var ngBindHtmlUnsafeDirective = ['$sce', function($sce) {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
scope.$watch($sce.parseAsHtml(attr.ngBindHtmlUnsafe), function ngBindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
};
Expand Down
23 changes: 17 additions & 6 deletions src/ng/directive/ngInclude.js
Expand Up @@ -8,9 +8,20 @@
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for
* file:// access on some browsers).
* Keep in mind that:
*
* - by default, the template URL is restricted to the same domain and protocol as the
* application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on it. To load templates from other domains and/or protocols,
* you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
* {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value. Refer Angular's {@link
* ng.$sce Strict Contextual Escaping}.
* - in addition, the browser's
* {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
* Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing
* (CORS)} policy apply that may further restrict whether the template is successfully loaded.
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for `file://`
* access on some browsers)
*
* Additionally, you can also provide animations via the ngAnimate attribute to animate the **enter**
* and **leave** effects.
Expand Down Expand Up @@ -132,8 +143,8 @@
* @description
* Emitted every time the ngInclude content is reloaded.
*/
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animator',
function($http, $templateCache, $anchorScroll, $compile, $animator) {
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animator', '$sce',
function($http, $templateCache, $anchorScroll, $compile, $animator, $sce) {
return {
restrict: 'ECA',
terminal: true,
Expand All @@ -155,7 +166,7 @@ var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile'
animate.leave(element.contents(), element);
};

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

if (src) {
Expand Down
27 changes: 16 additions & 11 deletions src/ng/interpolate.js
Expand Up @@ -54,7 +54,7 @@ function $InterpolateProvider() {
};


this.$get = ['$parse', '$exceptionHandler', function($parse, $exceptionHandler) {
this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;

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

if (!mustHaveExpression || hasInterpolation) {
Expand All @@ -148,6 +148,11 @@ function $InterpolateProvider() {
for(var i = 0, ii = length, part; i<ii; i++) {
if (typeof (part = parts[i]) == 'function') {
part = part(context);
if (trustedContext) {
part = $sce.getTrusted(trustedContext, part);
} else {
part = $sce.valueOf(part);
}
if (part == null || part == undefined) {
part = '';
} else if (typeof part != 'string') {
Expand Down

0 comments on commit bea9422

Please sign in to comment.