Algorithm Search⌘K

Algorithmresearch

Faceted execution

Also called faceted values.

Runs one program on values with a secret and a public facet, so that each observer sees the result computed from what it may know. This gives termination-insensitive noninterference.

Time
O((a + b) n) worst
Space
O(n) extra
Where
a = the number of steps of the plain run on the true inputs; b = the number of steps of the plain run on the public view; n = the number of nodes of the syntax tree of the program
Properties
not completedeterministiconlineiterativesound
Origin
Thomas H. Austin, Cormac Flanagan, 2012

Faceted execution runs a program once, on values that can have two facets: a value ⟨a:b⟩\langle a : b \rangle shows aa to an observer who may see secrets and bb to an observer who may not. A secret input hh starts as ⟨h:d⟩\langle h : d \rangle, with a fixed default value dd. Most of the program runs once for both observers. Only where the two facets of a condition differ does the run split, and each observer's view takes its own branch. Austin and Flanagan (2012) proved the projection theorem: the view of each observer is exactly the plain run of the program on the inputs that observer may see. This gives termination-insensitive noninterference (TINI) without the stops of no-sensitive-upgrade.

In plain words

Think of each variable as a pair of values. One is for people who may know the secret, and the other is for everyone else. At the start, a secret variable holds the real secret on the first side and a fake value, such as 0, on the second side. Public variables hold the same value on both sides. The program then runs on these pairs. Adding two pairs adds each side. When the program must choose a branch and both sides agree, it takes that branch once. When they disagree, it runs each branch for one side only, and an assignment there changes only that side. At the end, the public side is what the program would give with the fake secret. So it cannot depend on the real secret.

The problem

The input is a program cc in a small while language, a set of secret variables (level HH) and public variables (level LL), an initial store ss and a default value dd. The output is a final faceted store σ\sigma. The observer at HH sees the HH facet πH(σ)\pi_H(\sigma) of every variable, and the observer at LL sees the LL facet πL(σ)\pi_L(\sigma).

The goal is the projection property: πH(σ)\pi_H(\sigma) is the plain result [ ⁣[c] ⁣](s)[\![c]\!](s), and πL(σ)\pi_L(\sigma) is the plain result [ ⁣[c] ⁣](sL)[\![c]\!](s_L), where sLs_L is ss with each secret input replaced by dd. Since sLs_L depends only on the public inputs, so does the view of the public observer. The program may be any program, secure or not.

The algorithm

The run uses an explicit stack of pairs (command, program counter). The program counter is none outside a split, HH in a branch that only the HH view takes, and LL in a branch that only the LL view takes. Here ⟨a:b⟩\langle a : b \rangle is a plain value when a=ba = b, and the faceted value of an expression is the pair of its values in the two views.

  1. FACETED-RUN(c, σ) ▷ the final faceted store
  2. 1S ← a stack that holds the pair (c, none)
  3. 2while S is not empty do
  4. 3(d, p) ← pop(S)
  5. 4if d = (x := e) then v ← the faceted value of e in σ
  6. 5if p = none then σ(x) ← v
  7. 6if p = H then σ(x) ← ⟨H view of v : L view of σ(x)⟩
  8. 7if p = L then σ(x) ← ⟨H view of σ(x) : L view of v⟩
  9. 8if d = (d1; d2) then push (d2, p), then (d1, p)
  10. 9if d is an if or a while on e then (bH, bL) ← the truth of e in each view
  11. 10if p = none and bH ≠ bL then
  12. 11A ← [(L, bL), (H, bH)] ▷ split: each view takes its own arm
  13. 12else A ← [(p, b)], with b = bL if p = L and b = bH otherwise
  14. 13for each (q, b) in A, if d = (if e then d1 else d2): push (d1 if b else d2, q)
  15. 14for each (q, b) in A, if d = (while e do d1) and b: push (d, q), then (d1, q)
  16. 15return σ

Lines L6 and L7 are the faceted form of an assignment in a secret context: the write changes only the view that takes the branch, and the other view keeps the old value. This is how faceted execution handles the implicit flows of a branch that one view does not take: that view simply never sees the write. Line L10 splits the run only when the two views disagree on a condition. Inside a split (line L12), each view follows its own condition, and there is no second split, because there are only two views. A program that does not branch on secrets never splits and costs about as much as the plain run.

Example

Take Fenton's program, with hh secret, ll and mm public, and the default value d=0d = 0:

(l:=1); (m:=1); (if h then m:=0 else skip); (if m then l:=0 else skip).(l := 1);\ (m := 1);\ (\mathtt{if}\ h\ \mathtt{then}\ m := 0\ \mathtt{else}\ \mathtt{skip});\ (\mathtt{if}\ m\ \mathtt{then}\ l := 0\ \mathtt{else}\ \mathtt{skip}).

With h=1h = 1 the start store is h=⟨1:0⟩h = \langle 1 : 0 \rangle. The steps for the sequences are left out, and the two first assignments give l=m=1l = m = 1, the same in both views.

step popped (d,p)(d, p) action mm ll
1 (if hh ..., none) bH=1b_H = 1, bL=0b_L = 0: split, push (skip,L)(\mathtt{skip}, L), then (m:=0,H)(m := 0, H) 1 1
2 (m:=0,H)(m := 0, H) change the HH view only (L6) ⟨0:1⟩\langle 0 : 1 \rangle 1
3 (skip,L)(\mathtt{skip}, L) nothing ⟨0:1⟩\langle 0 : 1 \rangle 1
4 (if mm ..., none) bH=0b_H = 0, bL=1b_L = 1: split, push (l:=0,L)(l := 0, L), then (skip,H)(\mathtt{skip}, H) ⟨0:1⟩\langle 0 : 1 \rangle 1
5 (skip,H)(\mathtt{skip}, H) nothing ⟨0:1⟩\langle 0 : 1 \rangle 1
6 (l:=0,L)(l := 0, L) change the LL view only (L7) ⟨0:1⟩\langle 0 : 1 \rangle ⟨1:0⟩\langle 1 : 0 \rangle

The final store is h=⟨1:0⟩h = \langle 1 : 0 \rangle, l=⟨1:0⟩l = \langle 1 : 0 \rangle, m=⟨0:1⟩m = \langle 0 : 1 \rangle. The HH view (h,l,m)=(1,1,0)(h, l, m) = (1, 1, 0) is the plain run with h=1h = 1. The LL view (0,0,1)(0, 0, 1) is the plain run with h=0h = 0. With h=0h = 0 the two views agree everywhere, no split happens, and the run ends with l=0l = 0, m=1m = 1. So the public observer sees l=0l = 0 in both runs, while the plain program gives l=1l = 1 when h≠0h \ne 0. No-sensitive-upgrade stops the run with h=1h = 1 at step 2.

Correctness

Theorem 1 (projection, Austin and Flanagan 2012). Hypotheses: a deterministic while language and two levels; any program and any faceted start store σ0\sigma_0. Statement: the faceted run ends if and only if the plain runs from πH(σ0)\pi_H(\sigma_0) and from πL(σ0)\pi_L(\sigma_0) both end, and then πX\pi_X of the final store is the result of the plain run from πX(σ0)\pi_X(\sigma_0), for X=HX = H and X=LX = L.

The proof below shows that each step of the faceted run is a step of the plain run of one view or of both, and changes nothing in the other view. Lines L6 and L7 keep the other view, and line L11 gives each view the arm that its own condition chooses.

Theorem 2 (TINI). Hypotheses: two start stores that agree on the public inputs, each secret input xx given as ⟨s(x):d⟩\langle s(x) : d \rangle. Statement: if both faceted runs end, the observer at LL sees the same final store. Both LL views start from the same store sLs_L, so by Theorem 1 both are [ ⁣[c] ⁣](sL)[\![c]\!](s_L).

The HH view is the plain run on the true inputs. When the program is TINI and the faceted run ends, the LL view also gives the true values of the public variables, so faceted execution changes nothing that the public observer should see.

Proof: The projection theorem for faceted execution, and termination-insensitive noninterferencefull

We use the language and the pseudocode of the page, with the two levels L≤HL \le H. A faceted value is a plain value, which both views see, or a pair ⟨a:b⟩\langle a : b \rangle with a≠ba \ne b, whose HH view is aa and whose LL view is bb. We write ⟨a:b⟩\langle a : b \rangle also when a=ba = b, and then mean the plain value aa. For a faceted store σ\sigma and a view X∈{H,L}X \in \{H, L\}, πX(σ)\pi_X(\sigma) is the plain store of the XX views. The faceted value of an expression ee is ⟨[ ⁣[e] ⁣]πH(σ):[ ⁣[e] ⁣]πL(σ)⟩\langle [\![e]\!]\pi_H(\sigma) : [\![e]\!]\pi_L(\sigma) \rangle, so its XX view is the plain value of ee in πX(σ)\pi_X(\sigma).

The plain machine. The plain run of cc from a store ss is this machine. Its state is a stack of commands and a store, and it starts with the stack [c][c]. A step pops the top command dd. For skip it does nothing. For x:=ex := e it sets s(x)s(x) to the value of ee. For d1;d2d_1; d_2 it pushes d2d_2 and then d1d_1. For "if ee then d1d_1 else d2d_2" it pushes d1d_1 if ee is true and d2d_2 otherwise. For "while ee do d1d_1" it pushes the loop and then d1d_1 if ee is true, and nothing otherwise. The run ends when the stack is empty; [ ⁣[c] ⁣](s)[\![c]\!](s) is the final store, or ⊥\bot if the run does not end. This machine gives the usual semantics of the language.

Projection of a configuration. A configuration of the faceted run is a stack SS of pairs (d,p)(d, p) with p∈{none,H,L}p \in \{\mathit{none}, H, L\}, and a faceted store σ\sigma. For a view XX, let πX(S)\pi_X(S) be the stack of the commands dd of the pairs (d,p)(d, p) of SS with p=nonep = \mathit{none} or p=Xp = X, in the same order. A pair with p=Hp = H belongs only to the HH view, a pair with p=Lp = L only to the LL view, and a pair with p=nonep = \mathit{none} to both.

Lemma (one step). Let a step of the faceted run go from (S,σ)(S, \sigma) to (S′,σ′)(S', \sigma'), and let (d,p)(d, p) be the popped pair. For each view XX: if p=nonep = \mathit{none} or p=Xp = X, the plain machine goes in one step from (πX(S),πX(σ))(\pi_X(S), \pi_X(\sigma)) to (πX(S′),πX(σ′))(\pi_X(S'), \pi_X(\sigma')); otherwise πX(S′)=πX(S)\pi_X(S') = \pi_X(S) and πX(σ′)=πX(σ)\pi_X(\sigma') = \pi_X(\sigma).

Proof. If p=nonep = \mathit{none} or p=Xp = X, then dd is in πX(S)\pi_X(S), and it is the top of πX(S)\pi_X(S) because it is the top of SS and πX\pi_X keeps the order. So the plain machine also pops dd. We go through the cases.

  • skip. Nothing changes.
  • x:=ex := e (lines L4 to L7). Let vv be the faceted value of ee. If p=nonep = \mathit{none}, line L5 sets σ′(x)=v\sigma'(x) = v, whose XX view is the plain value of ee in πX(σ)\pi_X(\sigma), as in the plain machine. If p=Hp = H, line L6 sets the HH view of xx to the HH view of vv and keeps its LL view. So πH\pi_H follows the plain step, and πL(σ′)=πL(σ)\pi_L(\sigma') = \pi_L(\sigma); the pair is not in πL(S)\pi_L(S), so πL(S′)=πL(S)\pi_L(S') = \pi_L(S). Line L7 is the same with HH and LL exchanged.
  • d1;d2d_1; d_2 (line L8). Both new pairs get the label pp. So they are in πX(S′)\pi_X(S') exactly when the popped pair was in πX(S)\pi_X(S), and then πX\pi_X follows the plain step.
  • if or while on ee (lines L9 to L14). Let bHb_H and bLb_L be the truth of ee in the two views. If p=nonep = \mathit{none} and bH≠bLb_H \ne b_L, line L11 pushes the arm for bLb_L with the label LL and then the arm for bHb_H with the label HH. For an if, this is the branch chosen by bLb_L and the branch chosen by bHb_H. For a while, it is the loop and its body, for each view whose condition is true. The pairs with the label XX are the ones the plain step of the XX view pushes, with the condition bXb_X, and the other pairs are not in πX(S′)\pi_X(S'). Otherwise, line L12 makes one arm with the label pp and the truth value bb, where b=bLb = b_L if p=Lp = L and b=bHb = b_H if p=Hp = H. If p=nonep = \mathit{none}, then bH=bL=bb_H = b_L = b. In each case, for each view XX with p=nonep = \mathit{none} or p=Xp = X, b=bXb = b_X, so the pushed pairs are the ones the plain step pushes, and they are in πX(S′)\pi_X(S'). For the other view, nothing changes.

Theorem 1 (projection). Let σ0\sigma_0 be a faceted store. The faceted run of cc from σ0\sigma_0 ends if and only if the plain runs from πH(σ0)\pi_H(\sigma_0) and from πL(σ0)\pi_L(\sigma_0) both end. If it ends in σ\sigma, then πH(σ)=[ ⁣[c] ⁣](πH(σ0))\pi_H(\sigma) = [\![c]\!](\pi_H(\sigma_0)) and πL(σ)=[ ⁣[c] ⁣](πL(σ0))\pi_L(\sigma) = [\![c]\!](\pi_L(\sigma_0)). The number of steps of the faceted run is at most the sum of the numbers of steps of the two plain runs.

Proof. The start configuration ([(c,none)],σ0)([(c, \mathit{none})], \sigma_0) projects to the start configuration ([c],πX(σ0))([c], \pi_X(\sigma_0)) of the plain run of each view. By the lemma and induction on the number of steps, after each step of the faceted run, the projection on each view XX is a configuration of the plain run of XX, reached after as many plain steps as there were faceted steps whose pair belongs to XX. Each pair belongs to at least one view, so after mm faceted steps the two plain runs together have made at least mm steps.

If the faceted run ends, its stack is empty, so both projected stacks are empty: both plain runs have ended, with the final stores πH(σ)\pi_H(\sigma) and πL(σ)\pi_L(\sigma). Their numbers of steps add up to at least the number of faceted steps. If both plain runs end, after aa and bb steps, the faceted run cannot make more than a+ba + b steps, since each of its steps is a step of one of the plain runs, and a plain run that has ended has no more steps; so the stack of the faceted run is empty after at most a+ba + b steps, and the run ends.

Theorem 2 (TINI). Let s1s_1 and s2s_2 be plain stores that agree on the public variables. Let σi\sigma^i be the initial faceted store, as in the function initial_store of the code: each secret variable xx gets ⟨si(x):d⟩\langle s_i(x) : d \rangle for a fixed default value dd, and each public variable gets si(x)s_i(x). If both faceted runs end, in σ1\sigma^1 and σ2\sigma^2, then πL\pi_L of the two final stores are equal. So the observer at LL, who sees the LL view, sees the same final store in both runs.

Proof. πL(σ1)\pi_L(\sigma^1) and πL(σ2)\pi_L(\sigma^2) both map each secret variable to dd and each public variable to its common value, so they are equal; call this store sLs_L. By Theorem 1, the LL views of both final stores are [ ⁣[c] ⁣](sL)[\![c]\!](s_L).

Transparency. By Theorem 1, the HH view of the final store is the result of the plain run on the true inputs, [ ⁣[c] ⁣](si)[\![c]\!](s_i), because πH(σi)=si\pi_H(\sigma^i) = s_i. If cc is termination-insensitive noninterferent and the faceted run ends, the plain runs from sis_i and from sLs_L both end. Since sis_i and sLs_L agree on the public variables, the LL view gives the same public values as the plain run on the true inputs.

Only termination-insensitive. The faceted run does not end when the HH view does not end. For "while h=1h = 1 do skip; l:=1l := 1", the run with h=1h = 1 does not end and the run with h=0h = 0 ends with l=1l = 1, so the observer at LL learns whether h=1h = 1 from termination. The theorems compare only runs that end, and the code, with its bound on the steps, returns no result in the same cases or more. ■\blacksquare

Complexity

The model is the word-RAM. Let aa and bb be the numbers of steps of the plain runs on the HH and LL views, and nn the number of nodes of the syntax tree. Each step of the faceted run is a step of at least one plain run (Theorem 1), so there are at most a+ba + b steps. A step evaluates at most one expression in both views, in time O(n)O(n). So the time is O((a+b)n)O((a + b) n), and O(an)O(a n) when the run never splits, since then a=ba = b and each step serves both views. Each variable holds at most two values, and the stack holds the pending parts of the program for the two views, O(n)O(n) entries. The extra space is O(n)O(n).

With more levels there are more views, and a value can have one facet for each view. In the worst case, when all views differ, the faceted run does the work of one plain run per view, as secure multi-execution does.

Properties

  • Sound for TINI. The public view of the final store depends only on the public inputs (Theorem 2).
  • Not termination-sensitive. The single run does not end when the HH view does not end. For "while h=1h = 1 do skip; l:=1l := 1", the public observer sees no result exactly when h=1h = 1. Secure multi-execution gives TSNI here.
  • No stops. Faceted execution never stops a run for security. Where no-sensitive-upgrade stops, it splits instead.
  • Transparent for TINI programs. If the program is TINI and the faceted run ends, the public observer sees the true public results.
  • Not complete. A TINI program whose run on the public view does not end, such as "while h=0h = 0 do skip; l:=1l := 1" with h=1h = 1 and d=0d = 0, gives no result, although the plain run ends.
  • Shared work. The parts of the run that do not depend on secrets run once for both views.

Variants and improvements

  • Many levels. Austin and Flanagan label each facet with a principal kk and write ⟨k?VH:VL⟩\langle k ? V_H : V_L \rangle. Facets nest, and the program counter is a set of branches, each "kk" or "not kk". A value then has a view for each set of principals, and the projection theorem holds for each view.
  • Secure multi-execution. Secure multi-execution runs one plain copy per level instead of one faceted run. It shares no work, but its public copy does not wait for the secret one, so it is TSNI. Bielova and Rezk (2016) compare the two methods and show that, in their original forms, secure multi-execution gives the stronger guarantee.
  • No-sensitive-upgrade. No-sensitive-upgrade is the one-view form: it keeps a label instead of a second value and stops where faceted execution would split.
  • Faceted values for policies. Faceted values have also been used to enforce privacy policies in languages where a value shows different data to different users; this page does not cover those languages.

When to use it

Use faceted execution when the program is known only at run time, stops for security are not acceptable, and most of the program does not depend on secrets, so that the shared run saves work over secure multi-execution. Use secure multi-execution when the termination channel matters. Use no-sensitive-upgrade when a stop is acceptable and you want the smallest cost. Use the security type system when the program is known in advance. Like the others, faceted execution does not protect against the running time of the program; see covert channels.

Pitfalls

  • Both views at line L6. Writing "σ(x)←v\sigma(x) \leftarrow v" under the program counter HH changes the LL view too. For "if hh then l:=1l := 1 else skip" and h=1h = 1, the public view of ll becomes 1, and with h=0h = 0 it keeps its old value, so it copies a bit of hh. The right line L6 keeps the LL view of the old value, as line L7 keeps the HH view.
  • No split at line L10. Choosing the branch by the HH view alone and running it with the program counter none makes each assignment in it change both views, which is the plain run with its leaks. The right line L10 splits when bH≠bLb_H \ne b_L, and line L11 gives each view its own arm.
  • The wrong view at line L12. Inside a split with the program counter HH, the condition must be read in the HH view. Reading bLb_L there makes the HH view follow the branches of the public view, and πH\pi_H is then not the plain run on the true inputs. The right line L12 uses bHb_H when p=Hp = H and bLb_L when p=Lp = L.
  • A default value from the secret. The value dd of the public facet of a secret input must be fixed in advance. A value computed from the secret makes the public view depend on it.
  • Expecting TSNI. The run does not end if either view does not end, so the public observer can learn about the secret from termination.

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.

faceted_execution.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/faceted-execution/. The authors are listed in prov/5EDZCZ.jsonl.

"""Faceted execution of a small while language with two levels, L and H.

Programs are nested tuples:

    expression: an int (a constant), a str (a variable), or (op, e1, e2)
                with op one of "+", "-", "*", "<", "=="
    command:    ("skip",)
                ("assign", x, e)
                ("seq", c1, c2)
                ("if", e, c1, c2)
                ("while", e, c)

Values are integers modulo MOD. A nonzero value is true. A faceted value
<V_H : V_L> is the pair Facet(high, low): an observer at H sees V_H and an
observer at L sees V_L. A plain int is a value that both observers see.
The program counter is None (no secret branch), "H" (a branch only the H
view takes) or "L" (a branch only the L view takes).
"""

from typing import NamedTuple, Optional, Union

Expr = Union[int, str, tuple]
Cmd = tuple

MOD = 256


class Facet(NamedTuple):
    high: int
    low: int


Value = Union[int, Facet]
FStore = dict[str, Value]


def make(high: int, low: int) -> Value:
    """Return <high : low>, or the plain int when the two views agree. Cost: O(1)."""
    return high if high == low else Facet(high, low)


def view(v: Value, side: str) -> int:
    """Return what the observer at side ("H" or "L") sees of v. Cost: O(1)."""
    if isinstance(v, Facet):
        return v.high if side == "H" else v.low
    return v


def project(store: FStore, side: str) -> dict[str, int]:
    """Return the plain store that the observer at side sees. Cost: O(size of store)."""
    return {x: view(v, side) for x, v in store.items()}


def _plain_eval(e: Expr, store: FStore, side: str) -> int:
    values: list[int] = []
    work: list[tuple[bool, Expr]] = [(False, e)]
    while work:
        done, f = work.pop()
        if done:
            b = values.pop()
            a = values.pop()
            op = f[0]
            if op == "+":
                values.append((a + b) % MOD)
            elif op == "-":
                values.append((a - b) % MOD)
            elif op == "*":
                values.append((a * b) % MOD)
            elif op == "<":
                values.append(int(a < b))
            elif op == "==":
                values.append(int(a == b))
            else:
                raise ValueError(f"unknown operator {op!r}")
        elif isinstance(f, int):
            values.append(f % MOD)
        elif isinstance(f, str):
            values.append(view(store[f], side))
        else:
            work.append((True, f))
            work.append((False, f[2]))
            work.append((False, f[1]))
    return values[0]


def evaluate(e: Expr, store: FStore) -> Value:
    """Return the faceted value of e: its value in each view, joined by make.

    Precondition: every variable of e is a key of store.
    Cost: O(size of e). Uses an explicit stack, no recursion.
    """
    return make(_plain_eval(e, store, "H"), _plain_eval(e, store, "L"))


def initial_store(s: dict[str, int], high: set[str], default: int = 0) -> FStore:
    """Give each variable in high the value <s(x) : default>. Cost: O(size of s)."""
    return {x: (make(v % MOD, default % MOD) if x in high else v % MOD) for x, v in s.items()}


def faceted_run(c: Cmd, store: FStore, fuel: int = 10_000) -> Optional[FStore]:
    """Run c once on a faceted store. Return the final store, or None after fuel steps.

    A branch on a value whose two views differ runs the taken arm of each
    view under the program counter of that view. An assignment under pc
    "H" changes only the H view of the target, and under "L" only the L
    view.
    Precondition: every variable of c is a key of store.
    Cost: at most fuel steps; a step costs O(1) plus two plain evaluations
    of its expression. The run takes at most the steps of the H view plus
    the steps of the L view.
    """
    sigma = dict(store)
    stack: list[tuple[Cmd, Optional[str]]] = [(c, None)]  # @line L1
    while stack:  # @line L2
        fuel -= 1
        if fuel < 0:
            return None
        d, pc = stack.pop()  # @line L3
        tag = d[0]
        if tag == "skip":
            continue
        if tag == "assign":  # @line L4
            v = evaluate(d[2], sigma)
            old = sigma[d[1]]
            if pc is None:
                sigma[d[1]] = v  # @line L5
            elif pc == "H":
                sigma[d[1]] = make(view(v, "H"), view(old, "L"))  # @line L6
            else:
                sigma[d[1]] = make(view(old, "H"), view(v, "L"))  # @line L7
        elif tag == "seq":  # @line L8
            stack.append((d[2], pc))
            stack.append((d[1], pc))
        elif tag in ("if", "while"):  # @line L9
            v = evaluate(d[1], sigma)
            th, tl = view(v, "H") != 0, view(v, "L") != 0
            if pc is None and th != tl:  # @line L10
                arms = [("L", tl), ("H", th)]  # @line L11
            else:
                arms = [(pc, tl if pc == "L" else th)]  # @line L12
            for p, taken in arms:
                if tag == "if":  # @line L13
                    stack.append((d[2] if taken else d[3], p))
                elif taken:  # @line L14
                    stack.append((d, p))
                    stack.append((d[2], p))
        else:
            raise ValueError(f"unknown command {tag!r}")
    return sigma  # @line L15
test_faceted_execution.py 235 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/faceted-execution/. The authors are listed in prov/5EDZCZ.jsonl.

import itertools
import random

from faceted_execution import (MOD, Facet, evaluate, faceted_run,
                               initial_store, make, project, view)

VARS = ["h", "l", "m"]
HIGH = {"h"}
DOMAIN = [0, 1, 2]
FUEL = 200


# Independent oracle: a recursive plain interpreter.

class OutOfFuel(Exception):
    pass


def o_eval(e, s):
    if isinstance(e, int):
        return e % MOD
    if isinstance(e, str):
        return s[e]
    a, b = o_eval(e[1], s), o_eval(e[2], s)
    return {"+": (a + b) % MOD, "-": (a - b) % MOD, "*": (a * b) % MOD,
            "<": int(a < b), "==": int(a == b)}[e[0]]


def o_exec(c, s, fuel):
    fuel[0] -= 1
    if fuel[0] < 0:
        raise OutOfFuel
    tag = c[0]
    if tag == "assign":
        s[c[1]] = o_eval(c[2], s)
    elif tag == "seq":
        o_exec(c[1], s, fuel)
        o_exec(c[2], s, fuel)
    elif tag == "if":
        o_exec(c[2] if o_eval(c[1], s) else c[3], s, fuel)
    elif tag == "while":
        if o_eval(c[1], s):
            o_exec(c[2], s, fuel)
            o_exec(c, s, fuel)


def o_run_steps(c, s, fuel=FUEL):
    s = dict(s)
    left = [fuel]
    try:
        o_exec(c, s, left)
    except OutOfFuel:
        return None, fuel
    return s, fuel - left[0]


def o_run(c, s, fuel=FUEL):
    return o_run_steps(c, s, fuel)[0]


def stores():
    for vals in itertools.product(DOMAIN, repeat=len(VARS)):
        yield dict(zip(VARS, vals))


def defaulted(s):
    return {x: (0 if x in HIGH else v) for x, v in s.items()}


def low(s):
    return tuple(s[x] for x in VARS if x not in HIGH)


def fac(c, s, fuel=2 * FUEL):
    return faceted_run(c, initial_store(s, HIGH), fuel)


def faceted_is_tini(c):
    seen = {}
    for s in stores():
        t = fac(c, s)
        if t is None:
            continue
        out = low(project(t, "L"))
        if seen.setdefault(low(s), out) != out:
            return False
    return True


def is_tini_plain(c):
    seen = {}
    for s in stores():
        t = o_run(c, s)
        if t is None:
            continue
        if seen.setdefault(low(s), low(t)) != low(t):
            return False
    return True


def rand_expr(rng, depth=0):
    r = rng.random()
    if depth >= 2 or r < 0.35:
        return rng.choice(VARS)
    if r < 0.5:
        return rng.randrange(3)
    return (rng.choice(["+", "-", "*", "<", "=="]),
            rand_expr(rng, depth + 1), rand_expr(rng, depth + 1))


def rand_cmd(rng, budget):
    if budget <= 1:
        return ("assign", rng.choice(VARS), rand_expr(rng)), 1
    r = rng.random()
    if r < 0.35:
        return ("assign", rng.choice(VARS), rand_expr(rng)), 1
    if r < 0.4:
        return ("skip",), 1
    if r < 0.65:
        c1, n1 = rand_cmd(rng, budget // 2)
        c2, n2 = rand_cmd(rng, budget - n1)
        return ("seq", c1, c2), n1 + n2
    if r < 0.88:
        c1, n1 = rand_cmd(rng, (budget - 1) // 2)
        c2, n2 = rand_cmd(rng, max(1, budget - 1 - n1))
        return ("if", rand_expr(rng), c1, c2), 1 + n1 + n2
    c1, n1 = rand_cmd(rng, budget - 1)
    return ("while", rand_expr(rng), c1), 1 + n1


def seq(*cs):
    out = cs[-1]
    for c in reversed(cs[:-1]):
        out = ("seq", c, out)
    return out


FENTON = seq(("assign", "l", 1), ("assign", "m", 1),
             ("if", "h", ("assign", "m", 0), ("skip",)),
             ("if", "m", ("assign", "l", 0), ("skip",)))


def test_worked_example():
    t = fac(FENTON, {"h": 1, "l": 5, "m": 5})
    assert t == {"h": Facet(1, 0), "l": Facet(1, 0), "m": Facet(0, 1)}
    assert project(t, "L") == {"h": 0, "l": 0, "m": 1}
    assert project(t, "H") == {"h": 1, "l": 1, "m": 0}
    # With h = 0 the two views agree and no facet is made.
    assert fac(FENTON, {"h": 0, "l": 5, "m": 5}) == {"h": 0, "l": 0, "m": 1}
    assert faceted_is_tini(FENTON)
    assert not is_tini_plain(FENTON)


def test_make_view_evaluate():
    assert make(3, 3) == 3
    assert make(3, 4) == Facet(3, 4)
    assert view(Facet(3, 4), "H") == 3 and view(Facet(3, 4), "L") == 4
    assert view(7, "L") == 7
    assert evaluate(("+", "h", "l"), {"h": Facet(2, 0), "l": 1}) == Facet(3, 1)
    assert evaluate(("*", "h", 0), {"h": Facet(2, 0)}) == 0
    assert evaluate(("-", 0, 1), {}) == MOD - 1


def test_explicit_flow():
    t = fac(("assign", "l", "h"), {"h": 2, "l": 1, "m": 0})
    assert t["l"] == Facet(2, 0)


def test_high_loop():
    # A loop on h runs only in the H view; the L view sees h = 0.
    prog = seq(("assign", "m", 0),
               ("while", "h", seq(("assign", "h", ("-", "h", 1)),
                                  ("assign", "m", ("+", "m", 1)))),
               ("assign", "l", ("+", "l", 1)))
    t = fac(prog, {"h": 2, "l": 4, "m": 9})
    assert t == {"h": 0, "l": 5, "m": Facet(2, 0)}


def test_high_divergence_hides_low_view():
    # If the H view does not end, the single run does not end, so the
    # result is TINI only.
    prog = seq(("while", ("==", "h", 1), ("skip",)), ("assign", "l", 1))
    assert fac(prog, {"h": 1, "l": 0, "m": 0}) is None
    assert fac(prog, {"h": 0, "l": 0, "m": 0}) == {"h": 0, "l": 1, "m": 0}
    assert faceted_is_tini(prog)


def test_inputs_unchanged_and_no_high():
    store = {"a": 1, "b": 2}
    t = faceted_run(("assign", "a", ("+", "a", "b")), store)
    assert t == {"a": 3, "b": 2} and store == {"a": 1, "b": 2}


def test_deep_program_no_recursion():
    prog = ("assign", "l", 0)
    for _ in range(3000):
        prog = ("seq", ("assign", "l", ("+", "l", "h")), prog)
    t = fac(prog, {"h": 1, "l": 0, "m": 0}, fuel=100_000)
    assert t["l"] == 0


def test_random_projection_tini_transparency():
    rng = random.Random(2012)
    tini_programs = 0
    for _ in range(500):
        prog, _n = rand_cmd(rng, rng.randint(1, 10))
        plain = {}
        for s in stores():
            plain[tuple(s.values())] = o_run_steps(prog, s, 2 * FUEL)
        seen = {}
        tini = True
        for s in stores():
            th, _k = plain[tuple(s.values())]
            if th is not None and seen.setdefault(low(s), low(th)) != low(th):
                tini = False
        tini_programs += tini
        seen = {}
        for s in stores():
            th, kh = plain[tuple(s.values())]
            tl, kl = plain[tuple(defaulted(s).values())]
            t = fac(prog, s)
            if t is None:
                # The single run takes at most the steps of both views.
                assert th is None or tl is None or kh + kl > 2 * FUEL
                continue
            assert project(t, "H") == th, (prog, s)
            assert project(t, "L") == tl, (prog, s)
            out = low(project(t, "L"))
            assert seen.setdefault(low(s), out) == out, (prog, s)
            if tini:
                assert out == low(th), (prog, s)
    assert tini_programs >= 100

History

Austin and Flanagan (2009) had shown that the purely dynamic no-sensitive-upgrade monitor gives TINI, at the price of stops on secure programs. Devriese and Piessens (2010) avoided the stops with secure multi-execution, at the price of one run per level. Austin and Flanagan (2012) combined the two ideas: faceted values simulate the runs of all levels in one run and split only where the runs differ, and the projection theorem shows that each view is a plain run. Bielova and Rezk (2016) compared faceted execution and secure multi-execution in detail.

References

  1. Thomas H. Austin and Cormac Flanagan, Multiple facets for dynamic information flow, Proceedings of the 39th ACM SIGPLAN-SIGACT Symposium on Principles of Programming Languages (POPL 2012), pp. 165 to 178, faceted values, the semantics of branches and assignments under a program counter of branches, the projection theorem and termination-insensitive noninterference
  2. Nataliia Bielova and Tamara Rezk, Spot the difference, secure multi-execution and multiple facets, ESORICS 2016, LNCS 9878, pp. 501 to 519, the comparison of faceted execution with secure multi-execution
  3. Dominique Devriese and Frank Piessens, Noninterference through secure multi-execution, Proceedings of the 2010 IEEE Symposium on Security and Privacy, pp. 109 to 124, the method that faceted execution simulates in one run
  4. Thomas H. Austin and Cormac Flanagan, Efficient purely-dynamic information flow analysis, Proceedings of the 4th ACM SIGPLAN Workshop on Programming Languages and Analysis for Security (PLAS 2009), pp. 113 to 124, the no-sensitive-upgrade monitor that faceted execution makes more permissive

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.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