Algorithm Search⌘K

Algorithmadvanced

No-sensitive-upgrade check

Also called NSU monitor.

A dynamic information flow monitor that stops a run when it assigns to a public variable under a secret branch, which gives termination-insensitive noninterference.

Time
O(t n) worst
Space
O(n) extra
Where
n = the number of nodes of the syntax tree of the program; t = the number of steps of the run
Properties
not completedeterministiconlineiterativesound
Origin
Thomas H. Austin, Cormac Flanagan, 2009

The no-sensitive-upgrade (NSU) check is a dynamic monitor for information flow. It runs the program, keeps a label for each variable and a label pcpc for the program counter, and changes the label of a variable at each assignment, so that a public variable can hold a secret for a while. It adds one rule: under a secret program counter, an assignment to a variable that is now public stops the run. This rule closes the implicit flows through branches that are not taken, which a monitor cannot see. Austin and Flanagan (2009) proved that the monitor gives termination-insensitive noninterference (TINI).

In plain words

The monitor watches the program while it runs. Each variable has a tag, public or secret, and the tag can change: copying a secret into a variable makes the variable secret. Inside an if or a while whose condition reads a secret, everything the program writes is marked secret, because the fact that the write happened tells something about the secret. The problem is the branch that did not run. If a secret branch would have changed a public variable but did not, that variable keeps its public tag, and its value still tells something about the secret. The monitor cannot see writes that did not happen. So it forbids the dangerous case in the branch that does run: a write to a public variable inside a secret branch stops the program. A program that is never stopped has public results that do not depend on the secrets.

The problem

The input is a program cc in a small while language (assignments x:=ex := e, sequences, if statements and while loops), a security lattice (L,≤,⊔,⊓)(\mathcal{L}, \le, \sqcup, \sqcap) in which ℓ1≤ℓ2\ell_1 \le \ell_2 means that information may flow from ℓ1\ell_1 to ℓ2\ell_2, an initial store ss and an initial label λ(x)\lambda(x) for each variable. The output is the final store and the final labels, or "stop" when the monitor stops the run. Write labλ(e)\mathrm{lab}_\lambda(e) for the join of λ(y)\lambda(y) over the variables yy of ee.

The goal is soundness: for each observer level ℓ\ell and each two initial stores that agree on the variables with λ(x)≤ℓ\lambda(x) \le \ell, if both monitored runs end normally, the observer sees the same final values. The observer sees a variable only if its final label is at most ℓ\ell. A security type system gives the same guarantee before the run, but with a fixed label for each variable.

The algorithm

The monitor runs the program with an explicit stack of pairs (command, label of the program counter). Each pair carries its own label, so the label of a branch ends when its last command ends.

  1. NSU-RUN(c, s, λ) ▷ the final (s, λ), or stop
  2. 1S ← a stack that holds the pair (c, ⊥)
  3. 2while S is not empty do
  4. 3(d, p) ← pop(S)
  5. 4if d = (x := e) then
  6. 5if p ≰ λ(x) then stop the run
  7. 6(v, k) ← the value and label of e in (s, λ); s(x) ← v
  8. 7λ(x) ← k ⊔ p
  9. 8if d = (d1; d2) then push (d2, p), then (d1, p)
  10. 9if d = (if e then d1 else d2) then (v, k) ← the value and label of e
  11. 10push (d1 if v ≠ 0 else d2, p ⊔ k)
  12. 11if d = (while e do d1) then (v, k) ← the value and label of e
  13. 12if v ≠ 0 then q ← p ⊔ k; push (d, q), then (d1, q)
  14. 13return (s, λ)

A skip command does nothing. Line L7 is the flow-sensitive part: the new label of xx is the label of the data, kk, joined with the label of the context, pp. So "l:=hl := h" makes ll secret, and a later "l:=0l := 0" at a public program counter makes it public again. Lines L10 and L12 raise the program counter label for the commands that a secret condition controls. Line L5 is the no-sensitive-upgrade check: when the program counter label is not below the current label of xx, line L7 would raise the label of xx on a secret path. The monitor would raise it in this run, but a run with a different secret could skip the branch and leave xx public. So the monitor stops instead.

Example

The example is the one of Fenton (1974). Take the two-point lattice L≤HL \le H, λ(l)=λ(m)=L\lambda(l) = \lambda(m) = L, λ(h)=H\lambda(h) = H and

c=(l:=1); (m:=1); (if h then m:=0 else skip); (if m then l:=0 else skip).c = (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}).

Without the check of line L5, the final public ll is 1 when h≠0h \ne 0 and 0 when h=0h = 0: a copy of one bit of hh. The table shows the run with h=1h = 1, after the two first assignments, which give l=m=1l = m = 1 with label LL.

step popped (d,p)(d, p) NSU without line L5
1 (if hh ..., LL) v=1v = 1, k=Hk = H, push (m:=0,H)(m := 0, H) the same
2 (m:=0,H)(m := 0, H) H≰λ(m)=LH \not\le \lambda(m) = L: stop m=0m = 0, λ(m)=H\lambda(m) = H
3 (if mm ..., LL) v=0v = 0, k=Hk = H, push (skip,H)(\mathtt{skip}, H)
4 (skip,H)(\mathtt{skip}, H) end: l=1l = 1, λ(l)=L\lambda(l) = L

With h=0h = 0, both monitors run "skip" at HH, then the second if at LL, since m=1m = 1 has label LL, and they end with l=0l = 0 and λ(l)=L\lambda(l) = L. So without line L5 the observer sees l=1l = 1 or l=0l = 0, which tells whether h≠0h \ne 0. With NSU, the observer sees l=0l = 0 or a stopped run. TINI compares only the runs that end, and there is one, so there is no leak in this sense. The stop itself is a signal; see Pitfalls.

Correctness

Theorem (Austin and Flanagan 2009). Hypotheses: the deterministic while language above; an observer at level ℓ\ell who sees the final value of each variable whose final label is at most ℓ\ell, and sees which variables are hidden. Statement: if two initial stores agree on each xx with λ(x)≤ℓ\lambda(x) \le \ell, and both monitored runs end normally at line L13, the observer sees the same final state.

The proof below uses two lemmas. Lemma 2 (confinement) says that a command run at a program counter label p≰ℓp \not\le \ell changes no variable whose label is at most ℓ\ell: line L5 stops each such write. This is where the check is needed. Lemma 3 is an induction on the two runs, with the program counter labels of the two runs either both at most ℓ\ell or both not. A secret branch may run different commands in the two runs, and Lemma 2 shows that neither run changes what the observer sees.

When the monitor ends normally, the final store is the store of the plain run, because the monitor only adds labels and tests. The theorem says nothing about runs that stop or do not end.

Proof: The no-sensitive-upgrade monitor is termination-insensitive noninterferentfull

We use the language and the pseudocode of the page. Labels are in a finite lattice (L,≤,⊔,⊓)(\mathcal{L}, \le, \sqcup, \sqcap) with least element ⊥\bot. A monitor state is a pair (s,λ)(s, \lambda) of a store and a label map. For an expression ee, labλ(e)\mathrm{lab}_\lambda(e) is the join of λ(y)\lambda(y) over the variables yy of ee.

Semantics. We write ⟨d,p,s,λ⟩⇓(t,μ)\langle d, p, s, \lambda \rangle \Downarrow (t, \mu) when the monitored run of command dd at program counter label pp from (s,λ)(s, \lambda) ends normally in (t,μ)(t, \mu), with these rules:

  • skip leaves the state unchanged.
  • x:=ex := e needs p≤λ(x)p \le \lambda(x); then t=s[x↦v]t = s[x \mapsto v] and μ=λ[x↦labλ(e)⊔p]\mu = \lambda[x \mapsto \mathrm{lab}_\lambda(e) \sqcup p], where vv is the value of ee in ss. If p≰λ(x)p \not\le \lambda(x) the run stops, and there is no derivation.
  • d1;d2d_1; d_2 runs d1d_1 and then d2d_2, both at pp.
  • if ee then d1d_1 else d2d_2 runs the branch chosen by the value of ee at p⊔labλ(e)p \sqcup \mathrm{lab}_\lambda(e).
  • while ee do d1d_1: if ee is false, nothing changes. If ee is true, with q=p⊔labλ(e)q = p \sqcup \mathrm{lab}_\lambda(e), it runs d1d_1 at qq and then the loop again at qq.

The loop of lines L2 to L12 is the stack form of these rules. Each stack entry holds a command and its program counter label. Line L8 pushes the two parts of a sequence with the label of the sequence, line L10 pushes the chosen branch with the raised label, and line L12 pushes the body and then the loop with the raised label. So the entries are popped in the order of the rules, each with the label the rules give it, and the run ends normally at line L13 exactly when there is a derivation. A stopped run or a run that does not end has no derivation.

Observation. Fix an observer level ℓ\ell. The observer of a final state (t,μ)(t, \mu) sees, for each variable xx, the value t(x)t(x) if μ(x)≤ℓ\mu(x) \le \ell, and a mark "hidden" otherwise. Two states are ℓ\ell-equivalent, (s1,λ1)∼(s2,λ2)(s_1, \lambda_1) \sim (s_2, \lambda_2), if for every variable xx: λ1(x)≤ℓ\lambda_1(x) \le \ell if and only if λ2(x)≤ℓ\lambda_2(x) \le \ell, and if both hold, s1(x)=s2(x)s_1(x) = s_2(x). So two final states look the same to the observer exactly when they are ℓ\ell-equivalent. The relation ∼\sim is an equivalence relation. Two labels p1,p2p_1, p_2 are ℓ\ell-equivalent, p1≈p2p_1 \approx p_2, if p1≤ℓp_1 \le \ell if and only if p2≤ℓp_2 \le \ell.

Theorem. Let Γ\Gamma be the initial label map and let s1=ℓs2s_1 =_\ell s_2 (they agree on every xx with Γ(x)≤ℓ\Gamma(x) \le \ell). If ⟨c,⊥,s1,Γ⟩⇓(t1,μ1)\langle c, \bot, s_1, \Gamma \rangle \Downarrow (t_1, \mu_1) and ⟨c,⊥,s2,Γ⟩⇓(t2,μ2)\langle c, \bot, s_2, \Gamma \rangle \Downarrow (t_2, \mu_2), then (t1,μ1)∼(t2,μ2)(t_1, \mu_1) \sim (t_2, \mu_2).

The start states are ℓ\ell-equivalent, since both use Γ\Gamma and the stores agree where Γ(x)≤ℓ\Gamma(x) \le \ell. So the theorem follows from Lemma 3 below with p1=p2=⊥p_1 = p_2 = \bot.

Lemma 1 (expressions). If (s1,λ1)∼(s2,λ2)(s_1, \lambda_1) \sim (s_2, \lambda_2), then labλ1(e)≈labλ2(e)\mathrm{lab}_{\lambda_1}(e) \approx \mathrm{lab}_{\lambda_2}(e), and if labλ1(e)≤ℓ\mathrm{lab}_{\lambda_1}(e) \le \ell, the value of ee is the same in s1s_1 and s2s_2.

Proof. A join is at most ℓ\ell exactly when each of its terms is. So labλi(e)≤ℓ\mathrm{lab}_{\lambda_i}(e) \le \ell exactly when λi(y)≤ℓ\lambda_i(y) \le \ell for every variable yy of ee, and by ℓ\ell-equivalence this condition is the same for i=1i = 1 and i=2i = 2. When it holds, s1(y)=s2(y)s_1(y) = s_2(y) for each such yy, so ee has the same value.

Lemma 2 (confinement). If p≰ℓp \not\le \ell and ⟨d,p,s,λ⟩⇓(t,μ)\langle d, p, s, \lambda \rangle \Downarrow (t, \mu), then for every variable xx: if λ(x)≤ℓ\lambda(x) \le \ell then μ(x)=λ(x)\mu(x) = \lambda(x) and t(x)=s(x)t(x) = s(x); and if λ(x)≰ℓ\lambda(x) \not\le \ell then μ(x)≰ℓ\mu(x) \not\le \ell. In particular (s,λ)∼(t,μ)(s, \lambda) \sim (t, \mu).

Proof. By induction on the derivation. Every command in the derivation runs at a label p′≥pp' \ge p, since the rules only raise the label; so p′≰ℓp' \not\le \ell. Consider an assignment x:=ex := e at p′p' in state (u,ν)(u, \nu). The check gives p′≤ν(x)p' \le \nu(x). If ν(x)≤ℓ\nu(x) \le \ell we would get p′≤ℓp' \le \ell, which is false; so ν(x)≰ℓ\nu(x) \not\le \ell, and the new label labν(e)⊔p′≥p′\mathrm{lab}_\nu(e) \sqcup p' \ge p' is also not below ℓ\ell. So an assignment changes only variables whose label is not below ℓ\ell, and keeps their label not below ℓ\ell. Each other rule is a composition of such steps, and the property is kept under composition.

Lemma 3 (main). Let (s1,λ1)∼(s2,λ2)(s_1, \lambda_1) \sim (s_2, \lambda_2) and p1≈p2p_1 \approx p_2. If ⟨d,p1,s1,λ1⟩⇓(t1,μ1)\langle d, p_1, s_1, \lambda_1 \rangle \Downarrow (t_1, \mu_1) and ⟨d,p2,s2,λ2⟩⇓(t2,μ2)\langle d, p_2, s_2, \lambda_2 \rangle \Downarrow (t_2, \mu_2), then (t1,μ1)∼(t2,μ2)(t_1, \mu_1) \sim (t_2, \mu_2).

Proof. By induction on the sum of the sizes of the two derivations, by the form of dd.

  1. skip. The states do not change.
  2. x:=ex := e. Both checks pass, since both runs end normally. Let ℓi=labλi(e)\ell_i = \mathrm{lab}_{\lambda_i}(e). The new labels are ℓi⊔pi\ell_i \sqcup p_i. If p1,p2≤ℓp_1, p_2 \le \ell, then ℓi⊔pi≤ℓ\ell_i \sqcup p_i \le \ell exactly when ℓi≤ℓ\ell_i \le \ell, which by Lemma 1 is the same for both runs; and when it holds, Lemma 1 gives the same value for xx. If p1,p2≰ℓp_1, p_2 \not\le \ell, both new labels are not below ℓ\ell, so xx is hidden in both states. The other variables do not change.
  3. d1;d2d_1; d_2. The hypothesis for d1d_1 gives ℓ\ell-equivalent middle states, and the hypothesis for d2d_2, with the same labels p1≈p2p_1 \approx p_2, gives the result.
  4. if ee then d1d_1 else d2d_2. Let ℓi=labλi(e)\ell_i = \mathrm{lab}_{\lambda_i}(e); by Lemma 1, ℓ1≈ℓ2\ell_1 \approx \ell_2. If ℓ1≤ℓ\ell_1 \le \ell, then ee has the same value in both runs, both run the same branch, and the labels pi⊔ℓip_i \sqcup \ell_i are ℓ\ell-equivalent (both are below ℓ\ell exactly when pi≤ℓp_i \le \ell). The hypothesis for the branch gives the result. If ℓ1≰ℓ\ell_1 \not\le \ell, then pi⊔ℓi≰ℓp_i \sqcup \ell_i \not\le \ell, and Lemma 2 applied to each run gives (ti,μi)∼(si,λi)(t_i, \mu_i) \sim (s_i, \lambda_i). By transitivity, (t1,μ1)∼(s1,λ1)∼(s2,λ2)∼(t2,μ2)(t_1, \mu_1) \sim (s_1, \lambda_1) \sim (s_2, \lambda_2) \sim (t_2, \mu_2).
  5. while ee do d1d_1. Let ℓi\ell_i be as above. If ℓ1≤ℓ\ell_1 \le \ell, then ee has the same value in both runs. If it is false, the states do not change. If it is true, both runs run d1d_1 and then the loop at qi=pi⊔ℓiq_i = p_i \sqcup \ell_i, and q1≈q2q_1 \approx q_2. The hypothesis for d1d_1 and then for the loop (a smaller derivation in each run) gives the result. If ℓ1≰ℓ\ell_1 \not\le \ell, a run with a false condition does not change its state, and a run with a true condition runs the body and the loop at qi≰ℓq_i \not\le \ell, so Lemma 2 gives (ti,μi)∼(si,λi)(t_i, \mu_i) \sim (s_i, \lambda_i). Transitivity gives the result as in case 4.

This proves Lemma 3 and so the theorem. The theorem compares only runs that end normally. A run that the monitor stops, or that does not end, is not compared, so the monitor is termination-insensitive: whether it stops can depend on a secret. ■\blacksquare

Complexity

The model is the word-RAM. Let tt be the number of steps of the run, one for each pop at line L3, and nn the number of nodes of the syntax tree. A step evaluates at most one expression, in time linear in its size, which is at most nn, and does O(1)O(1) joins and tests of labels. For a fixed finite lattice, or for labels that are sets of at most ww categories stored as one machine word, each join and test takes O(1)O(1) time. So the time is O(tn)O(t n), and O(t)O(t) when each expression has constant size. The plain run takes the same number of steps, so the monitor costs a constant factor. Each stack entry is a distinct pending part of the program, so the stack holds O(n)O(n) entries; the labels take one word for each variable. The extra space is O(n)O(n).

Properties

  • Sound for TINI. Each pair of runs that end is noninterferent (Correctness).
  • Not complete. The secure program "if hh then l:=0l := 0 else l:=0l := 0" is stopped, since ll is public and the program counter is HH.
  • Flow-sensitive. The label of a variable follows its current content. The program "l:=hl := h; l:=0l := 0" ends with ll public.
  • Transparent on the runs it does not stop. A run that ends normally has the same final store as the plain run.
  • Online. The monitor needs only the current state, not the rest of the program, so it works for code that is known only at run time.
  • Stopping is the only defense. The monitor never changes a value. It either lets a step run or stops the run.

Variants and improvements

  • Permissive upgrade. Austin and Flanagan (2010) replace the stop at line L5 by a mark: the variable gets a special "partially leaked" label, and the run stops only if the program later branches on such a value. This accepts more programs and keeps TINI.
  • Hybrid monitors. A static analysis of the branch that is not taken finds the variables it could write, and the monitor raises their labels too. Then line L5 is not needed for those variables. The survey of Sabelfeld and Russo (2009) compares such monitors with purely dynamic ones.
  • Secure multi-execution. Secure multi-execution runs the program once for each level and gives each run only the inputs it may see. It never stops a run and gives termination-sensitive noninterference, at the cost of one run per level.
  • Faceted execution. Faceted execution keeps a secret and a public value for each variable that a secret branch writes, and runs both branches only where they differ. On Fenton's program it gives the observer l=0l = 0 in both runs, where NSU stops.
  • Taint tracking. Taint analysis usually keeps only lines L6 and L7 without pp. It tracks explicit flows and misses implicit ones.

On Fenton's program with h=1h = 1 the three dynamic methods behave as follows.

method runs what the public observer gets
NSU 1 stop
secure multi-execution 2 l=0l = 0, from the run with hh replaced by a default value 0
faceted execution 1, split where the facets differ l=0l = 0, the public facet of ll

When to use it

Use NSU when the program is known only at run time, for example a script on a web page, and a stop is an acceptable answer to a possible leak. It needs one run and a small cost at each step. Use a security type system when the program is known in advance, because a static check costs nothing at run time and gives the same TINI guarantee for all inputs. Use secure multi-execution or faceted execution when false stops are not acceptable. NSU does not protect against the time a run takes or against the fact that it stops; see covert channels.

Pitfalls

  • No check at line L5. A monitor with only lines L6 and L7 is unsound. On Fenton's program it gives the public result l=1l = 1 when h≠0h \ne 0 and l=0l = 0 when h=0h = 0 (Example). The right line L5 stops the run when p≰λ(x)p \not\le \lambda(x).
  • No program counter at line L7. With "λ(x)←k\lambda(x) \leftarrow k", the program "if hh then h:=0h := 0 else skip" passes the check, since hh is secret, but gives hh the label LL when h≠0h \ne 0 and leaves it at HH when h=0h = 0. The observer learns whether h≠0h \ne 0 from the label. The right line L7 is "λ(x)←k⊔p\lambda(x) \leftarrow k \sqcup p".
  • The plain label at line L10 or L12. Pushing the branch with pp instead of p⊔kp \sqcup k accepts "if hh then l:=1l := 1 else l:=0l := 0", which copies hh to ll. The right lines push p⊔kp \sqcup k, and line L12 also pushes the loop itself with qq, so that each later test of the loop condition runs at the raised label.
  • A shared program counter. A single variable pcpc that is raised at line L10 and never lowered stops each later public assignment, and one that is lowered at the end of the if command lowers it before the branch has run. Keep the label in each stack entry, as in lines L8, L10 and L12.
  • Treating the stop as invisible. The stop at line L5 depends on the secret: in the Example, the run stops exactly when h≠0h \ne 0. If the observer sees that a run stops, NSU leaks through this channel, as each TINI method does. With public output during the run, Askarov et al. (2008) show that such a channel can reveal a secret of NN binary digits, but only in time exponential in NN; see TINI.

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.

no_sensitive_upgrade.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/no-sensitive-upgrade/. The authors are listed in prov/V9BYDH.jsonl.

"""A no-sensitive-upgrade (NSU) monitor for a small while language.

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 label is a
frozenset of category names, ordered by inclusion; the empty set is the
public level L. Each variable carries a label that changes at run time.
"""

from typing import Optional, Union

Label = frozenset
Expr = Union[int, str, tuple]
Cmd = tuple
Store = dict[str, int]
Labels = dict[str, Label]

MOD = 256
BOTTOM: Label = frozenset()


def evaluate(e: Expr, s: Store, lab: Labels) -> tuple[int, Label]:
    """Return the value of e in the store s and the join of the labels it reads.

    Precondition: every variable of e is a key of s and of lab.
    Cost: O(size of e). Uses an explicit stack, no recursion.
    """
    values: list[int] = []
    level: Label = BOTTOM
    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(s[f])
            level = level | lab[f]
        else:
            work.append((True, f))
            work.append((False, f[2]))
            work.append((False, f[1]))
    return values[0], level


def nsu_run(c: Cmd, s: Store, lab: Labels, fuel: int = 10_000) -> tuple[str, Optional[Store], Optional[Labels]]:
    """Run c under the no-sensitive-upgrade monitor.

    Returns ("ok", store, labels) when the run ends, ("stop", None, None)
    when the monitor stops the run, and ("diverge", None, None) when the
    run takes more than fuel steps. The inputs are not changed.
    Each work item carries its own program counter label, so the label of
    a branch ends when its last command ends.
    Precondition: every variable of c is a key of s and of lab.
    Cost: O(1) lattice operations per step plus the cost of the
    expressions; at most fuel steps.
    """
    s = dict(s)
    lab = dict(lab)
    stack: list[tuple[Cmd, Label]] = [(c, BOTTOM)]  # @line L1
    while stack:  # @line L2
        fuel -= 1
        if fuel < 0:
            return ("diverge", None, None)
        d, pc = stack.pop()  # @line L3
        tag = d[0]
        if tag == "skip":
            continue
        if tag == "assign":  # @line L4
            x = d[1]
            if not pc <= lab[x]:  # @line L5
                return ("stop", None, None)
            v, le = evaluate(d[2], s, lab)  # @line L6
            s[x] = v
            lab[x] = le | pc  # @line L7
        elif tag == "seq":  # @line L8
            stack.append((d[2], pc))
            stack.append((d[1], pc))
        elif tag == "if":  # @line L9
            v, le = evaluate(d[1], s, lab)
            stack.append((d[2] if v != 0 else d[3], pc | le))  # @line L10
        elif tag == "while":  # @line L11
            v, le = evaluate(d[1], s, lab)
            if v != 0:
                q = pc | le  # @line L12
                stack.append((d, q))
                stack.append((d[2], q))
        else:
            raise ValueError(f"unknown command {tag!r}")
    return ("ok", s, lab)  # @line L13


def observe(store: Store, lab: Labels, level: Label = BOTTOM) -> tuple[tuple[str, object], ...]:
    """Return what an observer at the given level sees of a final store.

    The observer sees the value of each variable whose label is below its
    level, and a "*" for every other variable.
    Cost: O(number of variables).
    """
    return tuple((x, store[x] if lab[x] <= level else "*") for x in sorted(store))
test_no_sensitive_upgrade.py 240 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/no-sensitive-upgrade/. The authors are listed in prov/V9BYDH.jsonl.

import itertools
import random

from no_sensitive_upgrade import MOD, evaluate, nsu_run, observe

L = frozenset()
H = frozenset({"h"})
LABELS = {"l": L, "m": L, "h": H}
VARS = ["h", "l", "m"]
DOMAIN = [0, 1, 2]
FUEL = 200


# Independent oracle: a recursive big-step form of the same monitor, with
# the same step count (one step per command that starts, and one step per
# test of a loop guard).

class Stop(Exception):
    pass


class OutOfFuel(Exception):
    pass


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


def o_exec(c, pc, s, lab, fuel, check=True):
    fuel[0] -= 1
    if fuel[0] < 0:
        raise OutOfFuel
    tag = c[0]
    if tag == "skip":
        return
    if tag == "assign":
        if check and not pc <= lab[c[1]]:
            raise Stop
        v, le = o_eval(c[2], s, lab)
        s[c[1]] = v
        lab[c[1]] = le | pc
    elif tag == "seq":
        o_exec(c[1], pc, s, lab, fuel, check)
        o_exec(c[2], pc, s, lab, fuel, check)
    elif tag == "if":
        v, le = o_eval(c[1], s, lab)
        o_exec(c[2] if v else c[3], pc | le, s, lab, fuel, check)
    elif tag == "while":
        v, le = o_eval(c[1], s, lab)
        if v:
            o_exec(c[2], pc | le, s, lab, fuel, check)
            o_exec(c, pc | le, s, lab, fuel, check)


def oracle(c, s, lab, fuel=FUEL, check=True):
    s, lab = dict(s), dict(lab)
    try:
        o_exec(c, frozenset(), s, lab, [fuel], check)
    except Stop:
        return ("stop", None, None)
    except OutOfFuel:
        return ("diverge", None, None)
    return ("ok", s, lab)


def plain(c, s, fuel=FUEL):
    r = oracle(c, s, {x: frozenset() for x in s}, fuel)
    return r[1]


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


def low_part(s):
    return tuple(s[x] for x in VARS if LABELS[x] == L)


def is_tini(run, c):
    seen = {}
    for s in stores():
        status, t, lab = run(c, s)
        if status != "ok":
            continue
        out = observe(t, lab)
        if seen.setdefault(low_part(s), out) != out:
            return False
    return True


def nsu(c, s):
    return nsu_run(c, s, LABELS, FUEL)


def naive(c, s):
    # A monitor that tracks labels but has no check at line L5.
    return oracle(c, s, LABELS, FUEL, check=False)


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


# The worked example: a flow through a branch that is not taken.
FENTON = seq(("assign", "l", 1), ("assign", "m", 1),
             ("if", "h", ("assign", "m", 0), ("skip",)),
             ("if", "m", ("assign", "l", 0), ("skip",)))


def test_worked_example():
    # With h = 0 the run ends and l = 0 is public.
    status, t, lab = nsu_run(FENTON, {"h": 0, "l": 5, "m": 5}, LABELS)
    assert status == "ok"
    assert t["l"] == 0 and lab["l"] == L
    assert lab["m"] == L
    # With h = 1 the assignment m := 0 runs under pc = H to a public m.
    assert nsu_run(FENTON, {"h": 1, "l": 5, "m": 5}, LABELS)[0] == "stop"
    assert is_tini(nsu, FENTON)


def test_naive_monitor_leaks():
    # Without the check of line L5 the final public l equals (h == 0).
    for hv, expect in [(0, 0), (1, 1), (2, 1)]:
        status, t, lab = naive(FENTON, {"h": hv, "l": 5, "m": 5})
        assert status == "ok" and t["l"] == expect and lab["l"] == L
    assert not is_tini(naive, FENTON)


def test_explicit_flow_upgrades_label():
    status, t, lab = nsu_run(("assign", "l", "h"), {"h": 2, "l": 0, "m": 0}, LABELS)
    assert status == "ok" and t["l"] == 2 and lab["l"] == H
    assert observe(t, lab) == (("h", "*"), ("l", "*"), ("m", 0))


def test_flow_sensitive():
    # A public variable may hold a secret for a while and then a public value.
    prog = seq(("assign", "l", "h"), ("assign", "l", 0))
    status, t, lab = nsu_run(prog, {"h": 2, "l": 1, "m": 0}, LABELS)
    assert status == "ok" and lab["l"] == L and t["l"] == 0


def test_secure_program_is_stopped():
    # The program is secure, but NSU stops it: NSU is not complete.
    prog = ("if", "h", ("assign", "l", 0), ("assign", "l", 0))
    assert nsu_run(prog, {"h": 1, "l": 0, "m": 0}, LABELS)[0] == "stop"
    assert all(plain(prog, s)["l"] == 0 for s in stores())


def test_high_target_under_high_pc():
    prog = ("if", "h", ("assign", "h", 0), ("skip",))
    status, t, lab = nsu_run(prog, {"h": 1, "l": 0, "m": 0}, LABELS)
    assert status == "ok" and t["h"] == 0 and lab["h"] == H


def test_pc_ends_with_branch():
    prog = seq(("if", "h", ("skip",), ("skip",)), ("assign", "l", 3))
    status, t, lab = nsu_run(prog, {"h": 1, "l": 0, "m": 0}, LABELS)
    assert status == "ok" and t["l"] == 3 and lab["l"] == L


def test_divergence_and_inputs_unchanged():
    s = {"h": 0, "l": 1, "m": 0}
    lab = dict(LABELS)
    assert nsu_run(("while", 1, ("skip",)), s, lab, fuel=50)[0] == "diverge"
    assert s == {"h": 0, "l": 1, "m": 0} and lab == LABELS


def test_evaluate():
    assert evaluate(("+", "l", ("*", "h", 2)), {"l": 1, "h": 3}, {"l": L, "h": H}) == (7, H)
    assert evaluate(("-", 0, 1), {}, {}) == (MOD - 1, L)


def test_deep_program_no_recursion():
    prog = ("assign", "l", 0)
    for _ in range(3000):
        prog = ("seq", ("assign", "l", ("+", "l", 1)), prog)
    status, t, _lab = nsu_run(prog, {"h": 0, "l": 0, "m": 0}, LABELS)
    assert status == "ok" and t["l"] == 0


def test_random_against_oracle_soundness_transparency():
    rng = random.Random(9512)
    ok_runs = 0
    for _ in range(500):
        prog, _n = rand_cmd(rng, rng.randint(1, 10))
        for s in stores():
            got = nsu(prog, s)
            assert got == oracle(prog, s, LABELS), (prog, s)
            if got[0] == "ok":
                ok_runs += 1
                assert got[1] == plain(prog, s)
        assert is_tini(nsu, prog), prog
    assert ok_runs > 1000

History

Fenton (1974) described the flow through a branch that is not taken, and the certification of Denning and Denning (1977), based on the lattice model, handled it statically. For a long time, it was widely held that dynamic monitors were unable to enforce noninterference, because they see only one run. Austin and Flanagan (2009) took the no-sensitive-upgrade rule, which they credit to the 2002 thesis of Zdancewic, gave it its name, and proved that a purely dynamic monitor with this rule gives TINI for a language with references. Their later papers give the permissive-upgrade variant (2010) and faceted values (2012). The survey of Sabelfeld and Russo (2009) places these monitors with respect to static analysis.

References

  1. 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 rule and the proof of termination-insensitive noninterference
  2. Thomas H. Austin and Cormac Flanagan, Permissive dynamic information flow analysis, Proceedings of the 5th ACM SIGPLAN Workshop on Programming Languages and Analysis for Security (PLAS 2010), pp. 1 to 12, the permissive-upgrade variant
  3. Andrei Sabelfeld and Alejandro Russo, From dynamic to static and back, riding the roller coaster of information-flow control research, Perspectives of Systems Informatics (PSI 2009), LNCS 5947, pp. 352 to 365, purely dynamic monitors and their comparison with static analysis
  4. 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, the comparison of no-sensitive-upgrade with faceted values
  5. J. S. Fenton, Memoryless subsystems, The Computer Journal 17(2), 1974, pp. 143 to 147, the example of a flow through a branch that is not taken

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