Algorithm Search⌘K

Algorithmadvanced

Parse-tree validation of queries

Also called SQLGuard, SQLCheck.

Parses a query once with placeholders for the inputs and once with the real inputs, and rejects it unless the trees have the same shape and each input stays inside one literal.

Time
Θ(n) worst · average · best
Space
O(n) extra
Where
n = the length of the query with inputs plus the length of the query with placeholders
Properties
deterministiconlinerecursive
Origin
Gregory Buehrer, Bruce W. Weide, Paolo A. G. Sivilotti, Zhendong Su, Gary Wassermann, 2005

Parse-tree validation is a run-time check against SQL injection. The program builds a query from static text and inputs. Before the query goes to the database, the validator parses it twice with the grammar of the query language: once with each input replaced by a fixed placeholder, which gives the parse tree the programmer planned, and once with the real inputs. It accepts the query only when the two trees have the same shape and each input lies inside the literal that holds its placeholder. An input can then change a value but never a keyword, a name, an operator or the nesting of the query. Buehrer, Weide and Sivilotti (2005) gave the method, and Su and Wassermann (2006) gave the general criterion, syntactic confinement. The check is linear in the length of the query. It is a second line of defense: the first is a prepared statement, which sends the inputs apart from the query text.

In plain words

A program often makes a database query by gluing text together: a fixed part written by the programmer, then a value typed by a user, then more fixed text. The danger is that the value changes what the query means, for example because it holds a quote that ends a string early.

The check asks a simple question: does the query still have the form the programmer meant? To learn that form, it builds the same query with a harmless dummy in place of each value and reads its grammar structure. Then it reads the real query the same way. If the two structures match, and each value sits inside one quoted string or one number, the query goes on. If not, the query is stopped before the database sees it.

The problem

The input is a query template, static parts p0,…,pkp_0, \ldots, p_k from the programmer, and the inputs x1,…,xkx_1, \ldots, x_k. The query is q=p0x1p1⋯xkpkq = p_0 x_1 p_1 \cdots x_k p_k. The intended query q0q_0 is the same text with each xix_i replaced by a placeholder, here the one-character number 1. The task is to accept qq exactly when the inputs are syntactically confined: the parse tree of qq is the parse tree of q0q_0 with only the text of literals changed, and each input lies inside the literal that holds its placeholder.

The code of this page uses a toy subset of SQL: SELECT columns FROM a table, an optional WHERE condition with AND, OR, NOT, parentheses and the comparisons =, <>, <, <=, > and >=. Literals are numbers and strings in single quotes, with two quotes for a quote inside. A backslash is an ordinary character, as in standard SQL. The validator must know where each input starts and ends; the code keeps an origin for each character, either a static position or the number of an input.

The algorithm

  1. VALIDATE(p0, ..., pk; x1, ..., xk)
  2. 1q ← p0 x1 p1 ... xk pk, with the origin of each character
  3. 2q0 ← the same with each xi replaced by the placeholder
  4. 3A ← PARSE(q0)
  5. 4if A fails, or a placeholder is not inside exactly one literal of A then template error
  6. 5B ← PARSE(q)
  7. 6if B fails then reject
  8. 7if SHAPE(A) ≠ SHAPE(B) then reject ▷ SHAPE erases the text of literals
  9. 8for each pair of leaves a of A and b of B in the same place do
  10. 9if the origins of the first and the last characters of a and b differ then reject
  11. 10accept, with the tree B

PARSE builds the concrete parse tree, so each token is a leaf, and SHAPE keeps each node label and the kind and text of each leaf, but writes each literal as a bare "literal". Line L4 checks the template, not the inputs: if the programmer put a hole where a column name goes, no input can be a literal there, and the template is an error. Line L7 checks the structure. Lines L8 and L9 check the boundaries of the tokens: a token that starts or ends on a static character must start or end on the same static character in both queries. This rules out an input whose literal runs over the static text after it.

The template check of lines L2 to L4 depends only on the template, so a real system does it once and caches the tree AA.

Example

The template is SELECT a FROM t WHERE name = ' then x1x_1 then ' AND id = then x2x_2. The inputs are x1=x_1 = O''Brien, a name with the quote already doubled by the program, and x2=x_2 = 42. The table shows the tokens of the two queries and the origins of their first and last characters. sms_m is static character mm and h2h_2 is input 2.

leaves token of q0q_0 token of qq origins in q0q_0 origins in qq line L9
1 to 7 SELECT a FROM t WHERE name = the same s0s_0 to s27s_{27} the same equal
8 '1' 'O''Brien' s29s_{29}, s30s_{30} s29s_{29}, s30s_{30} equal
9 to 11 AND id = the same s32s_{32} to s39s_{39} the same equal
12 1 42 h2h_2, h2h_2 h2h_2, h2h_2 equal

Line L7 finds the same shape, with 12 leaves in both trees, so VALIDATE accepts. Three benign changes show the rejections:

  • x1=x_1 = O'Brien, with the quote not doubled. The string ends after O, the rest of the name is read as a name, and the closing quote opens a string that never ends. Line L6 rejects.
  • x2=x_2 = 4 2. The query has 13 tokens, not 12, and the grammar allows no second number after a comparison, so line L6 rejects. A grammar that allowed it would give a different shape, and line L7 would reject.
  • x2=x_2 = id. The query parses, but leaf 12 is a column name and not a literal, so the shapes differ at line L7.

An input with blanks around a number, such as 42, is accepted, and so is a complete string literal in place of the number.

Correctness

The claim: when the template passes line L4, VALIDATE accepts exactly when qq parses, its tree has the shape of the tree of q0q_0, and the jj-th tokens of the two queries start and end on characters of the same origin. Then each static character is in a token of the same kind and text as in q0q_0, and each non-blank character of xix_i is inside the literal that holds the placeholder of xix_i. The key fact is that origins never decrease along a query and that each static character and each one-character placeholder occurs once, so a token contains a character exactly when the character lies between the origins of the ends of the token. The proof also shows a simpler form of the condition, input by input: an input in a quoted hole is accepted exactly when its runs of quotes have even length, and an input in a number position exactly when it is one literal with blanks around it. The test checks the validator against this form on random benign inputs. The full proof is in proofs/correctness.md.

Proof: Parse-tree validation accepts exactly the queries whose inputs stay inside their literalsfull

We use the pseudocode VALIDATE of the page and its toy SQL grammar. The template has static parts p0,…,pkp_0, \ldots, p_k and the inputs are x1,…,xkx_1, \ldots, x_k. Line L1 builds q=p0x1p1⋯xkpkq = p_0 x_1 p_1 \cdots x_k p_k and line L2 builds q0q_0, the same text with each xix_i replaced by the one-character placeholder 1.

Origins. Each character of qq and of q0q_0 has an origin: sms_m for the mm-th static character, or hih_i for a character of input ii (in q0q_0, the placeholder of input ii). Order the origins as they occur in the template: sm<his_m < h_i when the static character mm comes before hole ii, and so on. Along qq and along q0q_0 the origins never decrease. Each static origin occurs exactly once in each string, and in q0q_0 each hih_i also occurs exactly once, because the placeholder has one character.

Fact 1. Let uu be a token of qq from position aa to position bb, and let oo be an origin that occurs exactly once in qq, at position pp. Then pp is in uu if and only if orig(a)≤o≤orig(b)\mathrm{orig}(a) \le o \le \mathrm{orig}(b).

Proof. If a≤p≤ba \le p \le b, monotonicity gives the inequalities. Conversely, if p<ap < a then o=orig(p)≤orig(a)o = \mathrm{orig}(p) \le \mathrm{orig}(a), and equality would put the unique occurrence of oo at aa, not at pp; so o<orig(a)o < \mathrm{orig}(a). The case p>bp > b is the same. □\square

The same holds in q0q_0, where all origins are unique.

The template check. Lines L3 and L4 require that q0q_0 parses to a tree AA, and that the placeholder of each input meets exactly one token of AA, a literal. Call it the literal of input ii, λi\lambda_i.

Theorem. Assume the template passes lines L3 and L4. VALIDATE accepts if and only if (a) qq parses to a tree BB; (b) BB and AA have the same shape when the text of each literal is erased; and (c) for each jj, the jj-th token of BB starts and ends at characters whose origins are those of the start and the end of the jj-th token of AA. When it accepts:

  1. BB is AA with the text of some literals changed. The structure of the query is the one the programmer planned.
  2. Each static character is in the jj-th token of qq if and only if it is in the jj-th token of q0q_0, and the two tokens have the same kind, and the same text when they are not literals.
  3. Each character of xix_i that is not a blank is inside the token of BB at the position of λi\lambda_i, which is a literal. No character of an input is part of a keyword, a name, an operator or a parenthesis.

Proof. Lines L5 and L6 reject when (a) fails, line L7 when (b) fails, and lines L8 and L9 when (c) fails. The leaves of a concrete parse tree are the tokens in order, so (b) gives the same number of tokens and lets line L8 pair them. So VALIDATE accepts exactly when (a), (b) and (c) hold. Claim 1 is (b).

For claim 2, let sms_m be a static origin and let bjb_j and aja_j be the jj-th tokens of qq and q0q_0. By Fact 1 in qq, sms_m is in bjb_j if and only if orig(start bj)≤sm≤orig(end bj)\mathrm{orig}(\mathrm{start}\ b_j) \le s_m \le \mathrm{orig}(\mathrm{end}\ b_j). By (c) the bounds are those of aja_j, and by Fact 1 in q0q_0 this holds if and only if sms_m is in aja_j. The kinds and texts agree by (b).

For claim 3, let cc be a character of xix_i that is not a blank. The lexer puts each character that is not a blank between tokens into a token, so cc is in some bjb_j, and by monotonicity orig(start bj)≤hi≤orig(end bj)\mathrm{orig}(\mathrm{start}\ b_j) \le h_i \le \mathrm{orig}(\mathrm{end}\ b_j). By (c) the same holds for aja_j, and since hih_i occurs once in q0q_0, Fact 1 says that the placeholder is in aja_j. So aj=λia_j = \lambda_i, a literal, and by (b) bjb_j is a literal too. □\square

The local form of the condition. The test of the page checks VALIDATE against a simpler description, input by input. Call hole ii quoted when λi\lambda_i is a string literal that starts at the static quote just before the hole and ends at the static quote just after it, and unquoted when λi\lambda_i is the placeholder alone, with a blank, an operator or the end of the text on each side.

Lemma. For a template whose holes are all quoted or unquoted, VALIDATE accepts if and only if each quoted input has only runs of quotes of even length, and each unquoted input is blanks, one number or one complete string literal, and blanks.

Proof. Only if. Let hole ii be quoted. By claim 2, the token of qq that holds the static quote before the hole is a string that ends at the static quote after it. The string lexer reads a pair of quotes as one quote and stops at the first quote that is not followed by another. If a quote run of xix_i had odd length, its last quote would either end the string inside xix_i or pair with the static quote after the hole, and in both cases the string would not end at that static quote. Let hole ii be unquoted. By claim 3 the non-blank characters of xix_i are all in one literal token bjb_j, and by (c) bjb_j starts and ends at characters with origin hih_i, so bjb_j is inside xix_i. A literal token is a number or a complete string, and the rest of xix_i is blanks.

If. The lexer reads qq and q0q_0 the same way up to the first hole. At a quoted hole it is inside the string in both texts; in qq it reads the even quote runs of xix_i as pairs, so the string does not end inside xix_i and continues over the same static text as in q0q_0. At an unquoted hole the character before the hole ends the token before it in both texts, since a blank or an operator is not continued by a digit or a quote; xix_i gives exactly one literal token; and the character after the hole starts a new token, since a blank or an operator does not continue a number or a closed string. So the token lists agree in kind, in non-literal text and in the origins of their ends, and the parser, which looks only at kinds and non-literal texts, builds trees of the same shape. □\square

Cost. Let n=∣q∣+∣q0∣n = |q| + |q_0|. The lexer reads each character once, with O(1)O(1) work for each, since the operators have at most two characters. The grammar is LL(1), so the recursive descent parser consumes one token per step with no backtracking, in O(n)O(n) time. Line L4 looks at each position of q0q_0 once, because the tokens are disjoint. SHAPE and the loop of line L8 visit each node and leaf once. So VALIDATE runs in Θ(n)\Theta(n) time and O(n)O(n) space on the word-RAM. ■\blacksquare

Complexity

  • Time. The lexer reads each character once. The toy grammar is LL(1), so the recursive descent parser reads each token once with no backtracking. Line L4 looks at each character of q0q_0 once, and SHAPE and the loop of line L8 visit each node once. So the time is Θ(n)\Theta(n) on every query, where nn counts the characters of qq and q0q_0.
  • Space. The two trees and the origins take O(n)O(n) space.
  • For a larger grammar. With an LR parser for an LR(1) grammar the time stays linear in the length of the query. With a general parser such as the Earley parser, it can grow to cubic time for an ambiguous grammar.

Properties

  • Sound for the grammar. An accepted query has the planned structure under the grammar of the validator. The guarantee holds for the database only if its parser agrees with this grammar.
  • Complete for confined inputs. Every input that stays inside its literal is accepted, whatever characters it holds. A name such as O'Brien is accepted once its quote is doubled, so the check does not block benign data.
  • No program analysis. The validator needs only the template and the input boundaries, not the source code of the program.
  • Online. Each query is checked when it runs, so stored data that comes back into a later query is checked then, if it is marked as an input.

Variants and improvements

  • Syntactic confinement. Su and Wassermann allow an input to be a complete subtree of a chosen kind, not only a literal, and check it with a grammar extended by markers around each input. Their checker is called SQLCheck.
  • A model of the intended queries. Instead of the template at run time, a static analysis of the program can compute the set of queries each call site can build and check each query against that set.
  • Taint tracking. Taint analysis marks the characters that come from inputs, which gives the origins of line L1 without help from the programmer.
  • Other languages. The same check works for any language with a grammar, for example a shell command, an LDAP filter or an XPath query, and the same idea underlies context-sensitive auto-escaping for HTML, which prevents the change instead of detecting it.

When to use it

Use prepared statements first: the database receives the query and the values apart, so no value can be parsed as code, and there is nothing to check. Parse-tree validation is useful where the query must be built as text, for example in old code that cannot be changed, or in a proxy in front of the database, and as a second line of defense. It does not help when the programmer puts an input where a name or a keyword goes (line L4 rejects such a template); there, the program must pick the name from an allow list.

Pitfalls

  • Checking only that the query parses. Lines L5 and L6 alone accept a query whose input changed its structure into another valid one. Line L7 compares the shapes, and lines L8 and L9 compare the token boundaries; both are needed.
  • No boundary check. Without lines L8 and L9, a quote at the end of an input can make its literal run over the static text up to the next quote, and the shapes can still agree if a later input supplies the missing tokens. Line L9 rejects, since the literal no longer ends on the static quote of the template.
  • A grammar that differs from the database. If the database reads a backslash as an escape inside strings and PARSE in lines L3 and L5 does not, the two parsers see different trees. The test of the page shows that, in this dialect, a backslash before a quote does not keep the quote inside the string. PARSE must use the dialect of the database.
  • A placeholder in the wrong place. A placeholder for a column name or a sort order is not a literal, and line L4 reports a template error. Weakening line L4 to accept a name there lets an input choose any column.

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.

parse_tree_query_validation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parse-tree-query-validation/. The authors are listed in prov/VTPNC3.jsonl.

"""Parse-tree validation of queries built from a template and inputs.

A query template is a list of static parts p0, p1, ..., pk written by the
programmer. The query is p0 x1 p1 x2 ... xk pk, where x1, ..., xk are inputs.
validate parses the query twice: once with each input replaced by the
placeholder "1", which gives the intended tree, and once with the real
inputs. It accepts only when the two concrete parse trees have the same
shape and every token starts and ends at the same place, so that each input
stays inside the one literal that holds its placeholder. This is the method
of Buehrer, Weide and Sivilotti (2005), on a toy subset of SQL:

  query   := SELECT cols FROM ident [WHERE cond]
  cols    := '*' | ident (',' ident)*
  cond    := term (OR term)*
  term    := factor (AND factor)*
  factor  := NOT factor | '(' cond ')' | operand cmp operand
  operand := ident | number | string
  cmp     := '=' | '<>' | '<' | '<=' | '>' | '>='

Strings are in single quotes, with '' for a quote inside. A backslash is an
ordinary character. Keywords are not case sensitive.
"""

from typing import NamedTuple, Union

PLACEHOLDER = "1"
KEYWORDS = frozenset({"SELECT", "FROM", "WHERE", "AND", "OR", "NOT"})
OPERATORS = ("<=", ">=", "<>", "=", "<", ">", ",", "(", ")", "*")
COMPARISONS = frozenset({"=", "<>", "<", "<=", ">", ">="})
SPACE = frozenset(" \t\n")
LITERALS = frozenset({"num", "str"})


class QueryError(ValueError):
    """The text is not a query of the toy language."""


class TemplateError(ValueError):
    """The template itself is bad: with placeholders it does not parse, or a
    placeholder is not inside one literal."""


class Token(NamedTuple):
    kind: str  # "kw", "ident", "num", "str" or "op"
    text: str
    start: int
    end: int


Tree = tuple  # (label, child, child, ...) with Token leaves


def lex(q: str) -> list[Token]:
    """Split q into tokens, longest match first. Cost: O(len(q))."""
    toks: list[Token] = []
    i, n = 0, len(q)
    while i < n:
        ch = q[i]
        if ch in SPACE:
            i += 1
        elif ch.isascii() and (ch.isalpha() or ch == "_"):
            j = i + 1
            while j < n and q[j].isascii() and (q[j].isalnum() or q[j] == "_"):
                j += 1
            word = q[i:j]
            if word.upper() in KEYWORDS:
                toks.append(Token("kw", word.upper(), i, j))
            else:
                toks.append(Token("ident", word, i, j))
            i = j
        elif ch.isascii() and ch.isdigit():
            j = i + 1
            while j < n and q[j].isascii() and q[j].isdigit():
                j += 1
            toks.append(Token("num", q[i:j], i, j))
            i = j
        elif ch == "'":
            j = i + 1
            while True:
                if j >= n:
                    raise QueryError("a string literal does not end")
                if q[j] == "'":
                    if j + 1 < n and q[j + 1] == "'":
                        j += 2
                        continue
                    break
                j += 1
            toks.append(Token("str", q[i : j + 1], i, j + 1))
            i = j + 1
        else:
            for op in OPERATORS:
                if q.startswith(op, i):
                    toks.append(Token("op", op, i, i + len(op)))
                    i += len(op)
                    break
            else:
                raise QueryError(f"no token starts with {ch!r}")
    return toks


class _Parser:
    """Recursive descent over a token list. The grammar is LL(1)."""

    def __init__(self, toks: list[Token]) -> None:
        self.toks = toks
        self.k = 0

    def _peek(self, kind: str, text: Union[str, None] = None) -> bool:
        if self.k >= len(self.toks):
            return False
        t = self.toks[self.k]
        return t.kind == kind and (text is None or t.text == text)

    def _take(self, kind: str, text: Union[str, None] = None) -> Token:
        if not self._peek(kind, text):
            raise QueryError(f"expected {text or kind} at token {self.k}")
        self.k += 1
        return self.toks[self.k - 1]

    def query(self) -> Tree:
        children: list = [self._take("kw", "SELECT"), self._cols(), self._take("kw", "FROM"), self._take("ident")]
        if self._peek("kw", "WHERE"):
            children.append(("where", self._take("kw", "WHERE"), self._cond()))
        if self.k != len(self.toks):
            raise QueryError(f"text after the end of the query at token {self.k}")
        return ("query", *children)

    def _cols(self) -> Tree:
        if self._peek("op", "*"):
            return ("cols", self._take("op", "*"))
        items: list = [self._take("ident")]
        while self._peek("op", ","):
            items += [self._take("op", ","), self._take("ident")]
        return ("cols", *items)

    def _cond(self) -> Tree:
        node = self._term()
        while self._peek("kw", "OR"):
            node = ("or", node, self._take("kw", "OR"), self._term())
        return node

    def _term(self) -> Tree:
        node = self._factor()
        while self._peek("kw", "AND"):
            node = ("and", node, self._take("kw", "AND"), self._factor())
        return node

    def _factor(self) -> Tree:
        if self._peek("kw", "NOT"):
            return ("not", self._take("kw", "NOT"), self._factor())
        if self._peek("op", "("):
            return ("paren", self._take("op", "("), self._cond(), self._take("op", ")"))
        left = self._operand()
        if self.k >= len(self.toks) or self.toks[self.k].text not in COMPARISONS:
            raise QueryError(f"expected a comparison at token {self.k}")
        op = self._take("op")
        return ("cmp", left, op, self._operand())

    def _operand(self) -> Token:
        for kind in ("ident", "num", "str"):
            if self._peek(kind):
                return self._take(kind)
        raise QueryError(f"expected an operand at token {self.k}")


def parse(q: str) -> Tree:
    """The concrete parse tree of q; raises QueryError. Cost: O(len(q))."""
    return _Parser(lex(q)).query()


def leaves(tree: Tree) -> list[Token]:
    """The tokens of a parse tree, left to right."""
    out: list[Token] = []
    stack: list = [tree]
    while stack:
        node = stack.pop()
        if isinstance(node, Token):
            out.append(node)
        else:
            stack.extend(reversed(node[1:]))
    return out


def shape(tree: Union[Tree, Token]) -> tuple:
    """The tree with the text of each literal erased, and its kind too."""
    if isinstance(tree, Token):
        return ("lit",) if tree.kind in LITERALS else (tree.kind, tree.text)
    return (tree[0],) + tuple(shape(child) for child in tree[1:])


def fill(parts: list[str], inputs: list[str]) -> tuple[str, list[tuple[str, int]]]:
    """The text p0 x1 p1 ... xk pk and the origin of each character:
    ("s", j) for the j-th static character, ("h", i) for a character of input i."""
    if len(parts) != len(inputs) + 1:
        raise ValueError("a template with k holes has k + 1 parts")
    text: list[str] = []
    origin: list[tuple[str, int]] = []
    j = 0
    for i, part in enumerate(parts):
        text.append(part)
        origin.extend(("s", j + d) for d in range(len(part)))
        j += len(part)
        if i < len(inputs):
            text.append(inputs[i])
            origin.extend(("h", i) for _ in inputs[i])
    return "".join(text), origin


def validate(parts: list[str], inputs: list[str]) -> Union[Tree, None]:
    """VALIDATE of the page. Returns the parse tree of the query when the
    inputs keep the intended structure, None when it rejects the query, and
    raises TemplateError when the template itself is bad.

    Precondition: parts are static text from the programmer, inputs are any
    strings. Cost: O(n) time and space for a query of n characters.
    """
    q, origin = fill(parts, inputs)  # @line L1
    q0, origin0 = fill(parts, [PLACEHOLDER] * len(inputs))  # @line L2
    try:
        a = parse(q0)  # @line L3
    except QueryError as e:
        raise TemplateError(f"the template does not parse: {e}") from None  # @line L4
    la = leaves(a)
    touching = [0] * len(inputs)  # the number of tokens that meet each placeholder
    for t in la:
        for i in {origin0[p][1] for p in range(t.start, t.end) if origin0[p][0] == "h"}:
            touching[i] += 1
            if t.kind not in LITERALS:
                touching[i] = 2
    if any(c != 1 for c in touching):
        raise TemplateError("a placeholder is not inside one literal")  # @line L4
    try:
        b = parse(q)  # @line L5
    except QueryError:
        return None  # @line L6
    if shape(a) != shape(b):  # @line L7
        return None
    for ta, tb in zip(la, leaves(b)):  # @line L8
        if origin[tb.start] != origin0[ta.start] or origin[tb.end - 1] != origin0[ta.end - 1]:  # @line L9
            return None
    return b  # @line L10


def string_value(tok: Token) -> str:
    """The value of a string literal token."""
    return tok.text[1:-1].replace("''", "'")
test_parse_tree_query_validation.py 160 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/parse-tree-query-validation/. The authors are listed in prov/VTPNC3.jsonl.

import random
import re

import pytest

from parse_tree_query_validation import (
    QueryError,
    TemplateError,
    fill,
    leaves,
    lex,
    parse,
    shape,
    string_value,
    validate,
)

# Templates written by the programmer. A hole is quoted when its part ends in a quote.
TEMPLATES = [
    ["SELECT a FROM t WHERE name = '", "'"],
    ["SELECT a, b FROM t WHERE id = ", ""],
    ["SELECT * FROM t WHERE (name = '", "' OR id > ", ") AND NOT b < '", "'"],
    ["SELECT a FROM t WHERE id = ", " AND name <> '", "'"],
    ["SELECT a FROM t WHERE (id = ", ")"],
    ["select a from t where ", " = b"],
]

# The independent oracle: an input is confined to its literal exactly when it
# matches the language of the inside of a string (quoted hole), or of one
# literal with blanks around it (unquoted hole).
QUOTED_OK = re.compile(r"(?:[^']|'')*")
UNQUOTED_OK = re.compile(r"[ \t\n]*(?:[0-9]+|'(?:[^']|'')*')[ \t\n]*")

# Benign characters only: letters that cannot form a keyword, digits, blanks,
# quotes, a backslash, an ampersand and angle brackets.
ALPHABET = "ab12 '\\&<>"


def quoted(parts: list, i: int) -> bool:
    return parts[i].endswith("'")


def oracle(parts: list, inputs: list) -> bool:
    return all(
        (QUOTED_OK if quoted(parts, i) else UNQUOTED_OK).fullmatch(x) is not None for i, x in enumerate(inputs)
    )


def placeholder_literals(parts: list, inputs: list, tree: tuple) -> list:
    """The literal token of the accepted tree that holds each input."""
    q, origin = fill(parts, inputs)
    out = []
    for i in range(len(inputs)):
        open_quote = ("s", sum(map(len, parts[: i + 1])) - 1)  # the static quote before a quoted hole
        for t in leaves(tree):
            if quoted(parts, i):
                inside = origin[t.start] == open_quote
            else:
                inside = any(origin[p] == ("h", i) for p in range(t.start, t.end))
            if inside:
                out.append(t)
                break
    return out


def test_page_example() -> None:
    parts = ["SELECT a FROM t WHERE name = '", "' AND id = ", ""]
    tree = validate(parts, ["O''Brien", "42"])
    assert tree is not None
    toks = leaves(tree)
    assert [t.text for t in toks] == ["SELECT", "a", "FROM", "t", "WHERE", "name", "=", "'O''Brien'", "AND", "id", "=", "42"]
    assert string_value(toks[7]) == "O'Brien"
    assert validate(parts, ["O'Brien", "42"]) is None  # the quote was not doubled: the string ends early
    assert validate(parts, ["O''Brien", "4 2"]) is None  # two tokens where one literal was planned
    assert validate(parts, ["O''Brien", "id"]) is None  # an identifier is not a literal
    assert validate(parts, ["O''Brien", " 42 "]) is not None
    assert validate(parts, ["O''Brien", "'42'"]) is not None  # a string literal is a literal too


def test_lexer_and_parser() -> None:
    assert [t.kind for t in lex("a<=b <> 'x''y' 12")] == ["ident", "op", "ident", "op", "str", "num"]
    with pytest.raises(QueryError):  # outside a string a backslash is no token
        lex("a \\ b")
    with pytest.raises(QueryError):
        lex("'abc")
    with pytest.raises(QueryError):
        parse("SELECT a FROM t WHERE a = 1 b")
    with pytest.raises(QueryError):
        parse("SELECT a FROM t WHERE a = 1 = 2")
    tree = parse("SELECT a FROM t WHERE NOT (a = 1 OR b = 'x') AND c > 2")
    assert shape(tree)[5][2][0] == "and"  # AND binds tighter than OR, and NOT tighter than AND
    assert len(leaves(tree)) == 19


@pytest.mark.parametrize(
    "parts",
    [
        ["SELECT ", " FROM t"],  # a placeholder where a column name goes
        ["SELECT a FROM t WHERE ab", " = 1"],  # the placeholder joins an identifier
        ["SELECT a FROM t WHERE name = '", ""],  # the string does not end
        ["SELECT a FROM t WHERE a = ", " ", ""],  # two numbers in a row
    ],
)
def test_bad_templates(parts: list) -> None:
    with pytest.raises(TemplateError):
        validate(parts, ["x"] * (len(parts) - 1))


def test_backslash_is_ordinary() -> None:
    parts = ["SELECT a FROM t WHERE name = '", "'"]
    tree = validate(parts, ["a\\b"])
    assert tree is not None and string_value(leaves(tree)[7]) == "a\\b"
    assert validate(parts, ["a\\'"]) is None  # in this dialect a backslash does not protect a quote


def test_random_inputs_against_oracle() -> None:
    rng = random.Random(20050311)
    accepted = rejected = 0
    for _ in range(3000):
        parts = rng.choice(TEMPLATES)
        inputs = []
        for i in range(len(parts) - 1):
            r = rng.random()
            if r < 0.3:
                x = rng.choice(["O''Brien", "42", " 7 ", "''", "", "'ab'", "a''b''", "x&y", "<b>"])
            else:
                x = "".join(rng.choice(ALPHABET) for _ in range(rng.randrange(7)))
            inputs.append(x)
        tree = validate(parts, inputs)
        assert (tree is not None) == oracle(parts, inputs), (parts, inputs)
        if tree is None:
            rejected += 1
            continue
        accepted += 1
        # The accepted tree has the planned shape, and each input is the
        # content of one literal: no character of an input became code.
        q0, _ = fill(parts, ["1"] * len(inputs))
        assert shape(tree) == shape(parse(q0))
        lits = placeholder_literals(parts, inputs, tree)
        assert len(lits) == len(inputs)
        for i, (x, t) in enumerate(zip(inputs, lits)):
            if quoted(parts, i):
                assert t.kind == "str" and string_value(t) == x.replace("''", "'")
            else:
                assert t.kind in ("num", "str") and t.text == x.strip(" \t\n")
    assert accepted > 500 and rejected > 500


def test_parse_only_is_not_enough() -> None:
    """A check that the query parses accepts inputs that move token boundaries."""
    parts = ["SELECT a FROM t WHERE id <", ""]
    # The input "=2" joins the static "<" into the operator "<=": the query
    # parses, but the input is no longer inside a literal.
    q, _ = fill(parts, ["=2"])
    parse(q)
    assert validate(parts, ["=2"]) is None
    assert validate(parts, ["2"]) is not None

History

Buehrer, Weide and Sivilotti presented parse tree validation at the SEM workshop in 2005, with a Java tool named SQLGuard that compares the tree of the query with and without the input. Su and Wassermann (POPL 2006) defined a command injection as an input that is not syntactically confined, proved that their checker SQLCheck, based on an augmented grammar, finds exactly these inputs, and measured it on real applications. Halfond, Viegas and Orso (2006) classified the attacks and the countermeasures and placed parse tree validation among the run-time techniques.

References

  1. Gregory Buehrer, Bruce W. Weide and Paolo A. G. Sivilotti, Using parse tree validation to prevent SQL injection attacks, 5th International Workshop on Software Engineering and Middleware (SEM 2005), pages 106 to 113, doi:10.1145/1108473.1108496, the comparison of the parse tree of the intended query with the parse tree of the query with the input, and the tool SQLGuard
  2. Zhendong Su and Gary Wassermann, The essence of command injection attacks in web applications, POPL 2006, pages 372 to 382, the definition of a command injection as input that is not syntactically confined, and the checker SQLCheck that parses with an augmented grammar
  3. William G. J. Halfond, Jeremy Viegas and Alessandro Orso, A classification of SQL injection attacks and countermeasures, International Symposium on Secure Software Engineering 2006, the section on prevention techniques, where parse tree validation is compared with the other countermeasures

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/VTPNC3/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