Algorithm Search⌘K

Data structureadvanced

Code property graph

Also called CPG.

Merges the syntax tree, control flow graph and program dependence graph into one graph, queried by graph traversals to find vulnerable patterns.

A code property graph is one directed graph that holds three views of a program over a shared set of nodes: the abstract syntax tree, the control flow graph and the program dependence graph. Nodes and edges carry key-value properties, such as the type of a node, the name of a variable or the outcome of a branch, and every edge has a label that says which view it belongs to. A statement is one node, so a single traversal can move from the syntax of a call to the definitions that its arguments depend on and to the conditions that guard it. A pattern of a vulnerability, such as "a length from the input reaches a copy without a check", becomes a graph query. Yamaguchi, Golde, Arp and Rieck introduced the structure in 2014 for the analysis of C code.

In plain words

A compiler sees a program in several ways. The syntax tree shows how the code is written. The flow graph shows the order in which statements can run. The dependence graph shows which value comes from which assignment, and which condition decides whether a statement runs.

Each view answers different questions, and many security bugs need all three. A code property graph puts them on top of each other. Each statement is one dot, and arrows of three colours connect the dots.

A search can then follow arrows of any colour. For example: start at each call of a copy function, follow the data arrows back to see if the length comes from the input, and follow the control arrows back to see if some condition checks it. Calls with an input length and no check are shown to a person.

The abstract type

A property graph stores nodes and labelled, directed edges, each with a dictionary of properties. It supports:

  • ADD-NODE(props) returns a new node;
  • ADD-EDGE(u, v, label, props) adds an edge;
  • OUT(u, label) and IN(v, label) return the heads of the edges with this label out of uu, or the tails of those into vv, with their properties;
  • FIND(props) returns the nodes whose properties match.

A code property graph is a property graph built from a program with four labels: AST from a syntax node to its children; CFG between statement and predicate nodes, with cond true, false or none; REACHES from a definition of xx to a use of xx that it reaches, with var xx (data dependence); and CONTROLS from a predicate to the nodes whose execution it decides, with the outcome (control dependence). Queries are traversals: sequences of steps along edges of given labels with filters on properties.

Representation

The implementation keeps a list of node property dictionaries, a list of edges (tail, head, label, properties), and for each node two dictionaries that map a label to the list of the numbers of its outgoing and incoming edges. The invariant is that each edge appears exactly once in the outgoing list of its tail for its label, once in the incoming list of its head for its label, and nowhere else, in insertion order. Real systems store the same model in a graph database and add indexes on properties, so that FIND does not scan all nodes.

Operations

The main block holds the graph operations, the construction and the query. The toy language has assignments, call statements, if and while; the CFG nodes are ENTRY, EXIT, the assignments, the calls and the predicates.

  1. ADD-NODE(G, props)
  2. 1i ← |V|, V[i] ← props, out[i] ← ∅, in[i] ← ∅, return i
  3. ADD-EDGE(G, u, v, ℓ, props)
  4. 2j ← |E|, E[j] ← (u, v, ℓ, props), append j to out[u][ℓ] and to in[v][ℓ], return j
  5. OUT(G, u, ℓ)
  6. 3return the heads and properties of the edges in out[u][ℓ] ▷ IN is symmetric
  7. BUILD(program)
  8. 4add a node for each syntax element and an AST edge from its parent, with its position
  9. 5link the statement and predicate nodes by CFG edges from ENTRY to EXIT, with cond true, false or none
  10. 6for each use of x at n and each definition d of x in the reaching definitions of n: add REACHES d → n, var x
  11. 7for each CFG edge a → s with cond c and each y that postdominates s but not strictly a: add CONTROLS a → y, cond c
  12. QUERY(G, source, sink)
  13. 8for each call statement s of the sink and each variable x of its last argument do
  14. 9T ← the tails of the REACHES edges into s with var x, closed backward under REACHES
  15. 10C ← the nodes from which CONTROLS edges lead to s
  16. 11if a node of T contains a call of the source and no predicate in C uses x then report (s, x)

Lines L1 to L3 cost O(1)O(1), plus the size of the result for OUT. Line L4 is one walk of the syntax tree. Line L5 is a recursive walk that returns the list of the pending exits of each block: an if returns the exits of both branches, and a while links the exits of its body back to its predicate and returns its false edge. Line L6 solves the reaching definitions equations by round-robin passes, and line L7 computes the postdominator sets by round-robin passes from the set of all nodes and applies the definition of Ferrante, Ottenstein and Warren. Lines L9 and L10 are backward depth-first searches restricted to one label.

Example

The program has five lines. It reads a number, derives a second one, copies with a checked length on line 4, and copies with the derived length on line 5.

1  n = input()
2  m = n + 4
3  if n < 64:
4      copy(buf, n)
5  copy(buf, m)
step operation state after the step
1 L4: syntax nodes 22 nodes (the function, ENTRY, EXIT and 19 syntax nodes), 19 AST edges
2 L5: control flow 7 CFG edges: ENTRY → 1 → 2 → 3, 3 → 4 (true), 3 → 5 (false), 4 → 5, 5 → EXIT
3 L6: data dependence 4 REACHES edges: 1 → 2, 1 → 3 and 1 → 4 with var n; 2 → 5 with var m
4 L7: control dependence 1 CONTROLS edge: 3 → 4 (true); line 5 runs on both branches, so it depends on no predicate
5 QUERY(input, copy) line 4: n comes from input, but predicate 3 uses n, so no report; line 5: m comes from line 2 and line 1, no predicate controls it, so report (5, m)

The rule is a heuristic, and the example shows its limits. A program with lines 1 and 2 and only copy(buf, m) inside "if m < 68" gives no report. If the if is removed and both copies run unguarded, both are reported. The tests of the implementation check these results and the counts in the table.

Correctness

The operations of the property graph keep the invariant, since ADD-EDGE appends the new, largest edge number to exactly the two lists that the invariant names, and OUT reads one of these lists. By structural induction on the program, every step of every execution is a CFG edge with the right outcome. The round-robin passes for reaching definitions start from empty sets and grow, and when they stop, a definition is in the set of a node exactly when a CFG path without another definition of the variable leads to it. The passes for postdominators start from full sets and shrink to the true postdominator sets, provided that EXIT is reachable from every node, which holds in this language. So the REACHES and CONTROLS edges are exactly the data and control dependences, and the query reports exactly the pairs of its rule. The full proof is in the proof file. The tests compare the edges with brute-force path searches and the CFG with executions on 500 random programs each, and the graph operations with a list model on 500 random sequences.

Proof: Correctness of the code property graphfull

We prove that the operations of the property graph (lines L1 to L3) keep its invariant and return the right edges, that BUILD (lines L4 to L7) makes exactly the AST, CFG, REACHES and CONTROLS edges that their definitions require, and that QUERY (lines L8 to L11) reports exactly the pairs of its rule. Programs are in the toy language of the page: assignments, call statements, if and while. A CFG node is ENTRY, EXIT, an assignment, a call statement or a predicate (the condition of an if or a while).

The property graph

Invariant (I). Every edge j=(u,v,ℓ,p)j = (u, v, \ell, p) appears exactly once in out[u][ℓ]\mathit{out}[u][\ell], exactly once in in[v][ℓ]\mathit{in}[v][\ell], and in no other list; each list is in increasing order of edge number.

Claim 1. ADD-NODE and ADD-EDGE keep (I), and OUT(u,ℓ)(u, \ell) returns the heads of the edges with label ℓ\ell out of uu, in the order of insertion; IN is symmetric.

Proof. The empty graph satisfies (I). ADD-NODE adds empty lists for the new node and no edge. ADD-EDGE checks that uu and vv exist, gives the new edge the number j=∣E∣j = |E|, larger than all others, and appends jj to the two lists that (I) names, so each list stays sorted, and no other list changes. OUT reads out[u][ℓ]\mathit{out}[u][\ell], which by (I) holds exactly the numbers of the edges with tail uu and label ℓ\ell, in increasing order, which is the order of insertion. □\square

Each of the three operations costs O(1)O(1) plus the size of the result, with dictionaries of labels of expected O(1)O(1) lookup.

The AST edges

Claim 2. The AST edges form a tree rooted at the function node that contains every syntax node, and the AST children of a node are in source order.

Proof. Every node except the function node, ENTRY and EXIT gets exactly one AST edge into it, when it is created, from a node created earlier (line L4 and the helper that creates statement nodes). So following the AST edge into a node backward always reaches older nodes and ends at the function node, which gives a tree. The children are created and linked in the order of the list of the parent, with the order property set to their index. □\square

The CFG edges

For a list of statements BB and a list PP of pending pairs (node, cond), BLOCK(B,P)(B, P) returns a list of exits. We show:

Claim 3. Let an execution of BB start right after a step from some pair (p,c)(p, c) of PP, that is, the node pp ran and, if it is a predicate, had outcome cc. Then each step of the execution, from the pair (p,c)(p, c) to the first node of BB and between consecutive nodes, is a CFG edge with the outcome of the earlier node as its cond. If the execution of BB ends, its last step is a pair of the returned list; if BB is empty, the returned list is PP.

Proof. By induction on the structure of BB. For an empty list, BLOCK returns PP, and there are no steps. For a list s;B′s; B', it suffices to show the claim for one statement ss and then apply the induction hypothesis to B′B' with the exits of ss as the pending list.

  • Assignment or call. Line L5 adds an edge from each pending pair to the node nn of ss, so the first step is an edge. The node runs once, with no outcome, and the exit list is [(n,none)][(n, \text{none})].
  • If. Line L5 links the pending pairs to the predicate pp. The execution goes on with the then-block after (p,true)(p, \text{true}) or the else-block after (p,false)(p, \text{false}), and these are exactly the pending lists given to the two recursive calls, whose exits are concatenated. The induction hypothesis applies to each block.
  • While. Line L5 links the pending pairs to pp. After (p,true)(p, \text{true}) the body runs with pending list [(p,true)][(p, \text{true})]; by the hypothesis its steps are edges, and its exits are linked back to pp, so the step back to the predicate is an edge. After (p,false)(p, \text{false}) the loop ends, and the exit list is [(p,false)][(p, \text{false})]. □\square

BUILD calls BLOCK on the program with [(ENTRY,none)][(\text{ENTRY}, \text{none})] and links the exits to EXIT, so every execution, and every prefix of an infinite one, is a path of the CFG from ENTRY. Every predicate has one true and one false edge out, every other node except EXIT has one edge out with cond none, and EXIT is reachable from every CFG node, since a while predicate can always take its false edge.

The REACHES edges

A definition of xx at dd reaches a use at nn when there is a CFG path from dd to nn with at least one edge whose inner nodes do not define xx. Line L6 adds an edge d→nd \to n with var xx for each d∈IN(n)d \in \mathrm{IN}(n) that defines xx, where IN and OUT are the result of the round-robin passes for

IN(n)=⋃p→nOUT(p),OUT(n)={d∈IN(n):d defines no variable that n defines}∪gen(n),\mathrm{IN}(n) = \bigcup_{p \to n} \mathrm{OUT}(p), \qquad \mathrm{OUT}(n) = \{ d \in \mathrm{IN}(n) : d \text{ defines no variable that } n \text{ defines} \} \cup \mathrm{gen}(n),

with gen(n)={n}\mathrm{gen}(n) = \{n\} if nn defines a variable and ∅\emptyset otherwise. Each node defines at most one variable.

Claim 4. When the passes stop, d∈IN(n)d \in \mathrm{IN}(n) if and only if dd is a definition that reaches nn for the variable it defines.

Proof. The sets start empty and the right-hand sides are monotone in the sets, so every value computed is a subset of the value of the next pass, and the passes stop because the sets are bounded by the set of CFG nodes. When they stop, the equations hold.

If d∈IN(n)d \in \mathrm{IN}(n), dd reaches nn. By induction on the number of the update. An element enters IN(n)\mathrm{IN}(n) because it is in OUT(p)\mathrm{OUT}(p) for an edge p→np \to n. If d=pd = p, the path is the edge d→nd \to n. Otherwise d∈IN(p)d \in \mathrm{IN}(p) from an earlier update, so by induction a path from dd to pp exists whose inner nodes do not define xx, and pp does not define xx either, since dd survived the kill at pp. Appending the edge p→np \to n gives a path to nn.

If dd reaches nn, d∈IN(n)d \in \mathrm{IN}(n). By induction on the length of a path d=v0,v1,…,vk=nd = v_0, v_1, \ldots, v_k = n whose inner nodes do not define xx. For k=1k = 1, d∈gen(d)⊆OUT(d)⊆IN(n)d \in \mathrm{gen}(d) \subseteq \mathrm{OUT}(d) \subseteq \mathrm{IN}(n) by the equations. For k>1k > 1, by induction d∈IN(vk−1)d \in \mathrm{IN}(v_{k-1}); the node vk−1v_{k-1} does not define xx, so d∈OUT(vk−1)⊆IN(n)d \in \mathrm{OUT}(v_{k-1}) \subseteq \mathrm{IN}(n). □\square

So the REACHES edges into nn with var xx are exactly the definitions of xx that reach a use of xx at nn: the data dependence edges of the program dependence graph.

The CONTROLS edges

A node yy postdominates nn if every CFG path from nn to EXIT contains yy; every node postdominates itself. Following Ferrante, Ottenstein and Warren, yy is control dependent on aa through an edge a→sa \to s with cond cc if yy postdominates ss and yy does not strictly postdominate aa. Line L7 adds the edge a→ya \to y with cond cc for exactly the yy in pdom(s)∖(pdom(a)∖{a})\mathrm{pdom}(s) \setminus (\mathrm{pdom}(a) \setminus \{a\}), without duplicates.

Claim 5. When the passes for pdom stop, pdom(n)\mathrm{pdom}(n) is the set of postdominators of nn, for every CFG node nn. Hence the CONTROLS edges are exactly the control dependences.

Proof. Let D(n)D(n) be the true set of postdominators. It satisfies D(EXIT)={EXIT}D(\text{EXIT}) = \{\text{EXIT}\} and D(n)={n}∪⋂n→sD(s)D(n) = \{n\} \cup \bigcap_{n \to s} D(s) for n≠EXITn \ne \text{EXIT}, since a path from nn to EXIT is nn followed by a path from some successor, and every node except EXIT has a successor.

The computed sets contain DD. They start as the set of all nodes, except at EXIT, which contains DD. The update is monotone, so if every set contains DD before an update, the new set contains {n}∪⋂D(s)=D(n)\{n\} \cup \bigcap D(s) = D(n).

The computed sets are contained in DD. When the passes stop, the equations hold for the computed sets. Let y∈pdom(n)y \in \mathrm{pdom}(n) and let n=v0,…,vk=EXITn = v_0, \ldots, v_k = \text{EXIT} be a path. If y≠v0y \ne v_0, then y∈pdom(v1)y \in \mathrm{pdom}(v_1) by the equation at v0v_0; repeating, either y=viy = v_i for some i<ki < k, or y∈pdom(EXIT)={EXIT}y \in \mathrm{pdom}(\text{EXIT}) = \{\text{EXIT}\}. Either way yy is on the path.

The passes stop, since each set only shrinks. The second statement follows because line L7 applies the definition to these sets. □\square

The query

Claim 6. QUERY reports (s,x)(s, x) exactly when ss is a call of the sink, xx is a variable of its last argument, some statement that contains a call of the source reaches ss through a chain of REACHES edges whose last edge has var xx, and no predicate from which a chain of CONTROLS edges leads to ss uses xx.

Proof. Line L8 enumerates the sink calls by their properties and the variables of the last AST child by Claim 2. Line L9 takes the tails of the REACHES edges into ss with var xx and closes them backward under REACHES; this is the set of the statements that begin such a chain. Line L10 closes {s}\{s\} backward under CONTROLS. A depth-first closure returns exactly the nodes with a path to its start set. Line L11 tests the two conditions. □\square

The rule itself is a heuristic. A check of a variable may not bound it, the bound may be wrong, and a value may be sanitized by a function call that the rule does not know, so the reports have both false positives and false negatives. Claims 4 and 5 are exact only for the toy language, which has no pointers, arrays or calls with effects; for C, the dependence edges come from an approximate analysis.

Complexity

For a program with NN syntax nodes and ss CFG nodes, and a graph with VV nodes and EE edges:

operation worst-case time
ADD-NODE, ADD-EDGE O(1)O(1)
OUT, IN O(1+the number of edges returned)O(1 + \text{the number of edges returned})
FIND by scanning O(V)O(V)
BUILD O(N+s4)O(N + s^4): each round-robin pass costs O(s2)O(s^2), and each pass but the last changes one of at most s2s^2 set entries
QUERY, per sink and variable O(V+E)O(V + E)

The space is O(V+E)O(V + E), with E=O(N+s2)E = O(N + s^2), because there are at most s2s^2 dependence edges of each kind. The bound for BUILD is loose: with a good order of the nodes, round-robin passes for these problems usually stop after a few passes. On real code the dependence analysis, not the graph, dominates the cost, and a database index makes FIND logarithmic or constant.

Variants

  • Interprocedural graphs. Add call graph edges from a call to the function it calls and from parameters to arguments, so that traversals can cross function boundaries, as in a system dependence graph. Later versions of the idea did this for taint-style vulnerabilities.
  • Other languages and binaries. The same schema works for Java, JavaScript or lifted binary code, with a language-specific front end. The open-source tool Joern grew from the original C implementation.
  • Queries in Datalog. Store the edges as relations and write the patterns as Datalog rules; reachability then becomes a recursive rule.
  • Learned patterns. Use the graph as the input of a learner that ranks functions or infers the sanitizer checks of a code base, instead of writing every query by hand.
  • Interval facts as properties. Attach the results of an analysis, such as the ranges of buffer overrun detection by range analysis, as properties of the nodes and filter on them in the query.

When to use it

Use a code property graph when an analyst wants to search a large code base for a known shape of bug, written once as a query, and then read the matches. It suits patterns that mix syntax, data flow and guards: unchecked lengths, missing permission checks before an operation, or values from a source that reach a sink, as in taint analysis. For a single question, such as "where is this variable defined", a plain dependence analysis is cheaper. When the goal is a proof that no bug of a class exists, use a sound analysis instead; the queries are search tools.

Pitfalls

  • Treating matches as bugs. A query is a heuristic. A check of the right variable may still be wrong, and a sanitizer function may not look like a check. Every match needs review, and the rate of true matches is a measurement on a given code base.
  • Missing flows. Dependence edges built without alias and pointer analysis miss flows through memory, so a query can stay silent on a real bug. State the precision of the analysis with the results.
  • Query cost. Unrestricted backward closures over all labels can visit the whole graph. Restrict each step to the labels it needs, and use property indexes for the start nodes.
  • Stale graphs. The graph is a snapshot of one version of the code. Rebuild it, or update it per file, before running queries on new code.

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.

code_property_graph.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/code-property-graph/. The authors are listed in prov/MM07HE.jsonl.
"""A code property graph for a toy structured language, and a taint-style query on it.

A property graph has nodes and directed, labelled edges, and both carry a
dictionary of properties. The code property graph puts three views of one
program into one such graph over a shared set of nodes:

* AST edges from each syntax node to its children, in order;
* CFG edges between statement and predicate nodes, with cond = True, False or None;
* REACHES edges (data dependence, with var = x) from a definition of x to a
  use of x that it reaches, and CONTROLS edges (control dependence, with the
  cond of the branch) from a predicate to the statements whose execution it
  decides.

The toy language has statements ("assign", x, e), ("call", f, [e, ...]),
("if", e, then, else) and ("while", e, body), and expressions ("var", x),
("const", c), ("call", f, [e, ...]) and ("op", o, [e, ...]). The query reports
calls of a sink whose last argument depends on a call of a source, with no
controlling predicate that tests the same variable. That rule is a heuristic:
it has false positives and false negatives, like the queries of the paper.
"""

from dataclasses import dataclass
from typing import Any, Iterable, Optional

AST, CFG, REACHES, CONTROLS = "AST", "CFG", "REACHES", "CONTROLS"


class PropertyGraph:
    """Nodes and labelled edges with properties, and adjacency lists per label in both directions.

    Invariant: edge j = (u, v, label, props) is listed once in out[u][label]
    and once in inn[v][label], and nowhere else. Every operation costs O(1),
    or O(1 + the size of the result).
    """

    def __init__(self) -> None:
        self.props: list[dict[str, Any]] = []
        self.edges: list[tuple[int, int, str, dict[str, Any]]] = []
        self._out: list[dict[str, list[int]]] = []
        self._in: list[dict[str, list[int]]] = []

    def add_node(self, **props: Any) -> int:
        """Add a node with the given properties and return its identifier."""
        self.props.append(dict(props))  # @line L1
        self._out.append({})
        self._in.append({})
        return len(self.props) - 1

    def add_edge(self, u: int, v: int, label: str, **props: Any) -> int:
        """Add the edge u -> v with a label and properties; u and v must exist."""
        if not (0 <= u < len(self.props) and 0 <= v < len(self.props)):
            raise IndexError("unknown node")
        j = len(self.edges)
        self.edges.append((u, v, label, dict(props)))  # @line L2
        self._out[u].setdefault(label, []).append(j)
        self._in[v].setdefault(label, []).append(j)
        return j

    def out_edges(self, u: int, label: str) -> list[tuple[int, dict[str, Any]]]:
        """The (head, properties) of the edges with this label out of u, in insertion order."""
        return [(self.edges[j][1], self.edges[j][3]) for j in self._out[u].get(label, [])]  # @line L3

    def in_edges(self, v: int, label: str) -> list[tuple[int, dict[str, Any]]]:
        """The (tail, properties) of the edges with this label into v, in insertion order."""
        return [(self.edges[j][0], self.edges[j][3]) for j in self._in[v].get(label, [])]

    def out(self, u: int, label: str) -> list[int]:
        return [v for v, _ in self.out_edges(u, label)]

    def inn(self, v: int, label: str) -> list[int]:
        return [u for u, _ in self.in_edges(v, label)]

    def find(self, **match: Any) -> list[int]:
        """The nodes whose properties include every given key and value. Cost O(|V|)."""
        return [i for i, p in enumerate(self.props) if all(p.get(k) == val for k, val in match.items())]

    def check_invariant(self) -> bool:
        seen = [0] * len(self.edges)
        for side, lists in ((0, self._out), (1, self._in)):
            for node, by_label in enumerate(lists):
                for label, js in by_label.items():
                    for j in js:
                        e = self.edges[j]
                        if e[side] != node or e[2] != label:
                            return False
                        seen[j] += 1
        return all(c == 2 for c in seen)


def closure(g: PropertyGraph, start: Iterable[int], label: str, backward: bool = True) -> set[int]:
    """Every node reachable from start along edges with this label, start included."""
    seen = set(start)
    stack = list(seen)
    while stack:
        n = stack.pop()
        for m in (g.inn(n, label) if backward else g.out(n, label)):
            if m not in seen:
                seen.add(m)
                stack.append(m)
    return seen


def expr_vars(e: tuple) -> set[str]:
    if e[0] == "var":
        return {e[1]}
    if e[0] == "const":
        return set()
    return set().union(*(expr_vars(a) for a in e[2]))


@dataclass
class CodePropertyGraph:
    graph: PropertyGraph
    entry: int
    exit: int
    cfg_nodes: list[int]


def build_cpg(program: list[tuple]) -> CodePropertyGraph:
    """Build the AST, CFG, REACHES and CONTROLS edges of a program over one node set.

    Statement and predicate nodes get a line number in source order. With s
    CFG nodes and N syntax nodes, the worst-case cost is O(N + s^4): each
    round-robin pass costs O(s^2), and each pass but the last changes one of
    the at most s^2 set entries. In practice a few passes suffice.
    """
    g = PropertyGraph()
    root = g.add_node(type="function")
    entry = g.add_node(type="entry", defs=(), uses=())
    exit_ = g.add_node(type="exit", defs=(), uses=())
    cfg_nodes = [entry]
    line = [0]

    def expr(e: tuple, parent: int, order: int) -> None:
        if e[0] == "var":
            n = g.add_node(type="var", name=e[1])
        elif e[0] == "const":
            n = g.add_node(type="const", value=e[1])
        elif e[0] == "call":
            n = g.add_node(type="callexpr", name=e[1])
        else:
            n = g.add_node(type="op", op=e[1])
        g.add_edge(parent, n, AST, order=order)  # @line L4
        for i, a in enumerate(e[2] if e[0] in ("call", "op") else ()):
            expr(a, n, i)

    def link(pending: list[tuple[int, Optional[bool]]], n: int) -> None:
        for p, cond in pending:
            g.add_edge(p, n, CFG, cond=cond)  # @line L5

    def cfg_node(parent: int, order: int, **props: Any) -> int:
        line[0] += 1
        n = g.add_node(line=line[0], **props)
        g.add_edge(parent, n, AST, order=order)
        cfg_nodes.append(n)
        return n

    def block(stmts: list[tuple], parent: int, pending: list) -> list:
        for i, s in enumerate(stmts):
            pending = stmt(s, parent, i, pending)
        return pending

    def stmt(s: tuple, parent: int, order: int, pending: list) -> list:
        if s[0] == "assign":
            n = cfg_node(parent, order, type="assign", name=s[1], defs=(s[1],), uses=tuple(sorted(expr_vars(s[2]))))
            expr(s[2], n, 0)
            link(pending, n)
            return [(n, None)]
        if s[0] == "call":
            n = cfg_node(parent, order, type="call", name=s[1], defs=(), uses=tuple(sorted(set().union(*map(expr_vars, s[2])))))
            for i, a in enumerate(s[2]):
                expr(a, n, i)
            link(pending, n)
            return [(n, None)]
        head = g.add_node(type=s[0])
        g.add_edge(parent, head, AST, order=order)
        p = cfg_node(head, 0, type="pred", defs=(), uses=tuple(sorted(expr_vars(s[1]))))
        expr(s[1], p, 0)
        link(pending, p)
        body = g.add_node(type="block")
        g.add_edge(head, body, AST, order=1)
        if s[0] == "if":
            other = g.add_node(type="block")
            g.add_edge(head, other, AST, order=2)
            return block(s[2], body, [(p, True)]) + block(s[3], other, [(p, False)])
        link(block(s[2], body, [(p, True)]), p)
        return [(p, False)]

    link(block(program, root, [(entry, None)]), exit_)
    cfg_nodes.append(exit_)
    succ = {n: g.out_edges(n, CFG) for n in cfg_nodes}
    pred = {n: g.inn(n, CFG) for n in cfg_nodes}
    defs = {n: g.props[n]["defs"] for n in cfg_nodes}

    # Reaching definitions: OUT(n) = (IN(n) minus the definitions of what n defines) plus n.
    rd_out: dict[int, frozenset] = {n: frozenset() for n in cfg_nodes}
    rd_in: dict[int, frozenset] = dict(rd_out)
    changed = True
    while changed:
        changed = False
        for n in cfg_nodes:
            i = frozenset().union(*(rd_out[p] for p in pred[n]))
            o = frozenset(d for d in i if defs[d][0] not in defs[n]) | (frozenset([n]) if defs[n] else frozenset())
            if i != rd_in[n] or o != rd_out[n]:
                rd_in[n], rd_out[n], changed = i, o, True
    for n in cfg_nodes:
        for x in g.props[n]["uses"]:
            for d in sorted(rd_in[n]):
                if defs[d] == (x,):
                    g.add_edge(d, n, REACHES, var=x)  # @line L6

    # Postdominators: pdom(exit) = {exit}, pdom(n) = {n} plus the meet over the successors.
    everything = frozenset(cfg_nodes)
    pdom = {n: everything for n in cfg_nodes}
    pdom[exit_] = frozenset([exit_])
    changed = True
    while changed:
        changed = False
        for n in reversed(cfg_nodes):
            if n == exit_:
                continue
            new = frozenset([n]) | frozenset.intersection(*(pdom[v] for v, _ in succ[n]))
            if new != pdom[n]:
                pdom[n], changed = new, True
    for a in cfg_nodes:
        done = set()
        for s, e in succ[a]:
            for y in sorted(pdom[s] - (pdom[a] - {a})):
                if (y, e["cond"]) not in done:
                    done.add((y, e["cond"]))
                    g.add_edge(a, y, CONTROLS, cond=e["cond"])  # @line L7
    return CodePropertyGraph(g, entry, exit_, cfg_nodes)


def ast_descendants(g: PropertyGraph, n: int) -> set[int]:
    return closure(g, [n], AST, backward=False)


def unchecked_flows(cpg: CodePropertyGraph, source: str, sink: str) -> list[tuple[int, str]]:
    """The (line, variable) pairs where the last argument of a sink call depends on a source call unchecked.

    A sink call s and a variable x of its last argument are reported when a
    chain of REACHES edges leads from a statement that calls the source to s
    through a definition of x, and no predicate that controls s, directly or
    through other predicates, uses x. Cost O(|V| + |E|) per pair.
    """
    g = cpg.graph
    found = []
    for s in g.find(type="call", name=sink):  # @line L8
        args = g.out(s, AST)
        if not args:
            continue
        for x in sorted({g.props[v]["name"] for v in ast_descendants(g, args[-1]) if g.props[v]["type"] == "var"}):
            start = [d for d, e in g.in_edges(s, REACHES) if e["var"] == x]
            tainted = closure(g, start, REACHES) if start else set()  # @line L9
            guards = closure(g, [s], CONTROLS) - {s}  # @line L10
            from_source = any(g.props[v]["type"] == "callexpr" and g.props[v]["name"] == source for t in tainted for v in ast_descendants(g, t))
            checked = any(x in g.props[c]["uses"] for c in guards)
            if from_source and not checked:  # @line L11
                found.append((g.props[s]["line"], x))
    return found
test_code_property_graph.py 272 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/code-property-graph/. The authors are listed in prov/MM07HE.jsonl.
import random

import pytest

from code_property_graph import AST, CFG, CONTROLS, REACHES, PropertyGraph, build_cpg, expr_vars, unchecked_flows

PAGE = [
    ("assign", "n", ("call", "input", [])),
    ("assign", "m", ("op", "+", [("var", "n"), ("const", 4)])),
    ("if", ("op", "<", [("var", "n"), ("const", 64)]), [("call", "copy", [("var", "buf"), ("var", "n")])], []),
    ("call", "copy", [("var", "buf"), ("var", "m")]),
]


def by_line(cpg):
    return {cpg.graph.props[n]["line"]: n for n in cpg.cfg_nodes if "line" in cpg.graph.props[n]}


def labelled(g, label):
    return {(u, v, tuple(sorted(p.items()))) for u, v, lab, p in g.edges if lab == label}


def test_page_example():
    cpg = build_cpg(PAGE)
    g, L = cpg.graph, by_line(cpg)
    assert unchecked_flows(cpg, "input", "copy") == [(5, "m")]
    counts = {lab: sum(1 for e in g.edges if e[2] == lab) for lab in (AST, CFG, REACHES, CONTROLS)}
    assert len(g.props) == 22 and counts == {AST: 19, CFG: 7, REACHES: 4, CONTROLS: 1}
    assert {(g.props[u].get("line"), g.props[v].get("line"), p["var"]) for u, v, _, p in g.edges if _ == REACHES} == {
        (1, 2, "n"), (1, 3, "n"), (1, 4, "n"), (2, 5, "m")}
    assert g.out_edges(L[3], CONTROLS) == [(L[4], {"cond": True})]
    # A check on m instead removes the report; a check on nothing adds one for line 4.
    fixed = PAGE[:2] + [("if", ("op", "<", [("var", "m"), ("const", 68)]), [PAGE[3]], [])]
    assert unchecked_flows(build_cpg(fixed), "input", "copy") == []
    unchecked = PAGE[:2] + [PAGE[2][2][0], PAGE[3]]
    assert unchecked_flows(build_cpg(unchecked), "input", "copy") == [(3, "n"), (4, "m")]
    assert g.check_invariant()


def test_graph_edge_cases():
    g = PropertyGraph()
    a = g.add_node(type="x")
    assert g.out(a, AST) == [] and g.inn(a, AST) == [] and g.find(type="x") == [a]
    with pytest.raises(IndexError):
        g.add_edge(a, 5, AST)
    g.add_edge(a, a, CFG, cond=None)
    g.add_edge(a, a, CFG, cond=True)
    assert g.out_edges(a, CFG) == [(a, {"cond": None}), (a, {"cond": True})]
    assert g.check_invariant()
    empty = build_cpg([])
    assert empty.graph.out(empty.entry, CFG) == [empty.exit]
    assert unchecked_flows(empty, "input", "copy") == []


def test_random_operations_against_a_list_model():
    rng = random.Random(51)
    for _ in range(500):
        g, nodes, model = PropertyGraph(), [], []
        for _ in range(rng.randint(1, 40)):
            if not nodes or rng.random() < 0.3:
                nodes.append(g.add_node(k=rng.randrange(3)))
            else:
                u, v, lab = rng.choice(nodes), rng.choice(nodes), rng.choice((AST, CFG))
                w = rng.randrange(5)
                g.add_edge(u, v, lab, w=w)
                model.append((u, v, lab, w))
        for n in nodes:
            for lab in (AST, CFG):
                assert g.out_edges(n, lab) == [(v, {"w": w}) for u, v, l2, w in model if u == n and l2 == lab]
                assert g.in_edges(n, lab) == [(u, {"w": w}) for u, v, l2, w in model if v == n and l2 == lab]
        for k in range(3):
            assert g.find(k=k) == [n for n in nodes if g.props[n]["k"] == k]
        assert g.check_invariant()


VARS = ("a", "b", "c")


def gen_expr(rng, depth):
    r = rng.random()
    if depth == 0 or r < 0.35:
        return ("var", rng.choice(VARS)) if rng.random() < 0.7 else ("const", rng.randrange(10))
    if r < 0.55:
        return ("call", "input", [])
    return ("op", rng.choice("+-<"), [gen_expr(rng, depth - 1), gen_expr(rng, depth - 1)])


def gen_block(rng, depth):
    out = []
    for _ in range(rng.randint(0, 3)):
        r = rng.random()
        if depth > 0 and r < 0.2:
            out.append(("if", gen_expr(rng, 1), gen_block(rng, depth - 1), gen_block(rng, depth - 1)))
        elif depth > 0 and r < 0.3:
            out.append(("while", gen_expr(rng, 1), gen_block(rng, depth - 1)))
        elif r < 0.75:
            out.append(("assign", rng.choice(VARS), gen_expr(rng, 2)))
        else:
            out.append(("call", "copy", [gen_expr(rng, 1) for _ in range(rng.randint(0, 2))]))
    return out


def lines_of(program):
    """The statements and predicates in source order, as (kind, statement)."""
    out = []

    def walk(stmts):
        for s in stmts:
            out.append(("pred" if s[0] in ("if", "while") else s[0], s))
            if s[0] == "if":
                walk(s[2])
                walk(s[3])
            elif s[0] == "while":
                walk(s[2])

    walk(program)
    return out


def calls_in(e):
    if e[0] in ("var", "const"):
        return set()
    own = {e[1]} if e[0] == "call" else set()
    return own.union(*(calls_in(a) for a in e[2]))


def evaluate(e, env, rng):
    if e[0] == "var":
        return env.get(e[1], 0)
    if e[0] == "const":
        return e[1]
    vals = [evaluate(a, env, rng) for a in e[2]]
    if e[0] == "call":
        return rng.randrange(100) if e[1] == "input" else 0
    a, b = vals
    return a + b if e[1] == "+" else a - b if e[1] == "-" else int(a < b)


def trace(program, rng, fuel):
    """Run the program and list (line, outcome) for each statement and predicate executed."""
    lines = {id(s): i + 1 for i, (_, s) in enumerate(lines_of(program))}
    env, out = {}, []

    def run(stmts):
        for s in stmts:
            if len(out) >= fuel:
                return
            if s[0] == "assign":
                env[s[1]] = evaluate(s[2], env, rng)
                out.append((lines[id(s)], None))
            elif s[0] == "call":
                [evaluate(a, env, rng) for a in s[2]]
                out.append((lines[id(s)], None))
            elif s[0] == "if":
                c = evaluate(s[1], env, rng) != 0
                out.append((lines[id(s)], c))
                run(s[2] if c else s[3])
            else:
                while len(out) < fuel:
                    c = evaluate(s[1], env, rng) != 0
                    out.append((lines[id(s)], c))
                    if not c:
                        break
                    run(s[2])

    run(program)
    return out, len(out) < fuel


def test_random_cfg_follows_executions():
    rng = random.Random(52)
    for _ in range(500):
        program = gen_block(rng, 2)
        cpg = build_cpg(program)
        g, L = cpg.graph, by_line(cpg)
        for n in cpg.cfg_nodes:
            conds = sorted((p["cond"] for _, p in g.out_edges(n, CFG)), key=str)
            if n == cpg.exit:
                assert conds == []
            elif g.props[n]["type"] == "pred":
                assert conds == [False, True]
            else:
                assert conds == [None]
        steps, finished = trace(program, rng, 60)
        prev, prev_cond = cpg.entry, None
        for ln, c in steps:
            assert (L[ln], {"cond": prev_cond}) in g.out_edges(prev, CFG)
            prev, prev_cond = L[ln], c
        if finished:
            assert (cpg.exit, {"cond": prev_cond}) in g.out_edges(prev, CFG)


def brute_reach(g, cfg_nodes, d, x):
    """The nodes that a definition of x at d reaches without passing another definition of x."""
    seen, stack = set(), [v for v in g.out(d, CFG)]
    while stack:
        v = stack.pop()
        if v in seen:
            continue
        seen.add(v)
        if x not in g.props[v]["defs"]:
            stack.extend(g.out(v, CFG))
    return seen


def postdominates(g, exit_, y, n):
    if y == n:
        return True
    seen, stack = {n}, [n]
    while stack:
        v = stack.pop()
        if v == exit_:
            return False
        for w in g.out(v, CFG):
            if w != y and w not in seen:
                seen.add(w)
                stack.append(w)
    return True


def test_random_dependences_and_query_against_brute_force():
    rng = random.Random(53)
    reported = 0
    for _ in range(500):
        program = gen_block(rng, 2)
        cpg = build_cpg(program)
        g, nodes = cpg.graph, cpg.cfg_nodes
        reach = set()
        for d in nodes:
            for x in g.props[d]["defs"]:
                for v in brute_reach(g, nodes, d, x):
                    if x in g.props[v]["uses"]:
                        reach.add((d, v, (("var", x),)))
        assert labelled(g, REACHES) == reach
        cd = set()
        for a in nodes:
            for s, p in g.out_edges(a, CFG):
                for y in nodes:
                    if postdominates(g, cpg.exit, y, s) and not (y != a and postdominates(g, cpg.exit, y, a)):
                        cd.add((a, y, (("cond", p["cond"]),)))
        assert labelled(g, CONTROLS) == cd
        # The query, from the program text and the two brute-force relations.
        L = by_line(cpg)
        info = {L[i + 1]: s for i, (_, s) in enumerate(lines_of(program))}
        expected = []
        for i, (kind, s) in enumerate(lines_of(program)):
            if kind != "call" or not s[2]:
                continue
            n = L[i + 1]
            for x in sorted(expr_vars(s[2][-1])):
                tainted = {d for d, v, _ in reach if v == n and g.props[d]["defs"] == (x,)}
                grow = True
                while grow:
                    more = {d for d, v, _ in reach if v in tainted} - tainted
                    tainted |= more
                    grow = bool(more)
                guards, grow = set(), True
                while grow:
                    more = {a for a, y, _ in cd if (y == n or y in guards)} - guards
                    guards |= more
                    grow = bool(more)
                guards.discard(n)
                src = any("input" in calls_in(info[t][2]) for t in tainted)
                if src and not any(x in expr_vars(info[c][1]) for c in guards):
                    expected.append((i + 1, x))
        got = unchecked_flows(cpg, "input", "copy")
        assert sorted(got) == sorted(expected)
        reported += len(got)
        assert g.check_invariant()
    assert reported > 30

History

Ferrante, Ottenstein and Warren (1987) combined data and control dependence in the program dependence graph, for optimization. Program slicing and dependence-based tools used such graphs for decades. Yamaguchi, Golde, Arp and Rieck (IEEE S&P 2014) merged the syntax tree, the control flow graph and the program dependence graph into one property graph, stored it in a graph database, and wrote traversals for types of vulnerabilities in C code. Their evaluation on the Linux kernel reported previously unknown vulnerabilities. Their implementation became the tool Joern, and the model was later extended across functions and to other languages.

References

  1. Fabian Yamaguchi, Nico Golde, Daniel Arp and Konrad Rieck, Modeling and discovering vulnerabilities with code property graphs, IEEE Symposium on Security and Privacy 2014, pp. 590 to 604, the property graph model, the merge of the three representations at statement and predicate nodes, and the traversals for types of vulnerabilities
  2. Jeanne Ferrante, Karl J. Ottenstein and Joe D. Warren, The program dependence graph and its use in optimization, ACM Transactions on Programming Languages and Systems 9(3), 1987, pp. 319 to 349, the definition of control dependence by postdominance

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/MM07HE/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
  • at least three sources