Algorithm Search⌘K

Algorithmadvanced

Logical attack graph generation

Also called MulVAL, monotonic attack graph.

Builds an attack graph of polynomial size by Datalog derivation over host configurations and vulnerabilities, under the monotonicity assumption.

Time
O(m b n^(b+1)) worst · average
Space
O(n + e) extra
Where
b = the largest number of atoms in a rule body; e = the number of derivation nodes; m = the number of rules; n = the number of facts in the fixpoint
Properties
deterministicexactofflineiterative
Origin
Xinming Ou, Wayne F. Boyer, Miles A. McQueen, 2006

Logical attack graph generation computes every way in which an attacker can reach a goal in a network, from a description of the network as logical facts. The facts state which host can reach which host on which port, which service runs where, and which service has which vulnerability. A small set of rules in Datalog states how an attacker who controls one host gains access to the next. The algorithm evaluates the rules to a fixpoint and records each rule instance it uses. Each recorded instance becomes an AND node, each derived fact an OR node, and each input fact a leaf. Ou, Boyer and McQueen (2006) built such graphs from the trace of the MulVAL engine and proved that their size grows quadratically with the number of hosts, where the earlier graphs over full network states could grow exponentially. The page treats the input as a formal model: hosts, services and vulnerabilities have made-up names, and nothing is scanned or attacked.

In plain words

Write down what is true about a network as short statements. "The outside can reach host one on port one." "Host one runs a service that has a known weakness." Then write rules, such as "if the attacker can reach a weak service, the attacker can run code on that host" and "if the attacker runs code on a host, the attacker can reach whatever that host can reach".

Apply all the rules again and again, and keep every new statement that you learn, until nothing new appears. Each time a rule fires, draw a box for that step, with arrows from the statements it used and an arrow to the statement it gave.

The result is a map. It shows each way to reach the goal, and it is small, because each statement appears once, however many paths lead to it.

The problem

The input is a set PP of ground primitive facts, a list RR of rules and an optional goal fact gg. A fact is a predicate applied to constants, such as hacl(h1,h2,p2)\mathit{hacl}(h_1, h_2, p_2) ("host h1h_1 may connect to host h2h_2 on port p2p_2"). A rule has the form H←B1,…,BtH \leftarrow B_1, \ldots, B_t with atoms that may contain variables. Every variable of the head HH also occurs in the body, and no rule derives a primitive predicate.

The output is the logical attack graph of Definition 1 of Ou et al.: the primitive facts as leaves, the derivable facts that are not primitive as OR nodes, and one AND node for each ground rule instance whose body facts are all derivable, with edges from the body facts to the instance and from the instance to its head. The goal is reachable if and only if gg is a derivable fact.

The method rests on monotonicity (Ammann, Wijesekera and Kaushik 2002): a fact, once gained, stays true, so the attacker never has to give up a privilege. This is a modeling assumption. Under it, the facts can be computed once, in any order, instead of over all sequences of network states.

The algorithm

The algorithm is naive bottom-up Datalog evaluation that also stores each rule instance it finds. Round kk matches every rule against the facts known after round k−1k - 1.

  1. LOGICAL-ATTACK-GRAPH(P, R, g) ▷ P: primitive facts, R: rules, g: a goal or none
  2. 1F ← P ; rank[f] ← 0 for each f in P ; D ← ∅ ; k ← 0
  3. 2repeat
  4. 3k ← k + 1 ; N ← ∅
  5. 4for each rule H ← B1, ..., Bt in R do
  6. 5for each substitution σ with σ(B1), ..., σ(Bt) all in F do
  7. 6D ← D ∪ {(rule, σ(H), σ(B1), ..., σ(Bt))} ▷ an AND node
  8. 7if σ(H) ∉ F then N ← N ∪ {σ(H)}
  9. 8for each h in N do F ← F ∪ {h} ; rank[h] ← k
  10. 9until N = ∅
  11. 10if g is given then keep only the nodes from which g can be reached
  12. 11return the leaves P, the OR nodes F - P and the AND nodes D

Line L5 is a join: it matches the body atoms one at a time against the facts with the same predicate, and keeps the substitutions that agree on shared variables. Line L6 stores a set, so an instance found again in a later round is not duplicated. Line L8 adds the new facts only after the round, so the rank of a fact is the round in which it first appears. The last round adds no fact, but it still records the instances whose last body fact appeared in the round before, so DD is complete. Line L10 follows the edges backward from gg.

Example

The rules are made up in the style of MulVAL:

  • R1: execCode(H,U)←networkService(H,S,P,U),vulExists(H,V,S,remote),netAccess(H,P)\mathit{execCode}(H, U) \leftarrow \mathit{networkService}(H, S, P, U), \mathit{vulExists}(H, V, S, \mathit{remote}), \mathit{netAccess}(H, P)
  • R2: netAccess(H2,P)←execCode(H1,U),hacl(H1,H2,P)\mathit{netAccess}(H_2, P) \leftarrow \mathit{execCode}(H_1, U), \mathit{hacl}(H_1, H_2, P)
  • R3: netAccess(H,P)←attackerLocated(Z),hacl(Z,H,P)\mathit{netAccess}(H, P) \leftarrow \mathit{attackerLocated}(Z), \mathit{hacl}(Z, H, P)
  • R4: execCode(H,root)←execCode(H,user),localVul(H,V)\mathit{execCode}(H, \mathit{root}) \leftarrow \mathit{execCode}(H, \mathit{user}), \mathit{localVul}(H, V)

The 11 primitive facts are: the attacker is in zone z0z_0; hacl\mathit{hacl} allows z0→h1z_0 \to h_1 on p1p_1, h1→h2h_1 \to h_2 and h1→h3h_1 \to h_3 on p2p_2, and h2→h1h_2 \to h_1 on p1p_1; services s1s_1 on h1h_1 (port p1p_1), s2s_2 on h2h_2 and s3s_3 on h3h_3 (port p2p_2) run as user\mathit{user}; s1s_1 has the remote vulnerability v1v_1 and s2s_2 has v2v_2; h2h_2 has the local vulnerability v3v_3. The goal is execCode(h2,root)\mathit{execCode}(h_2, \mathit{root}).

round rule instance found new fact
1 R3 from z0z_0 over p1p_1 netAccess(h1,p1)\mathit{netAccess}(h_1, p_1)
2 R1 s1s_1, v1v_1 execCode(h1,user)\mathit{execCode}(h_1, \mathit{user})
3 R2 from h1h_1 to h2h_2 netAccess(h2,p2)\mathit{netAccess}(h_2, p_2)
3 R2 from h1h_1 to h3h_3 netAccess(h3,p2)\mathit{netAccess}(h_3, p_2)
4 R1 s2s_2, v2v_2 execCode(h2,user)\mathit{execCode}(h_2, \mathit{user})
5 R4 v3v_3 execCode(h2,root)\mathit{execCode}(h_2, \mathit{root})
5 R2 from h2h_2 as user to h1h_1 none (a second way to netAccess(h1,p1)\mathit{netAccess}(h_1, p_1))
6 R2 from h2h_2 as root to h1h_1 none (a third way)

Round 6 adds no fact, so the loop stops. The full graph has 11 leaves, 6 OR nodes and 8 AND nodes. Host h3h_3 is reachable but has no vulnerable service, so the attacker does not run code there. The two instances of rounds 5 and 6 close a cycle through h1h_1 and h2h_2. Pruning to the goal removes netAccess(h3,p2)\mathit{netAccess}(h_3, p_2), its AND node and the two leaves about h3h_3, and leaves 9 leaves, 5 OR nodes and 7 AND nodes.

Correctness

The full proof is in the proof file. Every fact that the algorithm adds is in the least model of the program, because each one is the head of a ground instance whose body is already in the table. Conversely, a fact with a derivation tree of height hh enters the table by round hh, because line L5 enumerates every substitution into the current facts. So the loop stops with exactly the least model, and the rank of each fact is the least height of its derivation trees.

When the loop stops, the last round has seen the final set of facts, so DD holds every ground instance whose body is derivable. Every derived fact of rank rr has an instance whose body facts have smaller ranks, so the graph is well founded even when it has cycles. Under monotonicity, any order of firing single instances ends at the same set of facts, which is why one fixpoint replaces the search over attack sequences. After pruning, an AND-OR evaluation from the kept leaves still derives the goal.

Proof: The derivation fixpoint yields exactly the derivable facts and all their ground derivationsfull

Fix a finite set PP of ground primitive facts and a finite list RR of rules. Each rule H←B1,…,BkH \leftarrow B_1, \ldots, B_k has k≥1k \ge 1, every variable of HH occurs in some BiB_i, and no head uses a predicate of PP. A ground instance of a rule is the result of a substitution σ\sigma that maps every variable of the rule to a constant. Let CC be the set of constants in PP and RR. The Herbrand base UU is the finite set of ground atoms over the predicates of PP and RR and the constants of CC.

A set SS of ground atoms is closed if P⊆SP \subseteq S, and for every ground instance σ(H)←σ(B1),…,σ(Bk)\sigma(H) \leftarrow \sigma(B_1), \ldots, \sigma(B_k) with all σ(Bi)∈S\sigma(B_i) \in S, also σ(H)∈S\sigma(H) \in S. The intersection of closed sets is closed and UU is closed, so there is a least closed set MM, the least model. A derivation tree of a fact ff is a leaf if f∈Pf \in P, and otherwise a root labeled with a ground instance with head ff whose children are derivation trees of its body facts. Its height is 0 for a leaf and $1 + $ the largest height of a child otherwise.

Let FkF_k be the set of facts in the table after round kk (line L8), with F0=PF_0 = P (line L1), and let DD be the set of derivations that line L6 records.

Lemma 1 (soundness). Every Fk⊆MF_k \subseteq M, and every recorded derivation is a ground instance whose body lies in Fk⊆MF_k \subseteq M for some kk.

Proof. By induction on kk. F0=P⊆MF_0 = P \subseteq M. In round kk, lines L4 to L6 record a derivation only for a substitution σ\sigma with every σ(Bi)∈Fk−1\sigma(B_i) \in F_{k-1}. Each variable of HH occurs in the body, so σ(H)\sigma(H) is ground. As MM is closed and Fk−1⊆MF_{k-1} \subseteq M, σ(H)∈M\sigma(H) \in M. Lines L7 and L8 add only such heads. □\square

Lemma 2 (rank). A fact ff has a derivation tree of height at most kk if and only if f∈Fkf \in F_k. So the rank that line L8 stores is the least height of a derivation tree of ff.

Proof. If f∈Fkf \in F_k and ff was added in round j≤kj \le k, then some recorded instance with head ff has its body in Fj−1F_{j-1}, and by induction each body fact has a tree of height at most j−1j - 1, which gives a tree of height at most jj for ff. Conversely, let ff have a tree of height h≤kh \le k. If h=0h = 0, f∈P=F0f \in P = F_0. Otherwise the root instance has body facts with trees of height at most h−1h - 1, so by induction they lie in Fh−1F_{h-1}. Line L5 enumerates every substitution that maps the body into Fh−1F_{h-1}, because the backtracking join tries every fact of the right predicate for each body atom in turn and keeps exactly the consistent extensions. So in round hh the instance is found and f∈Fh⊆Fkf \in F_h \subseteq F_k. □\square

Theorem 1. The loop of lines L2 to L9 stops after at most ∣U∖P∣+1|U \setminus P| + 1 rounds. When it stops, the set of facts equals MM, and DD equals the set of all ground instances of rules whose body facts all lie in MM.

Proof. Each round that does not stop adds at least one new atom of UU, so there are at most ∣U∖P∣|U \setminus P| such rounds, followed by one round that adds nothing. Let the last round be KK. Then FK=FK−1F_K = F_{K-1}, and round KK found every instance with body in FK−1F_{K-1}, and none had a head outside FK−1F_{K-1}. So FK−1F_{K-1} contains PP and is closed, hence M⊆FK−1M \subseteq F_{K-1}. With Lemma 1, FK−1=MF_{K-1} = M. Every instance with body in M=FK−1M = F_{K-1} is recorded in round KK, and by Lemma 1 every recorded instance has its body in MM. □\square

So the output graph has PP as leaves (primitive fact nodes), M∖PM \setminus P as OR nodes (derived fact nodes) and DD as AND nodes (derivation nodes), with an edge from each body fact to its derivation and from each derivation to its head. This is Definition 1 of Ou, Boyer and McQueen: each derivation node with its body and head is an instance of its rule. The graph can have cycles, but by Lemma 2 each derived fact ff of rank rr has a derivation whose body facts all have rank below rr.

Theorem 2 (order does not matter). Start from S=PS = P and repeatedly add the head of any one ground instance whose body lies in SS and whose head is not in SS, until no such instance exists. Every such run stops with S=MS = M.

Proof. Each added head is in MM by the argument of Lemma 1, so S⊆MS \subseteq M at all times and the run stops after at most ∣M∖P∣|M \setminus P| steps. When it stops, SS contains PP and is closed, so M⊆SM \subseteq S. □\square

This is the monotonicity assumption of Ammann, Wijesekera and Kaushik in this setting: a gained fact is never lost, so the order of the attack steps does not change what the attacker can reach.

Theorem 3 (goal pruning). Let g∈Mg \in M, and let line L10 keep the nodes from which gg can be reached along edges. Then evaluating the kept graph from its leaves (a derivation fires when all its body facts are known, and a fact is known when one of its derivations fires) makes gg known. If g∉Mg \notin M, the result is empty.

Proof. Take a derivation tree of gg. Every node of the tree has a path to gg along the tree, which is a path in the graph, so all its facts and instances are kept. Evaluating from the leaves up the tree makes gg known. If g∉Mg \notin M, gg is not in the table and line L10 keeps nothing. □\square

Cost. Let n=∣M∣n = |M|, let mm be the number of rules, let bb be the largest body length, and treat the arities as constants. In one round, for one rule, the join has at most nin^i partial substitutions after ii body atoms, and each scans at most nn facts, so the work is at most ∑i=0b−1ni+1=O(nb)\sum_{i=0}^{b-1} n^{i+1} = O(n^b), plus O(b)O(b) to build each of the at most nbn^b instances. There are at most n−∣P∣+1≤nn - |P| + 1 \le n rounds, so the time is O(mbnb+1)O(m b n^{b+1}). The space is O(n)O(n) for the facts and O(e)O(e) for the e≤mnbe \le m n^b derivations. ■\blacksquare

Complexity

The model is the word RAM, with the arity of each predicate a constant. In one round and for one rule, the join has at most nin^i partial substitutions after ii body atoms, and each scans at most nn facts, so the work is O(nb)O(n^b). There are at most nn rounds, which gives O(mbnb+1)O(m b n^{b+1}) time. The space is O(n+e)O(n + e), with e≤mnbe \le m n^b.

This bound is for any program. For the MulVAL rules, Ou et al. prove that evaluation takes O(N2)O(N^2) derivation steps for NN hosts, because the rule with the most body instances is the multi-hop rule, whose only variables that grow with the network are the two hosts (their Theorem 1). Then the graph has O(N2)O(N^2) nodes and edges (Theorem 2), and building it from the trace is quadratic given constant-time lookup (Theorem 3). On the made-up rules of the example, a network of NN hosts that all reach each other and all have a remote vulnerability gives exactly N2+NN^2 + N AND nodes: NN from R3, NN from R1 and N(N−1)N(N - 1) from R2.

Properties

  • Polynomial size. Each fact and each ground instance appears once. A graph over network states, as produced by a model checker, can have a node for each subset of attacker privileges.
  • AND-OR semantics. A derived fact needs one of its AND nodes, and an AND node needs all its body facts. So the graph answers "which sets of configuration facts suffice for the goal" by AND-OR evaluation.
  • Cycles. The graph can have cycles, as in the example. Analyses on it must handle them, for example by the rank, which gives an acyclic derivation for each fact.
  • Exact within the model. The graph is exactly the set of derivations of the rules. Whether those rules match the real network is outside the algorithm.

Variants and improvements

  • Semi-naive evaluation. Semi-naive evaluation joins at least one fact of the last round in each instance, so it does not find an old instance again in each round. The result is the same.
  • Goal-directed evaluation. MulVAL runs the rules top-down from the goal in the tabled Prolog system XSB and records a trace step each time a rule body succeeds. Tabling stops infinite loops in cyclic rules, but the trace can still contain cycles, which the graph builder keeps.
  • Model checking. Sheyner et al. (2002) produced attack graphs as the set of counterexamples of a symbolic model checker over network states. This handles non-monotonic steps but the graph can be exponential in size.
  • Graph search under monotonicity. Ammann et al. (2002) gave a polynomial search over attributes and exploits, with a bound of O(∣A∣2∣E∣)O(|A|^2 |E|). Ou et al. estimate this as O(N6)O(N^6) for NN hosts if attributes include host connectivity.
  • Analyses on the graph. A smallest set of leaves whose removal makes the goal underivable is a hitting set problem over the minimal derivations, and in special cases a cut problem. Probabilities on leaves give a likelihood of the goal.

When to use it

Use it for a network of many hosts when the question is "can the attacker reach this goal, and through which configuration facts", and when the attack steps can be modeled as gaining facts that are never lost. Use a state-based model checker instead when a step can remove a fact that later steps need, for example when an action crashes the service that another action uses.

Pitfalls

  • Monotonicity is an assumption. It does not hold for actions that close an access path or for defenses that react. Ou et al. argue that most such cases can be modeled monotonically at a higher level of detail, but this is a modeling heuristic.
  • Garbage in. The graph is only as good as the facts and rules. A missing hacl\mathit{hacl} fact hides a path, and a too-general rule adds paths that do not exist.
  • Large bodies. The nb+1n^{b+1} term is real for rules with many independent variables. The quadratic bound of Ou et al. depends on the shape of the MulVAL rules.
  • Counting paths. The graph is small because it shares facts. The number of distinct attack paths through it can still be exponential, so an analysis that lists all paths loses the gain.

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.

logical_attack_graph_generation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/logical-attack-graph-generation/. The authors are listed in prov/XBY4JC.jsonl.

"""Logical attack graph generation by Datalog derivation (after Ou, Boyer and McQueen 2006).

A fact is a tuple (predicate, constant, ...). A rule is a pair (head, body),
where head is an atom and body is a tuple of atoms. In an atom, a term that
starts with an upper-case letter is a variable, and any other term is a
constant. The input is a formal model with made-up host and vulnerability
names. Nothing here reads a real configuration or touches a real network.

The graph has three kinds of nodes: the primitive facts (leaves), the derived
facts (OR nodes: any one derivation suffices) and the derivations (AND nodes:
one ground rule instance, which needs all its body facts).
"""

from typing import Iterator

Atom = tuple[str, ...]
Rule = tuple[Atom, tuple[Atom, ...]]
Derivation = tuple[int, Atom, tuple[Atom, ...]]


def is_var(term: str) -> bool:
    return term[:1].isupper()


def ground(atom: Atom, sub: dict[str, str]) -> Atom:
    return (atom[0],) + tuple(sub[t] if is_var(t) else t for t in atom[1:])


def check_program(primitive: set[Atom], rules: list[Rule]) -> None:
    """Raise ValueError unless facts are ground and rules are range restricted."""
    for f in primitive:
        if any(is_var(t) for t in f[1:]):
            raise ValueError("primitive facts must be ground")
    prim_preds = {f[0] for f in primitive}
    for head, body in rules:
        if not body:
            raise ValueError("a rule needs a nonempty body")
        body_vars = {t for a in body for t in a[1:] if is_var(t)}
        if any(is_var(t) and t not in body_vars for t in head[1:]):
            raise ValueError("every head variable must occur in the body")
        if head[0] in prim_preds:
            raise ValueError("a rule may not derive a primitive predicate")


def _match(atom: Atom, fact: Atom, sub: dict[str, str]) -> dict[str, str] | None:
    if len(atom) != len(fact):
        return None
    out = dict(sub)
    for t, c in zip(atom[1:], fact[1:]):
        if is_var(t):
            if out.setdefault(t, c) != c:
                return None
        elif t != c:
            return None
    return out


def _substitutions(
    body: tuple[Atom, ...], index: dict[str, list[Atom]], sub: dict[str, str]
) -> Iterator[dict[str, str]]:
    """All substitutions that extend sub and map every body atom into the facts."""
    if not body:
        yield sub
        return
    for fact in index.get(body[0][0], ()):
        s = _match(body[0], fact, sub)
        if s is not None:
            yield from _substitutions(body[1:], index, s)


def logical_attack_graph(
    primitive: set[Atom], rules: list[Rule], goal: Atom | None = None
) -> dict:
    """Build the logical attack graph of a Datalog program.

    Precondition: primitive facts are ground; every rule has a nonempty body,
    every head variable occurs in the body, and no rule derives a primitive
    predicate. Returns a dict with "leaves" (the primitive facts), "rank" (the
    round in which each fact first appears, 0 for leaves) and "derivations"
    (the set of (rule index, head, body) ground instances). If goal is given,
    only the nodes from which the goal can be reached are kept, and the goal
    must be derivable or the result is empty.
    Cost: with n facts in the fixpoint, m rules and body length at most b,
    O(m b n^(b+1)) time in the worst case (at most n rounds of at most n^b
    substitutions per rule) and O(n + e) space for e derivations.
    """
    check_program(primitive, rules)
    rank: dict[Atom, int] = {f: 0 for f in primitive}  # @line L1
    derivations: set[Derivation] = set()
    k = 0
    while True:  # @line L2
        k += 1  # @line L3
        new: set[Atom] = set()
        index: dict[str, list[Atom]] = {}
        for f in rank:
            index.setdefault(f[0], []).append(f)
        for r, (head, body) in enumerate(rules):  # @line L4
            for sub in _substitutions(body, index, {}):  # @line L5
                h = ground(head, sub)
                derivations.add((r, h, tuple(ground(a, sub) for a in body)))  # @line L6
                if h not in rank:  # @line L7
                    new.add(h)
        for h in new:  # @line L8
            rank[h] = k
        if not new:  # @line L9
            break
    if goal is not None:  # @line L10
        keep = _ancestors(goal, rank, derivations)
        rank = {f: v for f, v in rank.items() if f in keep}
        derivations = {d for d in derivations if d in keep}
    leaves = {f for f in primitive if f in rank}
    return {"leaves": leaves, "rank": rank, "derivations": derivations}  # @line L11


def _ancestors(goal: Atom, rank: dict[Atom, int], derivations: set[Derivation]) -> set:
    """Facts and derivations from which goal can be reached by edges."""
    if goal not in rank:
        return set()
    into: dict[Atom, list[Derivation]] = {}
    for d in derivations:
        into.setdefault(d[1], []).append(d)
    seen: set = {goal}
    stack: list = [goal]
    while stack:
        node = stack.pop()
        if len(node) == 3 and isinstance(node[0], int):
            nxt = list(node[2])
        else:
            nxt = into.get(node, [])
        for x in nxt:
            if x not in seen:
                seen.add(x)
                stack.append(x)
    return seen


def graph_size(graph: dict) -> tuple[int, int, int]:
    """Return (leaves, derived facts, derivation nodes) of a graph."""
    leaves = len(graph["leaves"])
    return leaves, len(graph["rank"]) - leaves, len(graph["derivations"])
test_logical_attack_graph_generation.py 275 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/logical-attack-graph-generation/. The authors are listed in prov/XBY4JC.jsonl.

import itertools
import random

import pytest

from logical_attack_graph_generation import (
    ground,
    graph_size,
    is_var,
    logical_attack_graph,
)

# A small made-up rule set in the style of MulVAL. All names are abstract.
RULES = [
    (
        ("execCode", "H", "U"),
        (
            ("networkService", "H", "S", "P", "U"),
            ("vulExists", "H", "V", "S", "remote"),
            ("netAccess", "H", "P"),
        ),
    ),
    (("netAccess", "H2", "P"), (("execCode", "H1", "U"), ("hacl", "H1", "H2", "P"))),
    (("netAccess", "H", "P"), (("attackerLocated", "Z"), ("hacl", "Z", "H", "P"))),
    (("execCode", "H", "root"), (("execCode", "H", "user"), ("localVul", "H", "V"))),
]

EXAMPLE = {
    ("attackerLocated", "zone0"),
    ("hacl", "zone0", "h1", "p1"),
    ("hacl", "h1", "h2", "p2"),
    ("hacl", "h1", "h3", "p2"),
    ("hacl", "h2", "h1", "p1"),
    ("networkService", "h1", "s1", "p1", "user"),
    ("vulExists", "h1", "v1", "s1", "remote"),
    ("networkService", "h2", "s2", "p2", "user"),
    ("vulExists", "h2", "v2", "s2", "remote"),
    ("networkService", "h3", "s3", "p2", "user"),
    ("localVul", "h2", "v3"),
}


def test_page_example() -> None:
    g = logical_attack_graph(EXAMPLE, RULES)
    derived = {f: r for f, r in g["rank"].items() if r > 0}
    assert derived == {
        ("netAccess", "h1", "p1"): 1,
        ("execCode", "h1", "user"): 2,
        ("netAccess", "h2", "p2"): 3,
        ("netAccess", "h3", "p2"): 3,
        ("execCode", "h2", "user"): 4,
        ("execCode", "h2", "root"): 5,
    }
    assert graph_size(g) == (11, 6, 8)
    goal = ("execCode", "h2", "root")
    p = logical_attack_graph(EXAMPLE, RULES, goal)
    assert graph_size(p) == (9, 5, 7)
    assert ("netAccess", "h3", "p2") not in p["rank"]
    assert ("netAccess", "h1", "p1") in p["rank"]


def instances(rules, facts_by_pred):
    """Oracle join: every tuple of facts with matching predicates that unifies."""
    out = set()
    for r, (head, body) in enumerate(rules):
        pools = [facts_by_pred.get(a[0], []) for a in body]
        for combo in itertools.product(*pools):
            sub: dict = {}
            ok = True
            for a, f in zip(body, combo):
                if len(a) != len(f):
                    ok = False
                    break
                for t, c in zip(a[1:], f[1:]):
                    if is_var(t):
                        if sub.setdefault(t, c) != c:
                            ok = False
                    elif t != c:
                        ok = False
                if not ok:
                    break
            if ok:
                out.add((r, ground(head, sub), tuple(combo)))
    return out


def oracle(primitive, rules):
    """Naive fixpoint with the join done by an exhaustive product of facts."""
    facts = set(primitive)
    rank = {f: 0 for f in primitive}
    k = 0
    while True:
        k += 1
        by_pred: dict = {}
        for f in facts:
            by_pred.setdefault(f[0], []).append(f)
        ds = instances(rules, by_pred)
        new = {d[1] for d in ds} - facts
        if not new:
            return rank, ds
        for h in new:
            rank[h] = k
        facts |= new


def domain_oracle(primitive, rules):
    """Fixpoint by trying every map from variables to the constants in use."""
    consts = sorted({c for f in primitive for c in f[1:]})
    facts = set(primitive)
    while True:
        ds = set()
        for r, (head, body) in enumerate(rules):
            vs = sorted({t for a in body for t in a[1:] if is_var(t)})
            for vals in itertools.product(consts, repeat=len(vs)):
                sub = dict(zip(vs, vals))
                gb = tuple(ground(a, sub) for a in body)
                if all(g in facts for g in gb):
                    ds.add((r, ground(head, sub), gb))
        new = {d[1] for d in ds} - facts
        if not new:
            return facts, ds
        facts |= new


def random_network(rng: random.Random):
    hosts = ["h%d" % i for i in range(1, rng.randint(2, 4) + 1)]
    ports = ["p1", "p2"][: rng.randint(1, 2)]
    facts = {("attackerLocated", "zone0")}
    for a in ["zone0"] + hosts:
        for b in hosts:
            for p in ports:
                if a != b and rng.random() < 0.4:
                    facts.add(("hacl", a, b, p))
    for i, h in enumerate(hosts):
        if rng.random() < 0.8:
            s, p = "s%d" % i, rng.choice(ports)
            facts.add(("networkService", h, s, p, rng.choice(["user", "root"])))
            if rng.random() < 0.6:
                facts.add(("vulExists", h, "v%d" % i, s, rng.choice(["remote", "local"])))
        if rng.random() < 0.3:
            facts.add(("localVul", h, "v9"))
    return facts


def random_program(rng: random.Random):
    """Random range-restricted rules over primitive e/2, f/1 and derived a/1, b/2."""
    consts = ["c1", "c2", "c3"][: rng.randint(2, 3)]
    prim = set()
    for x in consts:
        if rng.random() < 0.5:
            prim.add(("f", x))
        for y in consts:
            if rng.random() < 0.4:
                prim.add(("e", x, y))
    preds = [("e", 2), ("f", 1), ("a", 1), ("b", 2)]
    rules = []
    for _ in range(rng.randint(1, 4)):
        body = []
        for _ in range(rng.randint(1, 3)):
            p, ar = rng.choice(preds)
            body.append((p,) + tuple(rng.choice(["X", "Y", "Z", "c1"]) for _ in range(ar)))
        bv = sorted({t for a in body for t in a[1:] if is_var(t)}) or ["c1"]
        hp, har = rng.choice([("a", 1), ("b", 2)])
        rules.append(((hp,) + tuple(rng.choice(bv) for _ in range(har)), tuple(body)))
    if not prim:
        prim.add(("f", "c1"))
    return prim, rules


def test_against_join_oracle() -> None:
    rng = random.Random(2006)
    for _ in range(400):
        facts = random_network(rng)
        g = logical_attack_graph(facts, RULES)
        rank, ds = oracle(facts, RULES)
        assert g["rank"] == rank
        assert g["derivations"] == ds


def test_against_domain_oracle() -> None:
    rng = random.Random(336)
    for _ in range(300):
        prim, rules = random_program(rng)
        g = logical_attack_graph(prim, rules)
        facts, ds = domain_oracle(prim, rules)
        assert set(g["rank"]) == facts
        assert g["derivations"] == ds


def test_any_firing_order_reaches_the_same_state() -> None:
    # Monotonicity: firing one new ground instance at a time, in any order,
    # ends in the same set of facts.
    rng = random.Random(345)
    for _ in range(150):
        facts = random_network(rng)
        target = set(logical_attack_graph(facts, RULES)["rank"])
        state = set(facts)
        while True:
            by_pred: dict = {}
            for f in state:
                by_pred.setdefault(f[0], []).append(f)
            fresh = sorted({d[1] for d in instances(RULES, by_pred)} - state)
            if not fresh:
                break
            state.add(rng.choice(fresh))
        assert state == target


def test_graph_structure() -> None:
    rng = random.Random(17)
    for _ in range(200):
        facts = random_network(rng)
        g = logical_attack_graph(facts, RULES)
        rank, ds = g["rank"], g["derivations"]
        heads = {d[1] for d in ds}
        assert not (heads & g["leaves"])
        for d in ds:
            assert all(b in rank for b in d[2])
        for f, r in rank.items():
            if r > 0:
                # Well founded: some derivation of f uses only older facts.
                assert any(d[1] == f and all(rank[b] < r for b in d[2]) for d in ds)
        for f in rank:
            if f[0] == "execCode":
                goal = f
                p = logical_attack_graph(facts, RULES, goal)
                # The AND-OR evaluation of the pruned graph derives the goal.
                known = set(p["leaves"])
                changed = True
                while changed:
                    changed = False
                    for d in p["derivations"]:
                        if d[1] not in known and all(b in known for b in d[2]):
                            known.add(d[1])
                            changed = True
                assert goal in known
                assert set(p["rank"]) <= set(rank)
                assert p["derivations"] <= ds
                break


def test_quadratic_size() -> None:
    # N hosts, all reachable from each other on one port, each with a remote
    # vulnerability: N + N derivations from rules 3 and 1, N (N - 1) from rule 2.
    for n in range(1, 9):
        hosts = ["h%d" % i for i in range(n)]
        facts = {("attackerLocated", "zone0")}
        for h in hosts:
            facts.add(("hacl", "zone0", h, "p1"))
            facts.add(("networkService", h, "s1", "p1", "user"))
            facts.add(("vulExists", h, "v1", "s1", "remote"))
            for h2 in hosts:
                if h2 != h:
                    facts.add(("hacl", h, h2, "p1"))
        g = logical_attack_graph(facts, RULES)
        assert graph_size(g) == (len(facts), 2 * n, n * n + n)


def test_bad_programs() -> None:
    with pytest.raises(ValueError):
        logical_attack_graph({("e", "c1", "c2")}, [(("a", "X"), (("e", "Y", "Y"),))])
    with pytest.raises(ValueError):
        logical_attack_graph({("e", "X", "c2")}, [(("a", "c1"), (("e", "c1", "c2"),))])
    with pytest.raises(ValueError):
        logical_attack_graph({("e", "c1", "c2")}, [(("e", "X", "X"), (("e", "X", "Y"),))])
    with pytest.raises(ValueError):
        logical_attack_graph({("e", "c1", "c2")}, [(("a", "c1"), ())])
    assert logical_attack_graph({("e", "c1", "c2")}, RULES, ("execCode", "h1", "user")) == {
        "leaves": set(),
        "rank": {},
        "derivations": set(),
    }

History

Phillips and Swiler (1998) proposed attack graphs for network risk analysis. Sheyner, Haines, Jha, Lippmann and Wing (2002) generated them with a model checker over network states. Ammann, Wijesekera and Kaushik (2002) introduced the monotonicity assumption and a polynomial graph search. Ou, Govindavajhala and Appel (2005) modeled network security in Datalog in the MulVAL analyzer. Ou, Boyer and McQueen (2006) turned the MulVAL derivation trace into the logical attack graph with a quadratic bound. On simulated networks of up to about 1000 hosts, on a 3.2 GHz Pentium 4 with XSB 2.7.1, they measured a CPU time between quadratic and cubic in the worst topology, a fully connected network. They attributed the extra factor to the lookup in a C++ map. This is a measurement from 2006, not a property of the algorithm.

References

  1. Xinming Ou, Wayne F. Boyer and Miles A. McQueen, A scalable approach to attack graph generation, ACM Conference on Computer and Communications Security (CCS) 2006, pages 336 to 345, Definition 1 (the logical attack graph with derivation, primitive fact and derived fact nodes), Section 4 (the attack simulation trace and the graph building algorithm), Section 5 (Theorems 1 to 3 on the quadratic size and time), Section 6 (the experiments on simulated networks)
  2. Xinming Ou, Sudhakar Govindavajhala and Andrew W. Appel, MulVAL, a logic-based network security analyzer, 14th USENIX Security Symposium, 2005, pages 113 to 128, the Datalog model of hosts, network access and vulnerabilities, and the interaction rules
  3. Paul Ammann, Duminda Wijesekera and Saket Kaushik, Scalable, graph-based network vulnerability analysis, ACM CCS 2002, pages 217 to 224, the monotonicity assumption and the polynomial graph search
  4. Oleg Sheyner, Joshua Haines, Somesh Jha, Richard Lippmann and Jeannette M. Wing, Automated generation and analysis of attack graphs, IEEE Symposium on Security and Privacy 2002, pages 273 to 284, attack graphs as the counterexamples of a model checker, the state-based approach that the logical graph replaces

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 proofH1 sketch
  • a full proof of time.average
  • a full proof of time.worst
  • a full proof of space.extra
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