angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

XSS issues with server-rendered Angular templates

Open triskweline opened this issue 12 years ago • 50 comments

Dear Angular community,

we would greatly appreciate any comments on the issue below.

Overview of the issue:

When rendering Angular templates with a server-side templating engine like ERB or Haml it is easy to introduce XSS vulnerabilities. These vulnerabilities are enabled by AngularJS evaluating user-provided strings containing interpolation symbols (default symbols are {{ and }}).

The standard mitigation strategy by templating engines is to always escape meaningful symbols in strings (unless they are explicitely marked as "safe"). Unfortunately the inability to escape AngularJS interpolation symbols makes it hard to apply this strategy here.

Reproducing the issue:

We are using AngularJS for the frontend and Rails in the backend. While we have written full Single Page Applications with AngularJS, we are often embedding small snippets of AngularJS in server-rendered views. We love that AngularJS lets us replace jQuery spaghetti with simple code like this:

<div ng-show="detailsShown">
  <%= user.profile %>
</div>

<span ng-click="detailsShown = true">Show details</span>

The problem is that the code snippet above enables Cross Site Scripting (XSS). If the server-parsed expression user.profile contains AngularJS markup like "Foo {{signOut()}} Bar", it will trigger functions on the current scope, allowing an attacker to trigger side effects on another computer.

Proposed fix:

The standard mitigation strategy by templating engines is to always escape symbols that have meaning for downsteam parsers, unless they are explicitely marked as "safe". E. g. if the server-parsed expression user.profile in the code example above would yield the string "Foo <script>alert('owned')</script> Bar", Rails, Haml, etc. would automatically replace the angle brackets with HTML entities.

To allow HTML tags to be rendered without escaping, the developer needs to explicitely mark a string as "safe" like so:

<%= user.profile.html_safe %>

(AngularJS actually uses this approach itself, when inserting the results of an evaluated Angular expression into the DOM.)

A good default for people rendering Angular templates using server-side templating engines would be to make templating engines automatically escape Angular interpolation symbols unless an evaluated string is explictely flagged as "safe". A patch for engines like ERB or Haml would be easily created, but unfortunately Angular's $interpolate service does not recognize any kind of escape symbol.

We propose that the $interpolate service should recognize escaped interpolation symbols like this:

Foo \{\{signOut()\}\} Bar

... or maybe a second pair of start/end symbols.

When encountering escaped interpolation symbols, the service would not evaluate the enclosed expression. Instead it would strip the escape symbols from the string.

(Note that we first tried to replace the curly braces with their HTML entities, which would have the added bonus of being output-neutral outside of an ng-app element. However, entitized braces are still recognized and their contents evaluated by Angular. We're not sure if the entities are expanded by Angular or by the browser.)

Plea to not dismiss this issue

We understand that this issue is not an actual bug in AngularJS, but (like all XSS issues) is caused by combining multiple technologies that are unaware of each other. Still we believe that AngularJS' ability to co-exist with non-Angular code in the same DOM is one of AngularJS greatest strengths. It sets Angular apart from frameworks like Ember, which need to own the entire page.

By offering a way to escape interpolation symbols (or maybe some other solution we didn't think of), AngularJS could be used safely in combination with upstream templating engines.

What do you think?

triskweline avatar Jan 02 '14 18:01 triskweline

Even if you change the start/end interpolation markers, the HTML compiler converts {{ and }} to match the new values, for interoperability with external components. So there isn't really anything angular can do client-side to prevent this.

As you say, it comes down to being entirely a server-side issue, but a solution such as suggested by @tbosch should be acceptable. "It broke inlined javascript" well, I'm having a hard time seeing how this is a "problem", since you typically don't want inlined javascript in user data anyways.

I don't really think this is something to be fixed on the client-side

caitp avatar Jan 03 '14 15:01 caitp

@caitp is right, there is nothing we can do on the client side. The server side templating engines escaping is done assuming that you will output html content. That's why it converts the <, > and some other html entities into entity names (&lt;, &gt;). It's a common solution that works fine for the html. If you need to escape 'angular entities', it's up to you to write a solution that does the job.

That's why I was talking about Twig and its extensibility that allows the developers to improve the escape function. I'm not sure that you can achieve such a thing in all other templating engine. Just keep in mind, that the solution should be set in the server and not the client.

sukei avatar Jan 03 '14 15:01 sukei

Inlined Javascript can be used for performance reasons to pre-populate an Angular scope without an additional AJAX request, but on second thought: Inlined Javascript is not subject to server-side escaping mechanisms, so there is no problem here.

The issue remains that we're changing content by replacing curly braces with something that looks like one, but isn't. I can't copy the changed text and use them for purposes where curly braces are expected (e.g. code snippets in this very page). I can't find those braces with a text search. And I will have a hard time to find out what's wrong, since the letters will look fine, but aren't.

triskweline avatar Jan 03 '14 17:01 triskweline

I feel this thread has moved away from the original proposal. I'm not asking Angular to solve this problem on its own. @sukei correctly said "If you need to escape 'angular entities', it's up to you to write a solution that does the job.". This is what I'm trying to do: Solve it on the backend. But I can't. It is not possible to escape Angular entities without changing the content.

The original proposal was to change $interpolate so it recognizes escaped interpolation marks. This would allow a server-side templating engine to solve this problem.

Here is a rough draft of a change to AngularJS that would add the ability to escape interpolation symbols using \{\{ and \}\}:

https://github.com/makandra/angular.js/commit/6c4490f77753c359d7ae871f1518ad0bf57ae53a

The commit linked above still has some minor issues:

  • Escaped interpolation symbols cannot be customized
  • \{\{{ is still incorrectly recognized as an interpolation mark

... but that can be fixed easily.

What do you think?

triskweline avatar Jan 03 '14 17:01 triskweline

Let me sum this up before this thread goes too wild. I'll update this summary as needed with future updates:

Summary of the issue

Issue 1. mixing server-side and client-side templating could result in XSS

example code:

<div ng-show="detailsShown">
  <%= user.profile %>
</div>

<span ng-click="detailsShown = true">Show details</span>

if this template is evaluated by Rails then <%= user.profile %> is interpreted as server side interpolation. If this user.profile expression evaluates to something that contains {{ and }} (e.g. My name is Patrick and I like {{ double.curlies }}. then the template arrives into the browser as:

<div ng-show="detailsShown">
  My name is Patrick and I like {{ double.curlies }}.
</div>

<span ng-click="detailsShown = true">Show details</span>

Once Angular processes this template then it will generate DOM that looks most likely like this:

<div ng-show="detailsShown">
  My name is Patrick and I like .
</div>

<span ng-click="detailsShown = true">Show details</span>

Notice that the {{ double.curlies }} was replaced by an empty string. This is because Angular interpreted this substring as a binding and evaluated it, but the double.curlies expression yielded no value which results in an empty string being used in the DOM view.

Because the expression was evaluated by Angular, the server-side interpolation could force Angular to executed unexpected code via expressions. This would require the user input to be crafted in a way that is meaningful to the Angular app being exploited.

Solution

It is not recommended to mix server-side and client-side templating that uses user-provided input in this way. We discourage developers from doing so because it's hard to audit and fix all the possible corner-cases that could be exploited using the interaction of these two templating systems. This is not a new recommendation, it has been in place since the first Google security review in 2011.

If you really really have to though, there are some workarounds:

Workaround 1

Use ng-non-bindable or a custom terminal directive that will prevent Angular's template compiler from descending into the DOM subtree that is constructed on the server-side from user's input:

<div ng-show="detailsShown">
  <div ng-non-bindable>
    <%= user.profile %>
  </div>
</div>

<span ng-click="detailsShown = true">Show details</span>

Workaround 2

The server could use html escaping on the input (user.profile in our case) and render the input harmless by escaping it in a way that would make Angular treat it as being a string rather than some template with binding or other instructions. This approach works almost perfectly with rails, which does this kind of escaping automatically, except for the inability to escape interpolation markers ({{ and }}) - see the second part of this issue.

Issue 2. Inability to escape interpolation markers on the server so that Angular does not interpret them as bindings

When Angular see's interpolation markers {{ followed by }} in a textContent or attribute value, it interprets the string in between as an expression that should be used for data-binding. These interpolation markers are configurable, but double-curlies are the default. The problem is that a server can't currently escape and thus disable these markers in a template being sent to the client. This is only a problem in case when two different server-side and client-side tempating engines are being used to generate the same view (see the first part of this issue).

A naïve way to approach the escaping would be to use html entities to encode the marker characters in the template - just as is being done with html tags.

This approach doesn't work, because Angular consumes DOM templates and not template strings. This means that when a string (containing html entities) is sent from the server to the client, the browser will parse it and turn it into DOM tree. Angular then walks the DOM tree and looks for interesting things (like interpolation markers). The problem is that by the time Angular finds the interpolation marker in a textContent attribute value, it has already been converted from html entity into a regular character.

Another approach would be for the server to replace {{ foo }} with {\{ foo }}. This however mangles the user input which is not desirable.

Yet another approach would be for the server to replace regular { and } symbols with unicode characters that visually look similar, but from the computer (code point) perspective are different. Example of these characters are: { : 0xFF5B ❴ : 0x2774.

This approach almost works, except if a user tries to search for curlies in the text or tries to copy&paste the text from the view, then these pseudo-curlies could cause a lot of issues that are not obvious to understand and debug by the end user.

Solution

Since it's unlikely that we can find a way to escape interpolation markers using html entities or with a similar method, the server and client might need to cooperate to get the behavior just right.

One solution would be for the server to escape interpolation markers in a way that Angular understands and treats as escaped markers that should be unescaped but not interpreted as binding. Example:

  1. server escapes {{ user.profile }} as {{{{ user.profile }}}}
  2. angular is configured to treat {{{{ followed by }}}} (e.g. via additional arg to $interpolateProvider's startSymbol and endSymbol methods)
  3. when angular comes across {{{{ user.profile }}}}, it simply replaces it with {{ user.profile }} but does not treat it as binding.

IgorMinar avatar Jan 03 '14 19:01 IgorMinar

when angular comes across {{{{ user.profile }}}}, it simply replaces it with {{ user.profile }} but does not treat it as binding.

\o/

sukei avatar Jan 03 '14 23:01 sukei

since we need to be explicit about the regular and escaped interpolation markers during configuration, it might be better to just add a second argument to the $interpolateProvider. So one could do:

$interpolateProvider.startSymbol('{{'. '{{{{');
$interpolateProvider.endSymbol('}}'. ''}}}}');

I'm not opposed to making this the default if we find a consensus on escaped markers that don't break anything out there. (this would be for 1.3 of course)

IgorMinar avatar Jan 04 '14 01:01 IgorMinar

PRs welcome!

IgorMinar avatar Jan 04 '14 01:01 IgorMinar

Well there's my shot at it, if anyone cares to improve the algorithm on their own, or offer suggestions or improve test coverage, you're more than welcome

caitp avatar Jan 04 '14 02:01 caitp

(Disclaimer: I do not have any plan to mix server-side processing with Angular like this, but I am hypothetically imagining that I were doing that.)

I am a little bit concerned by the potential complexity in the server-side processing to use the proposed solution correctly.

Suppose that I have a database with user profile, which allows certain HTML elements (say, only <b> elements are allowed). To use this solution correctly, the server must process strings as follows:

  • {{abc}}}}{{def}} → replace it by {{{{abc}}}}}}{{{{def}}}}
  • {{abc}{{def} → do not replace anything (It is incorrect to convert {{ to {{{{ here.)
  • {{abc<b>def</b>ghi}} → do not replace anything (It is incorrect to output {{{{abc<b>def</b>ghi}}}} because Angular would not interpret it as {{{{…}}}}.)

So the server has to take into account how Angular would interpret the result, and I am afraid that this is error-prone. Is there any alternative such that the server-side processing is simpler?

yuasakusa avatar Jan 04 '14 12:01 yuasakusa

@yuasakusa feel free to contribute a test to my current implementation to verify what would happen in this case, I'm fairly sure you'd see {{abc}}}}{{def}} rendered in the view without parsing in the first case, and {{abc<b>def</b>ghi}} rendered in the view without parsing in the third case (where the <b> is a literal child node due to not being escaped on the server). In the second case, the interpolate service won't parse it due to not finding the end symbol, I believe.

caitp avatar Jan 04 '14 12:01 caitp

@caitp My concerns are not about correctness of your patch or of the implementation of Angular in general. My concerns are that it may be difficult for the server to produce the correct output (which is the input to Angular) given the proposed behavior of Angular, and they are not addressed by adding tests to Angular. What would help is integration tests in each project that uses Angular in combination with server-side processing, but clearly we cannot write those tests as part of Angular.

If you are going to go with the current proposal, a sample code of using Angular with Ruby on Rails correctly would be probably very helpful. Unfortunately writing one is beyond my skills (to begin with, I have never used Ruby on Rails), but I am sure that some people can write one.

yuasakusa avatar Jan 04 '14 14:01 yuasakusa

Right, but we want to deal with poorly escaped stuff too, presumably, to avoid mistakes. At the very least, if you can think of any arrangements of text which might be exploitable (in the sense of executing javascript which was not meant to be executed), it would be awesome to submit tests so we can try not to choke on them

caitp avatar Jan 04 '14 14:01 caitp

Thanks everyone for your work so far!

@yuasakusa A simpler rule would be to have Angular unescape individual {{{{ and }}}} strings, but not require the matching bracket. This way both the server and Angular could blindly replace individual strings without worrying about getting the context right.

triskweline avatar Jan 04 '14 14:01 triskweline

@henning-koch unfortunately we can't really do a context-free replacement before doing the actual interpolation, because doing so would defeat the purpose of escaping entirely :( Unless we replaced them temporarily with some unusual unicode characters or something, but I don't really see that as being a good idea, and would probably hurt the typical case performance-wise. Hard to say without measurement though.

caitp avatar Jan 04 '14 14:01 caitp

@caitp I didn't mean to replace before the actual interpolation. I meant that we change the string parser in $interpolate to this (pseudo-code):

var pattern = /{{{{|}}}}|{{(.*?)}}/g;
var match;
while (match = text.exec(pattern)) {
  if (match[0] === '{{{{') {
    // we found escaped opening braces
    parts.push('{{');
  } else if (match[0] === '}}}}') {
    // we found escaped closing braces
    parts.push('}}');
  } else {
    // we found an Angular expression
    var expression = match[1]:
    parts.push($parse(expression));
  }
}

The code above scans text for the next interesting substring, interesting meaning one of the following:

  • {{{{
  • }}}}
  • {{ something something }}

(Code is still missing to process text between matches of course.)

triskweline avatar Jan 04 '14 14:01 triskweline

What would help is integration tests in each project that uses Angular in combination with server-side processing, but clearly we cannot write those tests as part of Angular.

We have already published a Ruby library angular_xss that configures popular templating engines to auto-escape Angular interpolation marks in unsafe Ruby Strings. Currently the library still works by replacing {{ by { { because it requires the changes suggested in this issue to do proper escaping.

If code from this issue is accepted into Angular, we would update the library with proper integration testing.

Other Rails projects would require this library, but not need to add their own tests.

triskweline avatar Jan 04 '14 14:01 triskweline

@henning-koch Great! With your proposal, the server just needs to replace all non-overlapping occurrences of {{ to {{{{ and (optionally) }} to }}}}, and does not have to worry about how exactly Angular will interpret the input. (That is assuming that the database on the server is sane and does not do anything like storing character { sometimes as { and sometimes as &#x7B;.)

Also it is great to know that there is already a standard library for encoding plain text for Angular. It is even better than just a sample code.

@caitp

At the very least, if you can think of any arrangements of text which might be exploitable (in the sense of executing javascript which was not meant to be executed), it would be awesome to submit tests so we can try not to choke on them

I am afraid that there are hundreds of ways to do it wrong. Even with the much simplified proposal by @henning-koch, I can see how other people may screw up (as I mentioned above, if the server stores character { sometimes as { and sometimes as &#x7B;, it is difficult to handle everything correctly). Providing the library for template engines is indeed a great solution.

yuasakusa avatar Jan 04 '14 14:01 yuasakusa

Yes, I think we can agree that it would be good (not just for angular, it could probably be specced out and standardized for all of the clientside stuff which uses handlebars/moustache conventions).

However, it sounds like we aren't forcing this to be an entirely server-side issue, and need conventions on the client-side to handle mistakes, and enable such escaping on the server in the first place.

caitp avatar Jan 04 '14 15:01 caitp

@yuasakusa Can you elaborate on some complicated ways to express those interpolation symbols, so an escaping implementation might not recognize it?

What I can think of so far:

{
&lcub;
&lbrace;
&#x7b;
&#x000007b;
&#x000000000007b;
&#123;
&#000000123;
&#0000000000000123;

... and all uppercase/lowercase variations.

It's more than I expected (and I need to update angular_xss for this), but manageable by a single Regex so far.

triskweline avatar Jan 04 '14 16:01 triskweline