Algorithm Search⌘K

Data structureintro

Capability list

Also called c-list, capability-based access control.

Stores the access matrix by row, so that each subject holds unforgeable tokens that name an object and the rights on it.

Time
O(1) worst
Space
Θ(n + s) extra
Where
n = the number of capabilities; o = the number of objects; r = the number of rights; s = the number of subjects
Properties
not concurrentnot externalnot persistent

A capability list (c-list) stores the access control matrix by row: each subject holds a list of capabilities, and each capability names one object and a set of rights on it. To use an object, a subject presents a capability from its own list; the system checks that the capability names the object and holds the right. A capability must be unforgeable, so the system keeps the lists and a subject names a capability only by its position, its slot, in its own list. Dennis and Van Horn (1966) introduced the idea. Capabilities make "what can this subject use?" cheap, and make it easy to pass a right, or only part of it, from one program to another. "Who can use this object?" and revocation are the hard part, which the access control list, the column view, makes easy.

In plain words

Think of the keys on a key ring. Each key opens one door, and some keys only let you look, not change things. A guard does not ask who you are; you show a key, and the guard checks that it fits this door. Keys are made by a locksmith that nobody can copy, so you cannot cut your own.

You can give a friend a copy of one of your keys, or a weaker copy that only lets them look. You cannot make a copy that does more than your own key does.

Taking keys back is harder. The locksmith keeps a record of who copied which key from whom. To take back a key, the locksmith takes it and every copy made from it, and copies of those copies, wherever they are.

The abstract type

A capability system stores a protection state (S,O,A)(S, O, A). Each subject ss has a c-list, a table of numbered slots. A slot holds a capability (o,T)(o, T) with o∈Oo \in O and T⊆RT \subseteq R. The matrix is the union over the row: A[s,o]A[s, o] is the union of the sets TT of the capabilities (o,T)(o, T) in the c-list of ss. The operations are:

  • CREATE(s,o,T)(s, o, T): the system gives ss a new capability (o,T)(o, T), for example when ss creates oo, and returns its slot.
  • CHECK(s,i,o,r)(s, i, o, r): true when slot ii of ss holds a capability for oo with rr in its rights.
  • DELEGATE(s,i,t,T)(s, i, t, T): give tt a copy of the capability in slot ii of ss, with the rights TT; refuse if TT is not a subset of its rights.
  • REVOKE(s,i)(s, i): remove the capability in slot ii of ss and every capability that was copied from it, directly or through other copies.
  • SLOTS(s)(s): the c-list of ss, which is the row of ss.

The request names a slot, not only an object. This is the difference from the matrix test r∈A[s,o]r \in A[s, o]: a subject uses the authority it chooses to present, and nothing else. A subject that holds two capabilities for oo uses one of them at a time.

Representation

The system holds two tables, out of reach of the subjects:

  • for each subject ss, its c-list: a map from slot numbers to capability records, as an array or a hash table;
  • for each capability record cc: its holder and slot, its object obj(c)\mathrm{obj}(c), its rights rights(c)\mathrm{rights}(c) as a bit mask of rr bits, its parent (the capability it was copied from, or none for a root), and the set of its children.

The parent links form a forest, the derivation tree: each root comes from CREATE, and each other node from one DELEGATE. The seL4 kernel keeps such a tree and calls it the capability derivation tree.

Invariant (C). (C1) Each record is in exactly one slot, the slot of its holder that it names. (C2) The parent of each record is a stored record, with the same object, and the rights of the record are a subset of the rights of its parent (attenuation). (C3) The children of each record are exactly the records whose parent it is. Slot numbers of a subject are never reused, so an old slot number can never name a new capability.

Operations

  1. CREATE(s, o, T)
  2. 1T ← T as a set of rights
  3. 2put a new root (o, T) in the next slot of the c-list of s; return the slot
  4. CHECK(s, i, o, r)
  5. 3if slot i of s is empty then return false
  6. 4(o', T') ← the capability in slot i of s
  7. 5return o' = o and r ∈ T'
  8. DELEGATE(s, i, t, T)
  9. 6if slot i of s is empty then return none
  10. 7c ← the capability in slot i of s
  11. 8if T ⊄ rights(c) then return none ▷ a copy never gains rights
  12. 9put a new child (obj(c), T) of c in the next slot of t; return the slot
  13. REVOKE(s, i)
  14. 10if slot i of s is empty then return 0
  15. 11stack ← [the capability in slot i of s]; detach it from its parent
  16. 12while stack is not empty do
  17. 13c ← pop stack; push the children of c
  18. 14clear the slot of c in the c-list of its holder

Create. Lines L1 and L2 make a root of the derivation tree. Which subject may call CREATE is policy, outside the structure: usually the system calls it when a subject creates a new object, with all rights.

Check. Line L3 denies an empty slot, so a guessed slot number gives nothing. Lines L4 and L5 test the object and the right of the one capability that the subject presented. Both steps are one lookup, O(1)O(1) time with an array c-list. The check needs no identity of the subject beyond whose c-list to read; the system knows that, because it runs the subject.

Delegate. Line L8 is attenuation: the new rights must be a subset of the rights of the capability that is copied. With rights as a bit mask the test is one AND, O(1)O(1) time. Line L9 links the copy to its parent, which REVOKE needs later. The receiver tt gets a new slot number in its own c-list; the slot number of ss means nothing to tt.

Revoke. Lines L11 to L14 are a depth-first search of the subtree of the derivation tree under the revoked capability, and they clear each slot they visit. Each capability has one parent, so it is pushed once, and the time is linear in the number of capabilities removed. This REVOKE also removes the capability itself; seL4 splits the two steps, and its revoke removes only the copies and keeps the capability that it is called on.

Example

Take the matrix of the access control matrix page. The system creates three roots: alice gets f1 with {own, r, w}, and bob gets f2 with {own, r, w} and the printer p with {w}. Then the owners delegate: alice gives bob r on f1, bob gives alice and carol r on f2, and bob gives carol w on p. The c-lists are the rows of the matrix:

subject slot object rights parent
alice 0 f1 own, r, w root
alice 1 f2 r bob slot 0
bob 0 f2 own, r, w root
bob 1 p w root
bob 2 f1 r alice slot 0
carol 0 f2 r bob slot 0
carol 1 p w bob slot 1

CHECK(carol, 1, p, w) is true. CHECK(carol, 0, p, w) is false: slot 0 holds a capability for f2, not for p, so carol cannot use her right on f2 to print. DELEGATE(carol, 0, alice, {w}) returns none, because {w} is not a subset of {r}.

Now carol passes her copy on: DELEGATE(carol, 0, alice, {r}) puts a copy of a copy in alice slot 2. Bob then calls REVOKE(bob, 0). The search starts at bob slot 0, finds its children alice slot 1 and carol slot 0, and under carol slot 0 it finds alice slot 2. It clears all four slots and returns 4. After this nobody holds a capability for f2, alice has only slot 0, and carol has only slot 1. A later CHECK(alice, 2, f2, r) is false, and slot 2 of alice is never used again.

The question "who can use f2?" needs a scan of all c-lists, or of the derivation tree under all roots for f2. Here it is alice, bob and carol before the revoke, and nobody after it.

Correctness

Invariant (C) holds after each operation: CREATE adds a root, DELEGATE adds a child with a subset of its parent's rights, and REVOKE removes a whole subtree, so no stored record has a removed parent. By induction on (C2), the rights of every capability are a subset of the rights of the root it comes from, and each root was made by CREATE. So a subject can hold a right on an object only through a chain of delegations from a capability that the system created; this is the precise sense of "unforgeable" here. CHECK returns true exactly when the presented slot holds a capability for the object with the right. REVOKE removes exactly the capability and its descendants, which is the set of capabilities that would not exist if the revoked one had never been made. The full proof is in the correctness proof.

Proof: Capability lists keep attenuation, and revocation removes exactly the derived copiesfull

A state is a finite set CC of capability records. Each record cc has a holder h(c)h(c), a slot σ(c)\sigma(c), an object obj(c)\mathrm{obj}(c), a set of rights rights(c)⊆R\mathrm{rights}(c) \subseteq R, a parent p(c)∈C∪{⊥}p(c) \in C \cup \{\bot\}, and a set of children ch(c)\mathrm{ch}(c). The c-list of ss maps each slot ii to the record cc with h(c)=sh(c) = s and σ(c)=i\sigma(c) = i, if there is one. Each record also has a number id(c)\mathrm{id}(c), given in the order of creation.

Invariant (C):

  • (C1) The map from records to pairs (h(c),σ(c))(h(c), \sigma(c)) is one to one, and the c-lists hold exactly these pairs.
  • (C2) For each cc with p(c)≠⊥p(c) \ne \bot: p(c)∈Cp(c) \in C, obj(c)=obj(p(c))\mathrm{obj}(c) = \mathrm{obj}(p(c)), rights(c)⊆rights(p(c))\mathrm{rights}(c) \subseteq \mathrm{rights}(p(c)), and id(p(c))<id(c)\mathrm{id}(p(c)) < \mathrm{id}(c).
  • (C3) For each cc: ch(c)={d∈C:p(d)=c}\mathrm{ch}(c) = \{d \in C : p(d) = c\}.

The matrix that the state stands for is M(C)[s,o]=⋃{rights(c):c∈C,h(c)=s,obj(c)=o}M(C)[s, o] = \bigcup \{\mathrm{rights}(c) : c \in C, h(c) = s, \mathrm{obj}(c) = o\}.

Lemma 1 (the parent links form a forest). Under (C2), following parent links from any record ends at a root, a record with p=⊥p = \bot, after finitely many steps.

Proof. Each step strictly decreases the id, by (C2), and ids are natural numbers. Each parent is in CC by (C2), so the walk stays in CC until it reaches a record with no parent. □\square

Write root(c)\mathrm{root}(c) for this root, and D(c)D(c) for the set of descendants of cc together with cc: the records whose walk passes through cc.

Lemma 2 (CREATE and DELEGATE keep (C)). Each of them adds one record and changes nothing else except one children set.

Proof. Line L2 stores a record with p=⊥p = \bot in a new slot of ss. The slot counter of ss only grows, so the pair (s,σ)(s, \sigma) is new and (C1) holds; (C2) and (C3) say nothing new about a root. Line L9 is reached only after line L6 found a record cc in slot ii of ss and line L8 checked T⊆rights(c)T \subseteq \mathrm{rights}(c). It stores a record dd with obj(d)=obj(c)\mathrm{obj}(d) = \mathrm{obj}(c), rights(d)=T\mathrm{rights}(d) = T, p(d)=cp(d) = c, a new slot of tt and a new id larger than every stored id, and adds dd to ch(c)\mathrm{ch}(c). So (C1) holds as before, (C2) holds for dd, and (C3) holds for cc and for dd, which has no children yet. If line L6 or L8 returns none, nothing changes. □\square

Lemma 3 (REVOKE removes exactly D(c)D(c)). Let slot ii of ss hold cc. Then REVOKE(s,i)(s, i) removes exactly the records of D(c)D(c), clears their slots, keeps (C), and returns ∣D(c)∣|D(c)|.

Proof. Line L11 removes cc from ch(p(c))\mathrm{ch}(p(c)) if cc has a parent, and starts the stack with cc. Each round of lines L13 and L14 pops a record, pushes its children and clears its slot. By (C3) the children pushed are exactly the records whose parent is the popped one. So every record pushed is in D(c)D(c), and by induction on the length of the walk from a record of D(c)D(c) up to cc, every record of D(c)D(c) is pushed. A record has one parent, so it is in one children set and is pushed at most once; by Lemma 1 there are no cycles, so the loop of line L12 ends after ∣D(c)∣|D(c)| rounds, and the count is ∣D(c)∣|D(c)|.

After the loop, the records left are C∖D(c)C \setminus D(c). (C1) holds because the slots of the removed records were cleared and no other slot changed. For (C2), take a record dd that is left with p(d)≠⊥p(d) \ne \bot. If p(d)∈D(c)p(d) \in D(c), then d∈D(c)d \in D(c) by the definition of DD, which is not the case; so p(d)p(d) is left, and the other conditions of (C2) did not change. For (C3), the only children set that held a removed record and belongs to a record that is left is ch(p(c))\mathrm{ch}(p(c)), and line L11 removed cc from it. If slot ii of ss is empty, line L10 returns 0 and nothing changes. □\square

Theorem 1 (attenuation, and no forgery). In every state reached from the empty state, every record cc has obj(c)=obj(root(c))\mathrm{obj}(c) = \mathrm{obj}(\mathrm{root}(c)) and rights(c)⊆rights(root(c))\mathrm{rights}(c) \subseteq \mathrm{rights}(\mathrm{root}(c)), and the root was made by a call of CREATE. So r∈M(C)[s,o]r \in M(C)[s, o] only if a call CREATE(s′,o,T)(s', o, T) with r∈Tr \in T was made, and a chain of DELEGATE calls led from it to a record held by ss.

Proof. The empty state holds (C). By Lemmas 2 and 3 every reachable state holds (C); CHECK changes nothing. Apply (C2) along the walk of Lemma 1: the object stays the same at each step and the set of rights can only grow toward the root, and ⊆\subseteq is transitive. A root is made only by line L2, and each other record only by line L9, which is a DELEGATE call from the holder of its parent. □\square

Theorem 2 (CHECK). CHECK(s,i,o,r)(s, i, o, r) returns true exactly when slot ii of ss holds a record cc with obj(c)=o\mathrm{obj}(c) = o and r∈rights(c)r \in \mathrm{rights}(c).

Proof. Line L3 returns false for an empty slot. Otherwise, by (C1), slot ii names one record, and lines L4 and L5 return the stated test on it. □\square

Theorem 3 (the oracle of the tests). Keep every record ever made, with a flag for each record on which REVOKE was called. Call a record live when neither it nor any ancestor has the flag. Then the stored set CC is exactly the set of live records.

Proof. By induction on the operations. CREATE and DELEGATE add a record with no flag whose parent, if any, is stored and so live by the hypothesis; both sides gain the same record. REVOKE on the record cc sets the flag of cc, which makes exactly D(c)D(c) not live, among the records that were live: a live record loses its status only if cc is on its walk to the root. By Lemma 3, REVOKE removes exactly D(c)D(c). A REVOKE on an empty slot changes neither side, because an empty slot names no live record. □\square

Termination and cost. CREATE, CHECK and DELEGATE run no loop; each does a constant number of table operations and, in line L8, one subset test, which is one word operation when the rights fit in a word. REVOKE runs ∣D(c)∣|D(c)| rounds by Lemma 3, each with a constant number of table operations plus the pushes of the children, and each record is pushed once, so the total is O(∣D(c)∣)O(|D(c)|). ■\blacksquare

Complexity

The model is the word RAM, with the rights of a capability in one word, and the c-lists as arrays indexed by slot. With hash tables for the c-lists, the times below are expected times.

operation time
CREATE O(1)O(1)
CHECK O(1)O(1)
DELEGATE O(1)O(1)
REVOKE O(k)O(k) for kk capabilities removed, at most O(n)O(n)
SLOTS (one row) O(length of the c-list)O(\text{length of the c-list})
holders of one object (one column) O(n)O(n), a scan of all c-lists
space Θ(n+s)\Theta(n + s) records

Revocation is cheap here because the derivation tree is kept. Without it, as in a system where capabilities are bit strings that a subject can copy freely, revocation needs a scan of every c-list, or it is not possible at all.

Variants

  • Protection in hardware. The machine keeps capabilities in segments that only special instructions can write, as the CAP computer at Cambridge did, or it marks each word that holds a capability with a tag bit that only those instructions can set, as the CHERI architecture does. Then a program can keep capabilities in its own memory and still cannot forge one.
  • Sparse capabilities. A capability is a bit string that holds the object name, the rights and a secret check field, for example a message authentication code of the other fields under a key of the server. A subject can store and send it as plain data, and forgery is as hard as guessing the check field. Such capabilities can be copied without the system knowing, so revocation needs a new key or a new object.
  • Revocation by indirection. Redell and Fabry proposed to give out a capability that points to an indirect object, which points to the real one. The owner revokes all copies at once by destroying the indirect object, with no derivation tree. This is selective: each holder can get a separate indirect object.
  • Amplification. Some systems let a trusted procedure add rights to a capability that it receives, for example to read the inside of an abstract data type. This is the controlled exception to line L8.
  • File descriptors. An open file descriptor in Unix works as a capability: it is an index into a table that the kernel holds, and it can be passed to another process. Capability modes of operating systems build on this.
  • Object capabilities. In a memory-safe language, a reference to an object is a capability for its methods. A program can only use what it was given, which makes the principle of least privilege a matter of what references a module gets.

When to use it

Use capabilities when rights must move between programs at run time, and when each program should run with only the rights it was handed. They avoid the confused deputy of Hardy (1988): a compiler that had the right to write a billing file was asked by a user to write its output to a file with the name of that billing file, and it did, because its own authority allowed it. With capabilities the user passes a capability for the output file, and the compiler writes only through it, so it cannot use its own right by mistake. Use access control lists instead when owners must review and change who can use each object, when the main audit question is "who can read this file?", or when revocation must be immediate and simple.

Pitfalls

  • Forgeable names. If a capability is a plain object name or an address that a subject can write, anyone can make one. The slot number of line L3 is safe only because the table is out of reach of the subject; a sparse capability is safe only if the check field is long and secret.
  • No attenuation test. If line L8 is left out, DELEGATE can make a copy with more rights than its parent, and any holder of a read capability can give itself a write capability.
  • Reused slot numbers. If a revoked slot is filled again with a new capability, a program that still holds the old number gets the new authority. This code never reuses a slot number; a system that does must make sure no stale number can be presented.
  • Revocation without the tree. Without parent links, REVOKE removes only one copy and the others stay. The holder may also have passed copies through channels that the system does not see, so plan revocation before handing out capabilities.
  • Confinement. Capabilities control which objects a program can use, but not where the information it reads goes. A program that holds a capability for a secret file and one for a public channel can copy the one to the other; this is the confinement problem.

Implementations

The Python class keeps a hash table of slots for each subject and a record for each capability with its parent and its children. It never reuses slot numbers, and it gives views of the rows, the matrix and the holders of one object. The tests compare it with an oracle that keeps every capability ever made and a flag for each explicit revoke, and treats a capability as live when it and all its ancestors are not revoked; they run random sequences of create, delegate, revoke and check.

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.

capability_list.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/capability-list/. The authors are listed in prov/P22TZC.jsonl.

"""Capability lists: the access matrix stored by row (Dennis and Van Horn 1966).

Each subject has a c-list, a table of slots. A slot holds a capability: an
object name, a set of rights, and a link to the capability it was copied
from. The table is held by the system, and a subject names a capability
only by a slot number of its own c-list, so a subject cannot forge one.
A copy never has more rights than its parent (attenuation), and revoking
a capability also removes every copy made from it (a derivation tree).
"""

from collections.abc import Hashable, Iterable
from dataclasses import dataclass, field

Subject = Hashable
Obj = Hashable
Right = Hashable


@dataclass
class Capability:
    """One capability, as the system stores it."""

    holder: Subject
    slot: int
    obj: Obj
    rights: frozenset[Right]
    parent: int | None
    children: set[int] = field(default_factory=set)


class CapabilityList:
    """The c-lists of all subjects of one protection state.

    create, check and the slot lookup take O(1) expected time (hash tables
    for the c-lists). delegate takes O(r) time for the subset test, where r
    is the number of rights. revoke takes time linear in the number of
    capabilities it removes. Slot numbers of a subject are never reused.
    """

    def __init__(self) -> None:
        self._clist: dict[Subject, dict[int, int]] = {}
        self._caps: dict[int, Capability] = {}
        self._next_slot: dict[Subject, int] = {}
        self._next_id = 0

    def _store(self, holder: Subject, obj: Obj, rights: frozenset[Right], parent: int | None) -> int:
        slot = self._next_slot.get(holder, 0)
        self._next_slot[holder] = slot + 1
        cid = self._next_id
        self._next_id += 1
        self._caps[cid] = Capability(holder, slot, obj, rights, parent)
        self._clist.setdefault(holder, {})[slot] = cid
        if parent is not None:
            self._caps[parent].children.add(cid)
        return slot

    def _lookup(self, s: Subject, i: int) -> Capability | None:
        cid = self._clist.get(s, {}).get(i)
        return None if cid is None else self._caps[cid]

    # The operations of the main pseudocode block.

    def create(self, s: Subject, o: Obj, rights: Iterable[Right]) -> int:
        """The system gives s a root capability for o; return its slot."""
        frozen = frozenset(rights)  # @line L1
        return self._store(s, o, frozen, None)  # @line L2

    def check(self, s: Subject, i: int, o: Obj, r: Right) -> bool:
        """Return True when slot i of the c-list of s names o and holds right r."""
        cap = self._lookup(s, i)
        if cap is None:  # @line L3
            return False
        obj, rights = cap.obj, cap.rights  # @line L4
        return obj == o and r in rights  # @line L5

    def delegate(self, s: Subject, i: int, t: Subject, rights: Iterable[Right]) -> int | None:
        """Give t a copy of slot i of s with the given rights; return the new slot.

        Return None when the slot is empty or when the rights are not a
        subset of the rights of the capability.
        """
        cap = self._lookup(s, i)
        if cap is None:  # @line L6
            return None
        cid = self._clist[s][i]  # @line L7
        wanted = frozenset(rights)
        if not wanted <= cap.rights:  # @line L8
            return None
        return self._store(t, cap.obj, wanted, cid)  # @line L9

    def revoke(self, s: Subject, i: int) -> int:
        """Remove slot i of s and every capability copied from it; return how many."""
        if self._lookup(s, i) is None:  # @line L10
            return 0
        root = self._clist[s][i]
        parent = self._caps[root].parent
        if parent is not None:
            self._caps[parent].children.discard(root)
        stack = [root]  # @line L11
        removed = 0
        while stack:  # @line L12
            cid = stack.pop()  # @line L13
            cap = self._caps.pop(cid)
            stack.extend(cap.children)
            del self._clist[cap.holder][cap.slot]  # @line L14
            removed += 1
        return removed

    # Views of the state.

    def slots(self, s: Subject) -> list[tuple[int, Obj, frozenset[Right]]]:
        """Return the c-list of s as (slot, object, rights), by slot number."""
        out = []
        for slot, cid in sorted(self._clist.get(s, {}).items()):
            cap = self._caps[cid]
            out.append((slot, cap.obj, cap.rights))
        return out

    def rights(self, s: Subject, o: Obj) -> frozenset[Right]:
        """Return the cell A[s, o]: the union of the rights of the capabilities of s for o."""
        out: frozenset[Right] = frozenset()
        for _, obj, rights in self.slots(s):
            if obj == o:
                out |= rights
        return out

    def to_matrix(self) -> dict[tuple[Subject, Obj], frozenset[Right]]:
        """Return the nonempty cells of the access matrix that the c-lists give."""
        out: dict[tuple[Subject, Obj], frozenset[Right]] = {}
        for cap in self._caps.values():
            if cap.rights:
                key = (cap.holder, cap.obj)
                out[key] = out.get(key, frozenset()) | cap.rights
        return out

    def holders(self, o: Obj) -> list[Subject]:
        """Return the subjects that hold some capability for o. This scans every c-list."""
        return sorted({cap.holder for cap in self._caps.values() if cap.obj == o}, key=repr)

    def check_invariant(self) -> None:
        """Raise AssertionError unless the slots, parents and children agree."""
        seen = 0
        for s, table in self._clist.items():
            for slot, cid in table.items():
                cap = self._caps[cid]
                assert cap.holder == s and cap.slot == slot
                seen += 1
        assert seen == len(self._caps), "a capability without a slot"
        for cid, cap in self._caps.items():
            if cap.parent is not None:
                parent = self._caps.get(cap.parent)
                assert parent is not None, "a live copy of a removed capability"
                assert cid in parent.children
                assert cap.obj == parent.obj
                assert cap.rights <= parent.rights, "a copy with more rights than its parent"
            for child in cap.children:
                assert self._caps[child].parent == cid
test_capability_list.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/capability-list/. The authors are listed in prov/P22TZC.jsonl.

import itertools
import random

from capability_list import CapabilityList

SUBJECTS = ["alice", "bob", "carol"]
OBJECTS = ["f1", "f2", "p"]
RIGHTS = ["own", "r", "w"]

# The access matrix of the page example.
MATRIX = {
    ("alice", "f1"): frozenset({"own", "r", "w"}),
    ("alice", "f2"): frozenset({"r"}),
    ("bob", "f1"): frozenset({"r"}),
    ("bob", "f2"): frozenset({"own", "r", "w"}),
    ("bob", "p"): frozenset({"w"}),
    ("carol", "f2"): frozenset({"r"}),
    ("carol", "p"): frozenset({"w"}),
}


def build_example() -> tuple[CapabilityList, dict[str, int]]:
    c = CapabilityList()
    a1 = c.create("alice", "f1", {"own", "r", "w"})  # alice slot 0
    b2 = c.create("bob", "f2", {"own", "r", "w"})  # bob slot 0
    bp = c.create("bob", "p", {"w"})  # bob slot 1
    c.delegate("alice", a1, "bob", {"r"})  # bob slot 2
    c.delegate("bob", b2, "alice", {"r"})  # alice slot 1
    cr = c.delegate("bob", b2, "carol", {"r"})  # carol slot 0
    cp = c.delegate("bob", bp, "carol", {"w"})  # carol slot 1
    return c, {"a1": a1, "b2": b2, "bp": bp, "cr": cr, "cp": cp}


def test_page_example_rows() -> None:
    c, s = build_example()
    c.check_invariant()
    assert c.to_matrix() == MATRIX
    assert c.slots("carol") == [(0, "f2", frozenset({"r"})), (1, "p", frozenset({"w"}))]
    assert c.check("carol", 1, "p", "w")
    assert not c.check("carol", 0, "p", "w")  # slot 0 names f2, not p
    assert not c.check("carol", 0, "f2", "w")
    assert c.delegate("carol", 0, "alice", {"w"}) is None  # no amplification
    assert c.holders("f2") == ["alice", "bob", "carol"]


def test_page_example_revoke() -> None:
    c, s = build_example()
    d = c.delegate("carol", s["cr"], "alice", {"r"})  # alice slot 2, a copy of a copy
    assert d == 2
    assert c.revoke("bob", s["b2"]) == 4  # bob's f2, and the copies of alice, carol and alice
    c.check_invariant()
    assert c.slots("alice") == [(0, "f1", frozenset({"own", "r", "w"}))]
    assert c.slots("carol") == [(1, "p", frozenset({"w"}))]
    assert c.holders("f2") == []
    assert not c.check("alice", 2, "f2", "r")
    assert c.revoke("bob", s["b2"]) == 0


def test_edge_cases() -> None:
    c = CapabilityList()
    assert not c.check("alice", 0, "f1", "r")
    assert c.delegate("alice", 0, "bob", set()) is None
    assert c.revoke("alice", 0) == 0
    i = c.create("alice", "f1", set())
    assert c.slots("alice") == [(i, "f1", frozenset())]
    assert c.to_matrix() == {}
    j = c.create("alice", "f1", {"r"})
    k = c.delegate("alice", j, "alice", {"r"})
    assert c.rights("alice", "f1") == frozenset({"r"})
    assert c.revoke("alice", k) == 1
    assert c.check("alice", j, "f1", "r")
    assert c.create("alice", "f2", {"r"}) == 3  # slots are never reused
    c.check_invariant()


class Oracle:
    """Every capability ever made, with a flag for an explicit revoke."""

    def __init__(self) -> None:
        self.caps: list[dict] = []

    def live(self, k: int) -> bool:
        while k is not None:
            if self.caps[k]["revoked"]:
                return False
            k = self.caps[k]["parent"]
        return True

    def find(self, s: str, i: int) -> int | None:
        for k, cap in enumerate(self.caps):
            if cap["holder"] == s and cap["slot"] == i and self.live(k):
                return k
        return None

    def next_slot(self, s: str) -> int:
        return sum(1 for cap in self.caps if cap["holder"] == s)

    def add(self, s: str, o: str, rights: frozenset, parent: int | None) -> int:
        slot = self.next_slot(s)
        self.caps.append({"holder": s, "slot": slot, "obj": o, "rights": rights, "parent": parent, "revoked": False})
        return slot

    def matrix(self) -> dict:
        out: dict = {}
        for k, cap in enumerate(self.caps):
            if self.live(k) and cap["rights"]:
                key = (cap["holder"], cap["obj"])
                out[key] = out.get(key, frozenset()) | cap["rights"]
        return out


def random_rights(rng: random.Random) -> frozenset:
    return frozenset(r for r in RIGHTS if rng.random() < 0.5)


def test_random_operations_against_oracle() -> None:
    rng = random.Random(1966)
    for _ in range(600):
        c = CapabilityList()
        oracle = Oracle()
        for _ in range(rng.randint(0, 30)):
            op = rng.random()
            s, t, o = rng.choice(SUBJECTS), rng.choice(SUBJECTS), rng.choice(OBJECTS)
            i = rng.randint(0, 5)
            if op < 0.25:
                rights = random_rights(rng)
                assert c.create(s, o, rights) == oracle.add(s, o, rights, None)
            elif op < 0.6:
                rights = random_rights(rng)
                k = oracle.find(s, i)
                ok = k is not None and rights <= oracle.caps[k]["rights"]
                got = c.delegate(s, i, t, rights)
                if ok:
                    assert got == oracle.add(t, oracle.caps[k]["obj"], rights, k)
                else:
                    assert got is None
            elif op < 0.8:
                k = oracle.find(s, i)
                before = sum(1 for j in range(len(oracle.caps)) if oracle.live(j))
                if k is not None:
                    oracle.caps[k]["revoked"] = True
                after = sum(1 for j in range(len(oracle.caps)) if oracle.live(j))
                assert c.revoke(s, i) == before - after
            else:
                r = rng.choice(RIGHTS)
                k = oracle.find(s, i)
                want = k is not None and oracle.caps[k]["obj"] == o and r in oracle.caps[k]["rights"]
                assert c.check(s, i, o, r) == want
            c.check_invariant()
            assert c.to_matrix() == oracle.matrix()
        for s, i, o, r in itertools.product(SUBJECTS, range(6), OBJECTS, RIGHTS):
            k = oracle.find(s, i)
            want = k is not None and oracle.caps[k]["obj"] == o and r in oracle.caps[k]["rights"]
            assert c.check(s, i, o, r) == want

History

Dennis and Van Horn (1966) defined capabilities and the c-list of a computation as part of a design for a multiprogrammed system. Lampson (1971) showed that the c-lists are the rows of the access matrix. Hardware and operating systems with capabilities followed in the 1970s, among them Hydra at Carnegie Mellon and the CAP computer at Cambridge, and Fabry (1974) argued for capabilities as the general form of addresses. Saltzer and Schroeder (1975) compared them with access lists and named revocation as their main problem, and Redell and Fabry (1974) gave revocation by indirection. Hardy (1988) gave the confused deputy as the case that capabilities solve and access lists do not. The seL4 microkernel keeps a capability derivation tree for revocation.

References

  1. Jack B. Dennis and Earl C. Van Horn, Programming semantics for multiprogrammed computations, Communications of the ACM 9(3), 1966, pages 143 to 155 (capabilities, the capability list of a computation, and the meta-instructions that grant and remove them)
  2. Butler W. Lampson, Protection, Proceedings of the 5th Princeton Conference on Information Sciences and Systems, 1971, reprinted in ACM SIGOPS Operating Systems Review 8(1), 1974, pages 18 to 24 of the reprint (the access matrix, and the capability list of a domain as its row)
  3. Robert S. Fabry, Capability-based addressing, Communications of the ACM 17(7), 1974, pages 403 to 412 (capabilities as the names of segments, and their protection from forgery)
  4. Jerome H. Saltzer and Michael D. Schroeder, The protection of information in computer systems, Proceedings of the IEEE 63(9), 1975, pages 1278 to 1308, Section II (ticket-oriented protection, capabilities and the problem of revocation)
  5. David D. Redell and Robert S. Fabry, Selective revocation of capabilities, Proceedings of the IRIA International Workshop on Protection in Operating Systems, 1974, revocation by indirection through a capability that the owner can destroy
  6. Norm Hardy, The confused deputy, or why capabilities might have been invented, ACM SIGOPS Operating Systems Review 22(4), 1988, pages 36 to 38 (the compiler that writes over the billing file, and how capabilities avoid it)
  7. seL4 Reference Manual, Section 3.1.5 (the capability derivation tree) and Section 3.2 (deletion and revocation)
  8. Matt Bishop, Computer Security: Art and Science, second edition, Addison-Wesley, 2018, ISBN 9780321712332, Chapter 16, Section 16.2 (capabilities, their implementation, copying and amplifying, and revocation)

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)
WritingW4 complete
  • a review of the text: no review record reviews/P22TZC/text.yaml