| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/ed25519" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/binary" |
| 9 | "fmt" |
| 10 | "sort" |
| 11 | "strings" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | const ( |
| 16 | // The algorithm identifier the note format prefixes a public key with, |
| 17 | // and the only algorithm this program renders (attest/sign.go). |
| 18 | algEd25519 = 1 |
| 19 | sshEd25519 = "ssh-ed25519" |
| 20 | |
| 21 | // The environment variable carrying the pushing key's principal name. |
| 22 | // One name, shared with nix/valley-host.nix — change it in both. |
| 23 | principalEnv = "VALLEY_PRINCIPAL" |
| 24 | |
| 25 | dateLayout = "2006-01-02" |
| 26 | ) |
| 27 | |
| 28 | const knownSignersHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8). |
| 29 | # Verifier keys whose attestations count, one per line: the name a key |
| 30 | # signs under, the note format's key hash over that name and key, and |
| 31 | # base64 of the algorithm byte and the raw ed25519 public key. |
| 32 | ` |
| 33 | |
| 34 | const authorizedKeysHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8). |
| 35 | # Keys that may push, each tagged with the principal it acts as. sshd puts |
| 36 | # the tag in the environment of the receive-pack the pre-receive hook runs |
| 37 | # under, which is what tells one pusher from another over a shared user. |
| 38 | ` |
| 39 | |
| 40 | const grantsHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8). |
| 41 | # Grants the pre-receive hook checks, one per line: the grant, then the |
| 42 | # principal holding it. A principal not named here holds none. |
| 43 | ` |
| 44 | |
| 45 | // grantRequest is the line a holder of a grant at a boundary of kind |
| 46 | // "request" is written under: the verb the hook checks (dcr-e544f20). |
| 47 | const grantRequest = "request" |
| 48 | |
| 49 | // artifacts is a whole compilation: every file, what was left out, and the |
| 50 | // counts the journal line reports. Nothing is written until every part of |
| 51 | // this exists, so a failure anywhere leaves the last good set intact. |
| 52 | type artifacts struct { |
| 53 | knownSigners []byte |
| 54 | authorizedKeys []byte |
| 55 | grants []byte |
| 56 | notes []string |
| 57 | signers int |
| 58 | authorized int |
| 59 | granted int |
| 60 | } |
| 61 | |
| 62 | // render turns a registry into every artifact as of one day. |
| 63 | func render(r registry, day time.Time) (artifacts, error) { |
| 64 | var a artifacts |
| 65 | var signers, authorized, granted []string |
| 66 | governed := false |
| 67 | |
| 68 | names := make([]string, 0, len(r.Principals)) |
| 69 | for name := range r.Principals { |
| 70 | names = append(names, name) |
| 71 | } |
| 72 | sort.Strings(names) |
| 73 | |
| 74 | for _, name := range names { |
| 75 | p := r.Principals[name] |
| 76 | |
| 77 | expired, err := hasExpired(p.Expires, day) |
| 78 | if err != nil { |
| 79 | return a, fmt.Errorf("%s: %w", name, err) |
| 80 | } |
| 81 | if expired { |
| 82 | a.notes = append(a.notes, fmt.Sprintf( |
| 83 | "%s expired %s: %d key(s) and every grant omitted from all artifacts", name, p.Expires, len(p.Keys))) |
| 84 | continue |
| 85 | } |
| 86 | |
| 87 | held, err := heldKinds(r, p) |
| 88 | if err != nil { |
| 89 | return a, fmt.Errorf("%s: %w", name, err) |
| 90 | } |
| 91 | governed = governed || held[boundaryRegistry] |
| 92 | pushes := held[boundaryGitPush] |
| 93 | if held[boundaryRequest] { |
| 94 | granted = append(granted, grantRequest+" "+name) |
| 95 | } |
| 96 | |
| 97 | for i, k := range p.Keys { |
| 98 | pub, err := sshEd25519Public(k.Public) |
| 99 | if err != nil { |
| 100 | return a, fmt.Errorf("%s: key %d: %w", name, i, err) |
| 101 | } |
| 102 | if k.Signs != "" { |
| 103 | signers = append(signers, verifierKey(k.Signs, pub)) |
| 104 | } |
| 105 | if pushes { |
| 106 | authorized = append(authorized, fmt.Sprintf("environment=%q %s", principalEnv+"="+name, k.Public)) |
| 107 | } |
| 108 | } |
| 109 | } |
| 110 | |
| 111 | // The state the whole render is refused for: after the expiry cut, |
| 112 | // nobody governs the registry's own stream (dcr-2f03be3). |
| 113 | if !governed { |
| 114 | return a, fmt.Errorf("governanceOrphaned: on %s no unexpired principal holds a grant at a boundary of kind %q", |
| 115 | day.Format(dateLayout), boundaryRegistry) |
| 116 | } |
| 117 | |
| 118 | a.knownSigners, a.signers = artifact(knownSignersHeader, signers) |
| 119 | a.authorizedKeys, a.authorized = artifact(authorizedKeysHeader, authorized) |
| 120 | a.grants, a.granted = artifact(grantsHeader, granted) |
| 121 | return a, nil |
| 122 | } |
| 123 | |
| 124 | // hasExpired reads an entry's expiry. The declared day is the first day the |
| 125 | // entry no longer counts, so a compilation on it already omits the entry. |
| 126 | func hasExpired(expires string, day time.Time) (bool, error) { |
| 127 | if expires == "" { |
| 128 | return false, nil |
| 129 | } |
| 130 | end, err := time.Parse(dateLayout, expires) |
| 131 | if err != nil { |
| 132 | return false, fmt.Errorf("expires %q is not a calendar day", expires) |
| 133 | } |
| 134 | return !day.Before(end), nil |
| 135 | } |
| 136 | |
| 137 | // heldKinds answers which boundary kinds the entry holds a grant at. A |
| 138 | // grant naming a boundary the registry does not declare fails the render: |
| 139 | // the schema already refuses one, and a compiler that silently dropped it |
| 140 | // would turn a typo into a quiet loss of access. |
| 141 | func heldKinds(r registry, p principal) (map[string]bool, error) { |
| 142 | held := map[string]bool{} |
| 143 | for _, name := range sortedGrants(p.Grants) { |
| 144 | b, ok := r.Boundaries[p.Grants[name].Boundary] |
| 145 | if !ok { |
| 146 | return nil, fmt.Errorf("grant %s names boundary %q, which the registry does not declare", |
| 147 | name, p.Grants[name].Boundary) |
| 148 | } |
| 149 | held[b.Kind] = true |
| 150 | } |
| 151 | return held, nil |
| 152 | } |
| 153 | |
| 154 | func sortedGrants(g map[string]grant) []string { |
| 155 | names := make([]string, 0, len(g)) |
| 156 | for name := range g { |
| 157 | names = append(names, name) |
| 158 | } |
| 159 | sort.Strings(names) |
| 160 | return names |
| 161 | } |
| 162 | |
| 163 | // artifact writes one file's bytes: the header, then the lines sorted and |
| 164 | // deduplicated. Sorting is what makes a compilation reproducible, so a |
| 165 | // registry that did not change re-renders byte for byte and the atomic |
| 166 | // replace below has nothing to do. |
| 167 | func artifact(header string, lines []string) ([]byte, int) { |
| 168 | sort.Strings(lines) |
| 169 | out := bytes.NewBufferString(header) |
| 170 | previous := "" |
| 171 | count := 0 |
| 172 | for i, line := range lines { |
| 173 | if i > 0 && line == previous { |
| 174 | continue |
| 175 | } |
| 176 | previous = line |
| 177 | count++ |
| 178 | out.WriteString(line) |
| 179 | out.WriteByte('\n') |
| 180 | } |
| 181 | return out.Bytes(), count |
| 182 | } |
| 183 | |
| 184 | // keyHash is the note format's identifier for a name-and-key pair, byte for |
| 185 | // byte what attest computes (attest/sign.go): sha256 over the name, a |
| 186 | // newline, the algorithm byte and the public key, truncated to four bytes. |
| 187 | // The name is inside the hash, which is why a key's signing name is |
| 188 | // recorded per key and getting it wrong compiles a line no verifier |
| 189 | // matches. |
| 190 | func keyHash(name string, pub ed25519.PublicKey) uint32 { |
| 191 | h := sha256.New() |
| 192 | h.Write([]byte(name)) |
| 193 | h.Write([]byte("\n")) |
| 194 | h.Write([]byte{algEd25519}) |
| 195 | h.Write(pub) |
| 196 | return binary.BigEndian.Uint32(h.Sum(nil)) |
| 197 | } |
| 198 | |
| 199 | // verifierKey is one line of the known-signers file. |
| 200 | func verifierKey(name string, pub ed25519.PublicKey) string { |
| 201 | return fmt.Sprintf("%s+%08x+%s", name, keyHash(name, pub), |
| 202 | base64.StdEncoding.EncodeToString(append([]byte{algEd25519}, pub...))) |
| 203 | } |
| 204 | |
| 205 | // sshEd25519Public takes the raw 32-byte public key out of an |
| 206 | // authorized_keys line: base64 of the SSH wire format, which is the |
| 207 | // algorithm name and the key, each length-prefixed. |
| 208 | func sshEd25519Public(line string) (ed25519.PublicKey, error) { |
| 209 | fields := strings.Fields(line) |
| 210 | if len(fields) < 2 || fields[0] != sshEd25519 { |
| 211 | return nil, fmt.Errorf("%q is not an %s public key", line, sshEd25519) |
| 212 | } |
| 213 | blob, err := base64.StdEncoding.DecodeString(fields[1]) |
| 214 | if err != nil { |
| 215 | return nil, fmt.Errorf("%s key: %w", sshEd25519, err) |
| 216 | } |
| 217 | algorithm, rest, err := sshString(blob) |
| 218 | if err != nil { |
| 219 | return nil, err |
| 220 | } |
| 221 | pub, rest, err := sshString(rest) |
| 222 | if err != nil { |
| 223 | return nil, err |
| 224 | } |
| 225 | switch { |
| 226 | case string(algorithm) != sshEd25519: |
| 227 | return nil, fmt.Errorf("key names algorithm %q, not %s", algorithm, sshEd25519) |
| 228 | case len(pub) != ed25519.PublicKeySize: |
| 229 | return nil, fmt.Errorf("key holds %d bytes, not the %d an ed25519 key has", len(pub), ed25519.PublicKeySize) |
| 230 | case len(rest) != 0: |
| 231 | return nil, fmt.Errorf("key carries %d trailing bytes", len(rest)) |
| 232 | } |
| 233 | return ed25519.PublicKey(pub), nil |
| 234 | } |
| 235 | |
| 236 | // sshString reads one length-prefixed field of the SSH wire format. |
| 237 | func sshString(b []byte) (value, rest []byte, err error) { |
| 238 | if len(b) < 4 { |
| 239 | return nil, nil, fmt.Errorf("truncated key blob") |
| 240 | } |
| 241 | n := binary.BigEndian.Uint32(b[:4]) |
| 242 | if uint64(n) > uint64(len(b)-4) { |
| 243 | return nil, nil, fmt.Errorf("key blob claims a %d-byte field it does not hold", n) |
| 244 | } |
| 245 | return b[4 : 4+n], b[4+n:], nil |
| 246 | } |