How is concatenating urls in templates in angular less secure than in other locations?

后端 未结 2 1726
日久生厌
日久生厌 2021-01-01 21:52

I have an angularjs template which looks similar to this:


         


        
2条回答
  •  情深已故
    2021-01-01 22:05

    I joined the party a little late, but here are my two cents:

    In (very) plain words:

    (1)
    Angular uses the $sce service to perform "Strict Conceptual Escaping" (SCE). Basically, SCE "requires bindings in certain contexts to result in a value that is marked as safe to use for that context".

    It is a protection mechanism provided by Angular to developers to easily protect (some aspects of) your app (this is even more important for apps that bind values based on user's input).

    (2)
    Some places (i.e. attributes) are considered more vulnerable to certain kinds of attacks (e.g. XSS) and SCE uses more strict rules for them. A few examples are a form's action or a frame's or object's src/ngSrc.

    (3)
    Based on Angular's current implementation (v1.2.16), an error will be thrown when such a vulnerable attribute is assigned a value that consists of more than 1 "part". A part (accoding to $interpolate service's parsing algorithm is either a part of the expression enclosed in {{ }} or a part of the expression that is outside of {{ }}.

    In your case, /resources/{{id}}/thumbnail is parsed into 3 parts:
    /resources/, {{id}}, /thumbnail


    So, what is the problem with more than 1 part ???

    There is nothing inherently more insecure in concatenating in the view vs concatenating in the controller and using a single-part expression.

    Quoting from Angular's source (emphasis mine):

    // Concatenating expressions makes it hard to reason about whether some combination of
    // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
    // single expression be used for iframe[src], object[src], etc., we ensure that the value
    // that's used 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.

    So, it is Angular's way to force a "more secure" practice on you. Constructing the value in the view is less testable and less explicit, so you (or someone else) will have a harder time auditing the app for XSS vulnerabilities (increasing the probability of security issues).


    There are a couple of ways (already mentioned in DaveA's answer) to circumvent this. (I would definitely not entirely disable $sce, though.)

提交回复
热议问题