Algorithm Search⌘K

Algorithmadvanced

Context-sensitive auto-escaping

Also called contextual auto-sanitization.

Runs an HTML parser model over the static text of a template to find the context of each hole, and inserts the escaper of that context. It rejects templates whose contexts do not agree.

Time
Θ(n) worst · average · best
Space
O(d) extra
Where
d = the nesting depth of the template; n = the size of the template (characters of static text plus nodes)
Properties
deterministicofflinerecursive
Origin
Mike Samuel, Prateek Saxena, Dawn Song, 2011

Context-sensitive auto-escaping makes a web template safe against cross-site scripting without asking the author to choose an escaper for each value. The algorithm reads the static text of the template with a model of the HTML parser, as a finite automaton. At each hole it knows the parser state, called the context: HTML text, a quoted attribute value, the start or the rest of a URL, script code or a script string. It puts the escaper of that context at the hole. It rejects the template when a hole is in a context with no safe escaper, or when the two branches of an IF, or a loop body, end in different contexts. Samuel, Saxena and Song (2011) wrote it as type inference with type qualifiers. The run is one pass, linear in the size of the template, and done once when the template is compiled.

In plain words

A web page template is fixed text with holes, and each hole is filled with a value at run time. A value must be changed before it goes in, so that the browser reads it as plain data. The right change depends on where the hole is. Between tags, an angle bracket must change. Inside a link, a space and a quote must change. Inside a script string, other characters must change.

Authors often forget, or choose the wrong change. This method reads the template once, the way a browser would, and keeps track of where it is. At each hole it writes down the change for that place. If a hole is in a place where no change is safe, or if two paths through the template leave the browser in different places, it stops and reports an error before the page is ever served.

The problem

A template TT is a list of nodes: TEXT(s)(s) with static text ss from the author, PRINT(e)(e) with a hole filled by a value ee at run time, IF(b,T1,T2)(b, T_1, T_2) and LOOP(n,B)(n, B). The static text is trusted and the values are not. The task is to give each PRINT node an escaper so that, for each choice of values, the parser reads each value as data inside one region (a text run, one attribute value, one string literal) and never as markup or code. In the words of Su and Wassermann (2006), the values must not change the syntactic structure of the output. A template for which no such choice exists must be rejected at compile time.

The parser model is a deterministic machine with a state for each context. The code of this page uses a toy subset of HTML: elements with quoted attributes, the URL attributes href and src, and script elements with string literals. It has no comments, character references in static text, unquoted values, CSS or event handler attributes; static text outside the subset is an error.

The algorithm

  1. AUTO-ESCAPE(T, c) ▷ c is the context where T starts
  2. 1for each node t of T, in order do
  3. 2if t is TEXT(s) then
  4. 3c ← TRANSITION(c, s) ▷ run the parser model over s
  5. 4else if t is PRINT(e) then
  6. 5if ESCAPER(c) = none then fail
  7. 6annotate t with ESCAPER(c)
  8. 7c ← AFTER-PRINT(c) ▷ the start of a URL becomes the rest of a URL
  9. 8else if t is IF(b, T1, T2) then
  10. 9c1 ← AUTO-ESCAPE(T1, c); c2 ← AUTO-ESCAPE(T2, c)
  11. 10if c1 ≠ c2 then fail
  12. 11c ← c1
  13. 12else if t is LOOP(n, B) then
  14. 13if AUTO-ESCAPE(B, c) ≠ c then fail
  15. 14return c

The whole template starts in the context TEXT and must end in TEXT. TRANSITION is the parser model. It fails on text outside the subset. ESCAPER maps a context to an escaper:

context escaper what it does
HTML text html &, <, >, " and ' become character references
quoted attribute value html the same, so the value cannot close its quote
start of a URL value url-filter keeps a relative URL or the schemes http, https and mailto; any other scheme becomes about:invalid; then html
rest of a URL value url-encode percent-encodes each UTF-8 byte that is not an unreserved character
script code js-value writes the value as a quoted string literal, with each character that is not a letter, a digit or a space as \uXXXX
script string js-string the same escapes, without the quotes
tag name, attribute name, event handler or style value none the template is rejected

Line L7 changes the context only at the start of a URL: after a value, the parser is no longer at the start, so a second value in the same URL is encoded and not filtered. Lines L10 and L13 are the join rules. A value that is printed after an IF must have one context whatever branch ran, and a loop body must leave the context as it found it, so that each repetition sees the same context. The code returns the annotated template; rendering it calls the chosen escaper on each value.

Example

The template below prints the value name five times and the value link once, in six contexts. The table gives the context that line L3 computes before each hole, the escaper that line L6 chooses, and the output for the benign value O'Neil & <Co>, which holds a quote, an ampersand and angle brackets. The value link is /u.

static text before the hole context escaper output for the hole
<p title=" attribute value, quote " html O&#39;Neil &amp; &lt;Co&gt;
">Hello, HTML text html O&#39;Neil &amp; &lt;Co&gt;
</p><a href=" start of a URL url-filter /u
?ref= rest of a URL url-encode O%27Neil%20%26%20%3CCo%3E
">home</a><script>var n = script code js-value "O\u0027Neil \u0026 \u003cCo\u003e"
; var s = 'Hi script string, quote ' js-string O\u0027Neil \u0026 \u003cCo\u003e

The last static text ';</script> returns the machine to HTML text, so the template is accepted. With link equal to ab:c, a scheme that is not on the list, the third hole renders about:invalid. One escaper for all six holes cannot work: html escaping inside the script string gives &#39;, which a script reads as five characters and not as a quote, and html escaping in the URL leaves the space and the & to end the query value.

Correctness

The claim, for the toy machine: if AUTO-ESCAPE accepts TT, then for each choice of values the machine reads the rendered page without failure and ends in HTML text, the output of each escaper stays inside one text run, attribute value or string literal, and each static character is read in the same context whatever the values are. The key step is a lemma for each escaper: from its context, the escaped output never takes the machine to another context, because it has no character that the machine reacts to there (no < in text, no quote in a value). The loop of line L1 then keeps the invariant that the context computed by the algorithm equals the real context of the machine on the rendered prefix, up to merging the start and the rest of a URL, since an empty value leaves the machine at the start. Lines L10 and L13 make this hold whatever branch runs and however often a loop repeats. The full proof is in proofs/correctness.md.

Proof: Auto-escaping keeps every value inside one data region of the toy HTML machinefull

We use the pseudocode AUTO-ESCAPE of the page and the toy HTML machine of the page. A context cc is a state of the machine with its fields (tag name, attribute name, quote character). δ(c,x)\delta(c, x) is the context after the machine reads the character xx in context cc, and it is undefined when the machine rejects xx. δ∗(c,s)\delta^*(c, s) is the run over a string ss. TRANSITION(c,s)(c, s) computes δ∗(c,s)\delta^*(c, s) and fails when it is undefined.

The URL merge. Let σ(c)\sigma(c) be cc with the two states URL-START and URL-REST replaced by one state URL, with the same fields. The machine reads a quote that closes the value in both states, and goes to URL-REST on each other character, so σ(δ(c,x))\sigma(\delta(c, x)) depends only on σ(c)\sigma(c) and xx. By induction on the length of ss, the same holds for δ∗\delta^*: if σ(c)=σ(d)\sigma(c) = \sigma(d), then δ∗(c,s)\delta^*(c, s) is defined if and only if δ∗(d,s)\delta^*(d, s) is defined, and then σ(δ∗(c,s))=σ(δ∗(d,s))\sigma(\delta^*(c, s)) = \sigma(\delta^*(d, s)). We need σ\sigma because an empty value at the start of a URL leaves the machine in URL-START, while line L7 moves the inferred context to URL-REST.

Lemma 1 (escapers). Let cc be a context with ESCAPER(c)=E(c) = E, not none, and let dd be a context with σ(d)=σ(c)\sigma(d) = \sigma(c). Then for each value vv, δ∗(d,E(v))\delta^*(d, E(v)) is defined and \sigma(\delta^*(d, E(v))) = \sigma(\textsc{After-Print}(c)) = \sigma(c).

Proof. We take the six cases of ESCAPER.

  • TEXT, escaper html. The output has no <, since each < of vv became &lt;. In TEXT the machine changes state only on <, so it stays in TEXT.
  • VALUE with quote qq in an attribute that is not an event handler or a style, escaper html. The output has no " and no '. In VALUE the machine changes state only on qq, so it stays in the same VALUE context.
  • URL-START or URL-REST with quote qq, escaper url-filter or url-encode. The url-filter output is html-escaped, so it has no quote. The url-encode output has only unreserved characters and %XX triples, so it has no quote. In both URL states each character that is not qq leads to URL-REST, so σ\sigma stays URL with the same fields.
  • SCRIPT, escaper js-value. The output is ", then a sequence of ASCII letters, digits, spaces and escapes \uXXXX, then ". The machine goes from SCRIPT to JS-STRING on the first ". In JS-STRING, a letter, a digit or a space keeps the state, and a backslash goes to JS-ESCAPE, from which u returns to JS-STRING; the hex digits then keep JS-STRING. The last " returns to SCRIPT. No < occurs, so the machine does not fail.
  • JS-STRING with quote qq, escaper js-string. The output is the middle part of the last case, so the machine ends in the same JS-STRING context. No quote, no < and no line break occurs. □\square

Lemma 2 (the induction). Suppose AUTO-ESCAPE(T,c)(T, c) returns the context c′c' without failure. Let dd be a context with σ(d)=σ(c)\sigma(d) = \sigma(c), and let ρ\rho be an environment that gives a string to each hole, a truth value to each IF and a count k≥0k \ge 0 to each LOOP. Let RR be the rendering of the annotated TT under ρ\rho. Then δ∗(d,R)\delta^*(d, R) is defined and σ(δ∗(d,R))=σ(c′)\sigma(\delta^*(d, R)) = \sigma(c').

Proof. By induction on the size of TT, and inside one list by induction on the number of nodes done by the loop of line L1. The invariant of that loop is: after the nodes t1,…,tjt_1, \ldots, t_j, the variable cc of the procedure and the real context dj=δ∗(d,R1⋯Rj)d_j = \delta^*(d, R_1 \cdots R_j) have σ(dj)=σ(c)\sigma(d_j) = \sigma(c), where RiR_i is the rendering of tit_i. It holds for j=0j = 0. For the node tj+1t_{j+1}:

  • TEXT(s)(s), lines L2 and L3. TRANSITION(c,s)(c, s) succeeded, so by the URL merge δ∗(dj,s)\delta^*(d_j, s) is defined and has the same σ\sigma as the new cc.
  • PRINT(e)(e), lines L4 to L7. Line L5 did not fail, so ESCAPER(c)(c) is an escaper EE, and line L6 makes the rendering E(ρ(e))E(\rho(e)). By Lemma 1 the real context after it has σ\sigma equal to σ(c)\sigma(c), and line L7 keeps σ(c)\sigma(c).
  • IF(b,T1,T2)(b, T_1, T_2), lines L8 to L11. The rendering is the rendering of T1T_1 or of T2T_2, as ρ(b)\rho(b) says. Both are smaller than TT, and both calls of line L9 returned, with c1=c2c_1 = c_2 by line L10. By the induction hypothesis the real context after the chosen branch has σ\sigma equal to σ(c1)\sigma(c_1), and line L11 sets cc to c1c_1.
  • LOOP(n,B)(n, B), lines L12 and L13. The rendering is kk copies of the rendering of BB, where k=ρ(n)k = \rho(n). Line L13 says that AUTO-ESCAPE(B,c)(B, c) returns cc. By the induction hypothesis on BB, applied kk times, each copy starts and ends in a real context with σ\sigma equal to σ(c)\sigma(c), and cc does not change.

At line L14 the procedure returns cc, and the invariant for the whole list is the claim. □\square

Theorem. If AUTO-ESCAPE of the page accepts the template TT (it returns TEXT from the start context TEXT), then for each environment ρ\rho:

  1. the machine reads the rendering of TT from TEXT without failure and ends in TEXT;
  2. the escaped output of each hole is read inside one data region: a text run, one quoted attribute value or one string literal of a script, and never in a tag, an attribute name or script code (except the two quotes that js-value adds);
  3. each static character of TT is read in a context whose σ\sigma does not depend on ρ\rho.

Proof. Part 1 is Lemma 2 with $c = d = $ TEXT, since σ\sigma is the identity on TEXT. For part 3, the proof of Lemma 2 shows that each static string ss is read from a real context with the same σ\sigma as the inferred context, and the inferred context is computed from TT alone. For part 2, the proof of Lemma 1 shows the states that each escaped output passes through: TEXT, one VALUE context, the URL states of one value, or the JS-STRING and JS-ESCAPE states of one literal. □\square

Part 3 is the property "data stays data": the static characters that open and close tags, attributes and scripts are the same for every value, so a value cannot add or remove a token. Inside its region each value decodes back to itself: html-unescaping inverts html escaping because & is replaced first, percent-decoding inverts percent-encoding byte by byte, and the \uXXXX escapes give back the UTF-16 code units of the value. At the start of a URL the value decodes to its filtered form. The test checks parts 2 and 3 and the decoding with an independent parser on random templates.

Limits. The theorem is about the toy machine. A browser parser has many more states (character references, comments, raw text elements, unquoted values, CSS, event handler attributes), and the claim holds for a real browser only as far as the machine of the code agrees with it. The URL filter checks the value, not the URL that the static text after the hole completes.

Cost. Each node of TT is visited once: line L9 visits each branch once and line L13 visits each loop body once. TRANSITION reads each character of static text once, with O(1)O(1) work when tag and attribute names have bounded length, and the comparisons of lines L10 and L13 compare contexts with a bounded number of fields. So AUTO-ESCAPE runs in Θ(n)\Theta(n) time for a template of size nn (characters of static text plus nodes), with O(d)O(d) extra space for a nesting depth dd besides the annotated copy. ■\blacksquare

Complexity

  • Time. Each node is visited once. Line L9 visits each branch once and line L13 each loop body once; the loop is not unrolled. TRANSITION reads each static character once with O(1)O(1) work, for tag and attribute names of bounded length. So the time is Θ(n)\Theta(n) on every template, where nn counts the characters of static text and the nodes. This is a compile-time cost on the word-RAM.
  • Space. The recursion of lines L9 and L13 is O(d)O(d) deep for a template of nesting depth dd, besides the annotated copy of the template.
  • Run time. Rendering costs what the escapers cost, linear in the length of the output. No parsing happens at run time, which is the main advantage over a run-time sanitizer.

Properties

  • Sound for the model. An accepted template keeps data in data regions for each value, in the sense of the theorem. The guarantee is only as good as the agreement of the parser model with the real browser parser.
  • Conservative. Some safe templates are rejected, for example an IF whose branches end in different contexts that are never followed by a hole.
  • Deterministic and compile time. The output depends only on the template, and the check runs once per template.
  • Static text is trusted. The algorithm protects against values, not against the author. A template that puts a hole inside script code that the author wrote is treated as the author intends.

Variants and improvements

  • Type qualifiers. Samuel, Saxena and Song present the contexts as type qualifiers on the output of each template expression, and the join rules as type checking of branches and loops.
  • Run-time checks for dynamic contexts. Where the context of a hole cannot be known at compile time, a system can track it at run time and choose the escaper then, at a run-time cost.
  • Typed values. Go's html/template and the Closure systems let trusted code mark a value as already safe for one context, for example as HTML from a sanitizer, so the escaper keeps it as is.
  • More contexts. Real systems model comments, CSS, unquoted attribute values, event handler attributes and the many string and regular expression states of JavaScript. The toy machine of this page rejects them.

When to use it

Use it in a template system that produces HTML, so that escaping is the default and not a task for each author. It removes the most common causes of cross-site scripting in server templates: a missing escaper and the wrong escaper. It does not cover values that reach the page by script at run time in the browser (DOM-based cases), nor values that the author marks as trusted. Use it together with a content security policy, which limits what an escaping mistake can do. For SQL, the matching check of the output structure is parse-tree query validation, but prepared statements are the better defense there.

Pitfalls

  • One escaper everywhere. Line L6 with html escaping for all contexts is wrong: a script string decodes &#39; as five characters, and a URL keeps the space and & that end a query value. The right line L6 uses ESCAPER(c)(c).
  • No join check. Without line L10, a value after an IF gets the escaper of one branch only; when the other branch runs, the parser may be in an attribute value and the html escaper of text no longer matches. The right line L10 fails when c1≠c2c_1 \ne c_2.
  • A loop checked once. Without line L13, the first repetition of a loop body is right and the second starts in the context the body left. Line L13 requires the body to end where it began.
  • A missing AFTER-PRINT. Without line L7, a second value in a URL is filtered as if it were the start of a URL, and its characters are not encoded. The context must change after the first value.
  • A parser model that differs from the browser. If TRANSITION handles a state in a different way than the browser does, the proof holds for the model and the page can still break. This is why real systems reject the cases they do not model.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

context_sensitive_auto_escaping.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/context-sensitive-auto-escaping/. The authors are listed in prov/ZZYC2R.jsonl.

"""Context-sensitive auto-escaping for a toy HTML template language.

A template is a list of nodes:
  ("text", s)            static text written by the template author
  ("print", name)        a hole filled at render time with the value env[name]
  ("if", name, T1, T2)   T1 when env[name] is true, else T2
  ("loop", name, B)      B repeated env[name] times

auto_escape walks the template once with a small HTML state machine. It
gives each hole the escaper that matches the parsing context at that point,
and it rejects a template whose context at a hole has no safe escaper, or
whose branches or loop bodies end in different contexts. This is the core of
the type inference of Samuel, Saxena and Song (CCS 2011), on a toy subset of
HTML: elements, quoted attributes, URL attributes and script elements with
string literals. It is a teaching model, not a full HTML parser.
"""

from typing import NamedTuple, Union

Node = tuple
Template = list


class EscapeError(ValueError):
    """The template has a hole in an unsafe context, or its contexts do not join."""


class Context(NamedTuple):
    """A parsing context: the state of the toy HTML machine and its fields."""

    state: str
    tag: str = ""
    attr: str = ""
    quote: str = ""


TEXT = Context("TEXT")
URL_ATTRS = frozenset({"href", "src"})
SAFE_SCHEMES = frozenset({"http", "https", "mailto"})
INVALID_URL = "about:invalid"


def _after_tag(tag: str) -> Context:
    return Context("SCRIPT", tag) if tag == "script" else TEXT


def transition(c: Context, s: str) -> Context:
    """Run the toy HTML state machine from context c over the static text s.

    Raises EscapeError on text outside the toy subset. Cost: O(len(s)).
    """
    i = 0
    n = len(s)
    while i < n:
        ch = s[i]
        st = c.state
        if st == "TEXT":
            if ch == "<":
                c = Context("TAG_OPEN")
        elif st == "TAG_OPEN":
            if ch.isascii() and ch.isalpha():
                c = Context("TAG_NAME", ch.lower())
            elif ch == "/":
                c = Context("END_TAG_OPEN")
            else:
                raise EscapeError("bad character after '<'")
        elif st == "TAG_NAME":
            if ch.isascii() and ch.isalnum():
                c = Context("TAG_NAME", c.tag + ch.lower())
            elif ch == " ":
                c = Context("TAG", c.tag)
            elif ch == ">":
                c = _after_tag(c.tag)
            else:
                raise EscapeError("bad character in a tag name")
        elif st == "TAG":
            if ch == " ":
                pass
            elif ch.isascii() and ch.isalpha():
                c = Context("ATTR_NAME", c.tag, ch.lower())
            elif ch == ">":
                c = _after_tag(c.tag)
            else:
                raise EscapeError("bad character in a tag")
        elif st == "ATTR_NAME":
            if (ch.isascii() and ch.isalpha()) or ch == "-":
                c = Context("ATTR_NAME", c.tag, c.attr + ch.lower())
            elif ch == "=":
                c = Context("BEFORE_VALUE", c.tag, c.attr)
            elif ch == " ":
                c = Context("TAG", c.tag)
            elif ch == ">":
                c = _after_tag(c.tag)
            else:
                raise EscapeError("bad character in an attribute name")
        elif st == "BEFORE_VALUE":
            if ch in "\"'":
                kind = "URL_START" if c.attr in URL_ATTRS else "VALUE"
                c = Context(kind, c.tag, c.attr, ch)
            else:
                raise EscapeError("the toy subset needs quoted attribute values")
        elif st in ("VALUE", "URL_START", "URL_REST"):
            if ch == c.quote:
                c = Context("TAG", c.tag)
            elif st == "URL_START":
                c = Context("URL_REST", c.tag, c.attr, c.quote)
        elif st == "END_TAG_OPEN":
            if ch.isascii() and ch.isalpha():
                c = Context("END_TAG_NAME")
            else:
                raise EscapeError("bad character after '</'")
        elif st == "END_TAG_NAME":
            if ch == ">":
                c = TEXT
            elif not (ch.isascii() and ch.isalnum()):
                raise EscapeError("bad character in an end tag")
        elif st == "SCRIPT":
            if s.startswith("</script>", i):
                c = TEXT
                i += len("</script>")
                continue
            if ch in "\"'":
                c = Context("JS_STRING", "script", "", ch)
            elif ch == "<":
                raise EscapeError("the toy subset allows '<' in a script only in '</script>'")
        elif st == "JS_STRING":
            if ch == "\\":
                c = Context("JS_ESCAPE", "script", "", c.quote)
            elif ch == c.quote:
                c = Context("SCRIPT", "script")
            elif ch in "\n<":
                raise EscapeError("bad character in a script string")
        elif st == "JS_ESCAPE":
            if ch == "\n":
                raise EscapeError("bad escape in a script string")
            c = Context("JS_STRING", "script", "", c.quote)
        else:  # pragma: no cover
            raise EscapeError("unknown state " + st)
        i += 1
    return c


def escaper_for(c: Context) -> Union[str, None]:
    """The name of the escaper for a hole in context c, or None if no escaper is safe."""
    st = c.state
    if st == "TEXT":
        return "html"
    if st == "VALUE":
        if c.attr.startswith("on") or c.attr == "style":
            return None  # script or style inside an attribute: not in the toy subset
        return "html"
    if st == "URL_START":
        return "url_filter"
    if st == "URL_REST":
        return "url_encode"
    if st == "SCRIPT":
        return "js_value"
    if st == "JS_STRING":
        return "js_string"
    return None


def after_print(c: Context) -> Context:
    """The context after a hole. Escaped output never leaves its context,
    except that a URL is no longer at its start."""
    if c.state == "URL_START":
        return Context("URL_REST", c.tag, c.attr, c.quote)
    return c


def escape_nodes(nodes: Template, c: Context) -> tuple[Template, Context]:
    """AUTO-ESCAPE of the page: annotate each hole of nodes, started in context c.

    Returns the annotated nodes and the context at the end. Raises EscapeError.
    Cost: O(n) for a template of total size n (characters of text plus nodes).
    """
    out: Template = []
    for t in nodes:  # @line L1
        kind = t[0]
        if kind == "text":  # @line L2
            c = transition(c, t[1])  # @line L3
            out.append(t)
        elif kind == "print":  # @line L4
            esc = escaper_for(c)
            if esc is None:
                raise EscapeError(f"no safe escaper for a hole in state {c.state}")  # @line L5
            out.append(("print", t[1], esc))  # @line L6
            c = after_print(c)  # @line L7
        elif kind == "if":  # @line L8
            t1, c1 = escape_nodes(t[2], c)  # @line L9
            t2, c2 = escape_nodes(t[3], c)
            if c1 != c2:  # @line L10
                raise EscapeError("the branches of an if end in different contexts")
            out.append(("if", t[1], t1, t2))
            c = c1  # @line L11
        elif kind == "loop":  # @line L12
            body, cb = escape_nodes(t[2], c)
            if cb != c:  # @line L13
                raise EscapeError("a loop body does not end in the context where it starts")
            out.append(("loop", t[1], body))
        else:
            raise EscapeError("unknown node " + repr(kind))
    return out, c  # @line L14


def auto_escape(template: Template) -> Template:
    """Annotate a whole template. It starts and must end in HTML text."""
    out, c = escape_nodes(template, TEXT)
    if c != TEXT:
        raise EscapeError(f"the template ends in state {c.state}, not in text")
    return out


# ---------------------------------------------------------------- escapers


def escape_html(v: str) -> str:
    """Escape the five HTML special characters. Safe in text and in quoted values."""
    return (
        v.replace("&", "&amp;")
        .replace("<", "&lt;")
        .replace(">", "&gt;")
        .replace('"', "&quot;")
        .replace("'", "&#39;")
    )


def filter_url(v: str) -> str:
    """Keep a relative URL or one with an allowed scheme; else return a harmless URL."""
    for k, ch in enumerate(v):
        if ch in "/?#":
            return v  # no scheme: a relative URL
        if ch == ":":
            return v if v[:k].lower() in SAFE_SCHEMES else INVALID_URL
    return v


_UNRESERVED = frozenset("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")


def percent_encode(v: str) -> str:
    """Percent-encode every UTF-8 byte that is not an unreserved URL character."""
    out = []
    for b in v.encode("utf-8"):
        ch = chr(b)
        out.append(ch if ch in _UNRESERVED else "%%%02X" % b)
    return "".join(out)


def escape_js_string(v: str) -> str:
    """Write each character that is not a letter, a digit or a space as a \\uXXXX escape."""
    out = []
    for ch in v:
        if (ch.isascii() and ch.isalnum()) or ch == " ":
            out.append(ch)
        else:
            units = ch.encode("utf-16-be")
            for k in range(0, len(units), 2):
                out.append("\\u%04x" % int.from_bytes(units[k : k + 2], "big"))
    return "".join(out)


ESCAPERS = {
    "html": escape_html,
    "url_filter": lambda v: escape_html(filter_url(v)),
    "url_encode": percent_encode,
    "js_string": escape_js_string,
    "js_value": lambda v: '"' + escape_js_string(v) + '"',
}


def render(template: Template, env: dict) -> str:
    """Render an annotated template. env maps hole names to strings, if names
    to booleans and loop names to repeat counts. Cost: linear in the output."""
    parts: list[str] = []
    stack = [iter(template)]
    while stack:
        t = next(stack[-1], None)
        if t is None:
            stack.pop()
            continue
        kind = t[0]
        if kind == "text":
            parts.append(t[1])
        elif kind == "print":
            if len(t) < 3:
                raise EscapeError("render needs an annotated template")
            parts.append(ESCAPERS[t[2]](str(env[t[1]])))
        elif kind == "if":
            stack.append(iter(t[2] if env[t[1]] else t[3]))
        elif kind == "loop":
            stack.append(iter([node for _ in range(int(env[t[1]])) for node in t[2]]))
    return "".join(parts)
test_context_sensitive_auto_escaping.py 395 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/context-sensitive-auto-escaping/. The authors are listed in prov/ZZYC2R.jsonl.

import random
import re

import pytest

from context_sensitive_auto_escaping import (
    TEXT,
    Context,
    EscapeError,
    auto_escape,
    escape_html,
    filter_url,
    render,
    transition,
)

# ------------------------------------------------------------ an independent parser
# The oracle parses the rendered output with its own small tokenizer (regular
# expressions, written apart from the state machine of the code under test). It
# turns a document into tokens with decoded data: text runs, start tags with
# decoded attribute values, end tags, script code runs and decoded script strings.

START_TAG = re.compile(r"<([a-z][a-z0-9]*)((?: +[a-z][a-z-]*(?:=\"[^\"]*\"|='[^']*')?)*) *>")
ATTR = re.compile(r" +([a-z][a-z-]*)(?:=\"([^\"]*)\"|='([^']*)')?")
END_TAG = re.compile(r"</([a-z][a-z0-9]*)>")


def html_unescape(s: str) -> str:
    return (
        s.replace("&lt;", "<")
        .replace("&gt;", ">")
        .replace("&quot;", '"')
        .replace("&#39;", "'")
        .replace("&amp;", "&")
    )


def js_decode(body: str) -> str:
    units: list[int] = []
    k = 0
    while k < len(body):
        if body[k] == "\\":
            if body[k + 1] == "u":
                units.append(int(body[k + 2 : k + 6], 16))
                k += 6
            else:
                units.append(ord(body[k + 1]))
                k += 2
        else:
            raw16 = body[k].encode("utf-16-be")
            units.extend(int.from_bytes(raw16[j : j + 2], "big") for j in range(0, len(raw16), 2))
            k += 1
    raw = b"".join(u.to_bytes(2, "big") for u in units)
    return raw.decode("utf-16-be", "surrogatepass")


def parse_script(src: str) -> list:
    toks = []
    code = []
    k = 0
    while k < len(src):
        ch = src[k]
        if ch in "\"'":
            if code:
                toks.append(("js_code", "".join(code)))
                code = []
            j = k + 1
            while src[j] != ch:
                j += 2 if src[j] == "\\" else 1
            toks.append(("js_str", js_decode(src[k + 1 : j])))
            k = j + 1
        else:
            code.append(ch)
            k += 1
    if code:
        toks.append(("js_code", "".join(code)))
    return toks


def parse(doc: str) -> list:
    toks = []
    k = 0
    while k < len(doc):
        if doc.startswith("</", k):
            m = END_TAG.match(doc, k)
            assert m, doc[k:]
            toks.append(("end", m.group(1)))
            k = m.end()
        elif doc[k] == "<":
            m = START_TAG.match(doc, k)
            assert m, doc[k:]
            attrs = tuple(
                (a.group(1), html_unescape(a.group(2) if a.group(2) is not None else (a.group(3) or "")))
                for a in ATTR.finditer(m.group(2))
            )
            toks.append(("start", m.group(1), attrs))
            k = m.end()
            if m.group(1) == "script":
                j = doc.index("</script>", k)
                toks.extend(parse_script(doc[k:j]))
                toks.append(("end", "script"))
                k = j + len("</script>")
        else:
            j = doc.find("<", k)
            j = len(doc) if j < 0 else j
            toks.append(("text", html_unescape(doc[k:j])))
            k = j
    return toks


# ------------------------------------------------------------ the oracle

SENTINEL = "\u00a7"


def pct(v: str) -> str:
    keep = set("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~")
    return "".join(chr(b) if chr(b) in keep else "%{:02X}".format(b) for b in v.encode())


def expected_url_start(v: str) -> str:
    m = re.match(r"([^/?#:]*):", v)
    if m and m.group(1).lower() not in ("http", "https", "mailto"):
        return "about:invalid"
    return v


def print_sequence(template: list, env: dict) -> list:
    seq = []
    for t in template:
        if t[0] == "print":
            seq.append(env[t[1]])
        elif t[0] == "if":
            seq.extend(print_sequence(t[2] if env[t[1]] else t[3], env))
        elif t[0] == "loop":
            for _ in range(env[t[1]]):
                seq.extend(print_sequence(t[2], env))
    return seq


def expected_tokens(sentinel_toks: list, values: list) -> list:
    """Put the expected decoded value of each hole where its sentinel is."""
    vals = iter(values)

    def sub(s: str, url: bool) -> str:
        if url:  # after the start of a URL the sentinel is percent-encoded
            s = s[:1] + s[1:].replace(pct(SENTINEL), SENTINEL)
        out = []
        for pos, ch in enumerate(s):
            if ch != SENTINEL:
                out.append(ch)
                continue
            v = next(vals)
            if url:
                out.append(expected_url_start(v) if pos == 0 else pct(v))
            else:
                out.append(v)
        return "".join(out)

    res = []
    for tok in sentinel_toks:
        if tok[0] == "start":
            res.append(("start", tok[1], tuple((a, sub(v, a in ("href", "src"))) for a, v in tok[2])))
        elif tok[0] == "text":
            s = sub(tok[1], False)
            if s:  # a text run of empty values leaves no text in the output
                res.append(("text", s))
        elif tok[0] == "js_str":
            res.append(("js_str", sub(tok[1], False)))
        elif tok[0] == "js_code":
            assert SENTINEL not in tok[1]
            res.append(tok)
        else:
            res.append(tok)
    assert next(vals, None) is None
    return res


def check_template(template: list, env: dict, escaped: list) -> None:
    """Data stays data: the rendered output parses to the same tokens as the
    sentinel rendering, and each hole decodes back to its value."""
    sentinel_env = {k: (SENTINEL if isinstance(v, str) else v) for k, v in env.items()}
    sentinel_toks = parse(render(escaped, sentinel_env))
    real_toks = parse(render(escaped, env))
    assert real_toks == expected_tokens(sentinel_toks, print_sequence(template, env))


# ------------------------------------------------------------ generators

TEXT_WORDS = ["ab", " ", "x > y", "1 2", "Q:", '"q"', "it's", "a/b"]
VALUE_WORDS = ["ab", " ", "c d", "1-2", "x/y"]
URL_WORDS = ["/a", "/p?q=", "#top", "http://example.com/"]
JS_WORDS = ["ab", " ", "c d"]
ALPHABET = "ab01<>&\"' \\:/=?#"


def gen_value(rng: random.Random) -> str:
    r = rng.random()
    if r < 0.15:
        return rng.choice(["http://example.org/a", "mailto:a", "ab:c", "/x?y=1", "HTTPS:b", ""])
    return "".join(rng.choice(ALPHABET) for _ in range(rng.randrange(6)))


def gen_attr_value(rng: random.Random, name: str, quote: str) -> list:
    nodes: list = []
    words = URL_WORDS if name in ("href", "src") else VALUE_WORDS
    for _ in range(rng.randrange(3)):
        if rng.random() < 0.5:
            nodes.append(("print", rng.choice("xyz")))
        else:
            nodes.append(("text", rng.choice(words)))
    return [("text", f" {name}={quote}")] + nodes + [("text", quote)]


def gen_script(rng: random.Random) -> list:
    nodes: list = [("text", "<script>")]
    for _ in range(rng.randrange(1, 3)):
        if rng.random() < 0.5:
            nodes += [("text", "var a = "), ("print", rng.choice("xyz")), ("text", "; ")]
        else:
            q = rng.choice("\"'")
            nodes.append(("text", "var b = " + q))
            for _ in range(rng.randrange(3)):
                nodes.append(("print", rng.choice("xyz")) if rng.random() < 0.5 else ("text", rng.choice(JS_WORDS)))
            nodes.append(("text", q + "; "))
    nodes.append(("text", "</script>"))
    return nodes


def gen_element(rng: random.Random, depth: int) -> list:
    if rng.random() < 0.2:
        return gen_script(rng)
    tag = rng.choice(["p", "div", "a", "span"])
    nodes: list = [("text", "<" + tag)]
    for name in rng.sample(["title", "href", "class", "src"], rng.randrange(3)):
        nodes += gen_attr_value(rng, name, rng.choice("\"'"))
    nodes.append(("text", ">"))
    nodes += gen_content(rng, depth - 1)
    nodes.append(("text", f"</{tag}>"))
    return nodes


def gen_content(rng: random.Random, depth: int) -> list:
    nodes: list = []
    for _ in range(rng.randrange(4 if depth > 0 else 2)):
        r = rng.random()
        if r < 0.3:
            nodes.append(("text", rng.choice(TEXT_WORDS)))
        elif r < 0.55:
            nodes.append(("print", rng.choice("xyz")))
        elif r < 0.8 and depth > 0:
            nodes += gen_element(rng, depth)
        elif r < 0.9 and depth > 0:
            nodes.append(("if", rng.choice("pq"), gen_content(rng, depth - 1), gen_content(rng, depth - 1)))
        elif depth > 0:
            nodes.append(("loop", "n", gen_content(rng, depth - 1)))
    return nodes


def gen_env(rng: random.Random) -> dict:
    env = {v: gen_value(rng) for v in "xyz"}
    env.update({b: rng.random() < 0.5 for b in "pq"})
    env["n"] = rng.randrange(3)
    return env


# ------------------------------------------------------------ tests

EXAMPLE = [
    ("text", "<p title=\""),
    ("print", "name"),
    ("text", "\">Hello, "),
    ("print", "name"),
    ("text", "</p><a href=\""),
    ("print", "link"),
    ("text", "?ref="),
    ("print", "name"),
    ("text", "\">home</a><script>var n = "),
    ("print", "name"),
    ("text", "; var s = 'Hi "),
    ("print", "name"),
    ("text", "';</script>"),
]


def test_page_example() -> None:
    escaped = auto_escape(EXAMPLE)
    assert [t[2] for t in escaped if t[0] == "print"] == [
        "html",
        "html",
        "url_filter",
        "url_encode",
        "js_value",
        "js_string",
    ]
    env = {"name": "O'Neil & <Co>", "link": "/u"}
    out = render(escaped, env)
    assert out == (
        '<p title="O&#39;Neil &amp; &lt;Co&gt;">Hello, O&#39;Neil &amp; &lt;Co&gt;</p>'
        '<a href="/u?ref=O%27Neil%20%26%20%3CCo%3E">home</a>'
        '<script>var n = "O\\u0027Neil \\u0026 \\u003cCo\\u003e"; '
        "var s = 'Hi O\\u0027Neil \\u0026 \\u003cCo\\u003e';</script>"
    )
    check_template(EXAMPLE, env, escaped)
    out2 = render(escaped, {"name": "a", "link": "ab:c"})
    assert 'href="about:invalid?ref=a"' in out2


def test_transition_trace() -> None:
    c = transition(TEXT, "<a href=\"")
    assert c == Context("URL_START", "a", "href", '"')
    assert transition(c, "/x") == Context("URL_REST", "a", "href", '"')
    assert transition(TEXT, "<script>var s = '") == Context("JS_STRING", "script", "", "'")
    assert transition(TEXT, "<script>x</script>") == TEXT


def test_escapers() -> None:
    assert escape_html("") == ""
    assert escape_html("a\\b") == "a\\b"
    assert escape_html("<&>\"'") == "&lt;&amp;&gt;&quot;&#39;"
    assert filter_url("/a:b") == "/a:b"
    assert filter_url("Http://h") == "Http://h"
    assert filter_url("ab:c") == "about:invalid"
    assert filter_url(":x") == "about:invalid"
    assert filter_url("plain") == "plain"


def test_empty_and_plain() -> None:
    assert auto_escape([]) == []
    assert render(auto_escape([("print", "x")]), {"x": ""}) == ""
    t = [("text", "<p>"), ("print", "x"), ("text", "</p>")]
    assert render(auto_escape(t), {"x": "\\\\"}) == "<p>\\\\</p>"


@pytest.mark.parametrize(
    "template",
    [
        [("text", "<p "), ("print", "x"), ("text", ">")],  # attribute name position
        [("text", "<p class="), ("print", "x"), ("text", ">")],  # unquoted value
        [("text", "<p onclick=\""), ("print", "x"), ("text", "\">")],  # script in an attribute
        [("text", "<p style='"), ("print", "x"), ("text", "'>")],  # style attribute
        [("text", "<"), ("print", "x"), ("text", ">")],  # tag name position
        [("if", "p", [("text", "<p title=\"")], []), ("print", "x"), ("text", "\">")],  # branches differ
        [("loop", "n", [("text", "<b title='")]), ("text", "'>")],  # loop body changes the context
        [("text", "<p title=\"a")],  # template ends inside a tag
        [("text", "<script>var s = '\\"), ("print", "x"), ("text", "';</script>")],  # hole after a backslash
    ],
)
def test_rejects_unsafe_templates(template: list) -> None:
    with pytest.raises(EscapeError):
        auto_escape(template)


def test_random_templates_against_parser() -> None:
    rng = random.Random(20111017)
    checked = 0
    for _ in range(600):
        template = gen_content(rng, 3)
        escaped = auto_escape(template)  # the generator makes only safe templates
        for _ in range(2):
            check_template(template, gen_env(rng), escaped)
            checked += 1
    assert checked == 1200


def test_html_escaping_everywhere_is_wrong() -> None:
    """A single escaper for all contexts breaks the decoding in scripts and URLs."""
    rng = random.Random(7)
    failures = 0
    for _ in range(300):
        template = gen_content(rng, 3)
        escaped = auto_escape(template)

        def naive(nodes: list) -> list:
            out = []
            for t in nodes:
                if t[0] == "print":
                    out.append(("print", t[1], "html"))
                elif t[0] == "if":
                    out.append(("if", t[1], naive(t[2]), naive(t[3])))
                elif t[0] == "loop":
                    out.append(("loop", t[1], naive(t[2])))
                else:
                    out.append(t)
            return out

        env = gen_env(rng)
        try:
            check_template(template, env, naive(escaped))
        except AssertionError:
            failures += 1
    assert failures > 30

History

Escaping by hand, with a function call for each value, was the rule for many years, and auto-escaping first meant one HTML escaper for all values, which is wrong in scripts and URLs. Samuel, Saxena and Song (CCS 2011) gave the context-sensitive version as type inference with type qualifiers and implemented it for the Closure Templates system. Go's html/template package uses the same approach, with errors for branches and loops that end in different contexts.

References

  1. Mike Samuel, Prateek Saxena and Dawn Song, Context-sensitive auto-sanitization in web templating languages using type qualifiers, ACM CCS 2011, pages 587 to 600, the context type qualifiers, the inference of contexts over branches and loops, and the choice of a sanitizer for each context
  2. Zhendong Su and Gary Wassermann, The essence of command injection attacks in web applications, POPL 2006, pages 372 to 382, the definition of an injection as input that changes the syntactic structure of the output (syntactic confinement)
  3. The Go standard library, package html/template, the package overview (contexts, the escapers it adds to each action, and the errors for branches and loops that end in different contexts)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/ZZYC2R/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example