| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/ed25519" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/binary" |
| 9 | "fmt" |
| 10 | "slices" |
| 11 | "sort" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "the-valley/note" |
| 16 | ) |
| 17 | |
| 18 | const ( |
| 19 | // The algorithm identifier the note format prefixes a public key with, |
| 20 | // and the only algorithm this program renders (attest/sign.go). |
| 21 | algEd25519 = 1 |
| 22 | sshEd25519 = "ssh-ed25519" |
| 23 | |
| 24 | // The environment variable carrying the pushing key's principal name. |
| 25 | // One name, shared with nix/valley-host.nix — change it in both. |
| 26 | principalEnv = "VALLEY_PRINCIPAL" |
| 27 | |
| 28 | // Only a human approves. |
| 29 | kindHuman = "human" |
| 30 | |
| 31 | dateLayout = "2006-01-02" |
| 32 | ) |
| 33 | |
| 34 | const knownSignersHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8). |
| 35 | # Verifier keys whose attestations count, one per line: the name a key |
| 36 | # signs under, the note format's key hash over that name and key, and |
| 37 | # base64 of the algorithm byte and the raw ed25519 public key. |
| 38 | ` |
| 39 | |
| 40 | const authorizedKeysHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8). |
| 41 | # Keys that may push, each tagged with the principal it acts as. The git |
| 42 | # user's shell reads the tag off the entry of the key sshd authenticated, |
| 43 | # which is what tells one pusher from another over a shared user. |
| 44 | ` |
| 45 | |
| 46 | const grantsHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8). |
| 47 | # Grants the pre-receive hook checks, one per line: the grant, then the |
| 48 | # principal holding it. A principal not named here holds none. |
| 49 | ` |
| 50 | |
| 51 | const approvalSignersHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8). |
| 52 | # Approval keys: every key of every human holding the approve grant, as |
| 53 | # verifier keys, one per line, each named by the principal who approves |
| 54 | # with it. |
| 55 | ` |
| 56 | |
| 57 | const approvalHardwareHeader = `# Compiled from the identity registry — do not edit (dcr-b87f6e8). |
| 58 | # Hardware approval keys: the approval keys whose YubiKey attestation |
| 59 | # verifies and says every signature needs a touch, as verifier keys, one |
| 60 | # per line, each named by the principal who approves with it. |
| 61 | ` |
| 62 | |
| 63 | // The lines a holder of a grant at a hook boundary is written under: the |
| 64 | // grant the hook checks. grantRequest is the approve grant, the verb of |
| 65 | // dcr-e544f20. A holder at a boundary of kind approve or of kind request |
| 66 | // is written under the name request, which every deployed hook reads, and |
| 67 | // the hook takes a line naming either name as the approve grant. |
| 68 | // grantRestack is the host restacker's. |
| 69 | const ( |
| 70 | grantRequest = "request" |
| 71 | grantRestack = "restack" |
| 72 | ) |
| 73 | |
| 74 | // artifacts is a whole compilation: every file, what was left out, and the |
| 75 | // counts the journal line reports. Nothing is written until every part of |
| 76 | // this exists, so a failure anywhere leaves the last good set intact. |
| 77 | type artifacts struct { |
| 78 | knownSigners []byte |
| 79 | authorizedKeys []byte |
| 80 | grants []byte |
| 81 | approvalSigners []byte |
| 82 | approvalHardware []byte |
| 83 | notes []string |
| 84 | signers int |
| 85 | authorized int |
| 86 | granted int |
| 87 | approvers int |
| 88 | hardware int |
| 89 | } |
| 90 | |
| 91 | // render turns a registry into every artifact as of one day. declared maps |
| 92 | // each key the host authorizes by hand to the principal its entry is |
| 93 | // tagged with, "" for an untagged one; nil when the caller names none. |
| 94 | // |
| 95 | // One key authorized as two principals is refused, whether both entries |
| 96 | // are the registry's or one is the host's. sshd authorizes a key by the |
| 97 | // first entry that names it, so which principal such a key pushed as would |
| 98 | // depend on the order of lines and files, and a grant could silently stop |
| 99 | // applying to the principal that holds it. |
| 100 | // |
| 101 | // A key that approves is refused under a second principal too, whatever |
| 102 | // that principal holds. An approval names the principal who gave it, and |
| 103 | // the key it is checked against must answer for that principal alone. |
| 104 | // |
| 105 | // A key's attestation, when the entry carries one, is verified here |
| 106 | // (attestation.go). One that does not verify fails the render: evidence |
| 107 | // that was offered and is wrong is never read as no evidence. |
| 108 | func render(r registry, day time.Time, declared map[string]string) (artifacts, error) { |
| 109 | var a artifacts |
| 110 | var signers, authorized, granted, approvers, hardware []string |
| 111 | governed := false |
| 112 | authorizedAs := map[string]string{} |
| 113 | // Every principal holding each key, by the key's raw bytes, and the |
| 114 | // keys that approve. |
| 115 | holders := map[string][]string{} |
| 116 | type approvalKey struct { |
| 117 | name string |
| 118 | index int |
| 119 | pub ed25519.PublicKey |
| 120 | } |
| 121 | var approving []approvalKey |
| 122 | |
| 123 | names := make([]string, 0, len(r.Principals)) |
| 124 | for name := range r.Principals { |
| 125 | names = append(names, name) |
| 126 | } |
| 127 | sort.Strings(names) |
| 128 | |
| 129 | for _, name := range names { |
| 130 | p := r.Principals[name] |
| 131 | |
| 132 | expired, err := hasExpired(p.Expires, day) |
| 133 | if err != nil { |
| 134 | return a, fmt.Errorf("%s: %w", name, err) |
| 135 | } |
| 136 | if expired { |
| 137 | a.notes = append(a.notes, fmt.Sprintf( |
| 138 | "%s expired %s: %d key(s) and every grant omitted from all artifacts", name, p.Expires, len(p.Keys))) |
| 139 | continue |
| 140 | } |
| 141 | |
| 142 | held, err := heldKinds(r, p) |
| 143 | if err != nil { |
| 144 | return a, fmt.Errorf("%s: %w", name, err) |
| 145 | } |
| 146 | governed = governed || held[boundaryRegistry] |
| 147 | pushes := held[boundaryGitPush] |
| 148 | if held[boundaryApprove] || held[boundaryRequest] { |
| 149 | granted = append(granted, grantRequest+" "+name) |
| 150 | } |
| 151 | if held[boundaryRestack] { |
| 152 | granted = append(granted, grantRestack+" "+name) |
| 153 | } |
| 154 | approves := p.Kind == kindHuman && (held[boundaryApprove] || held[boundaryRequest]) |
| 155 | |
| 156 | for i, k := range p.Keys { |
| 157 | pub, err := sshEd25519Public(k.Public) |
| 158 | if err != nil { |
| 159 | return a, fmt.Errorf("%s: key %d: %w", name, i, err) |
| 160 | } |
| 161 | isHardware := false |
| 162 | if k.Attestation != nil { |
| 163 | att, err := verifyAttestation(*k.Attestation, pub, day, yubico) |
| 164 | if err != nil { |
| 165 | return a, fmt.Errorf("%s: key %d: %w", name, i, err) |
| 166 | } |
| 167 | isHardware = att.hardware() |
| 168 | report := fmt.Sprintf("%s: key %d is on %s", name, i, att) |
| 169 | switch { |
| 170 | case !approves: |
| 171 | report += "; its principal approves nothing" |
| 172 | case isHardware: |
| 173 | report += "; it approves as a hardware key" |
| 174 | default: |
| 175 | report += "; it approves, but not as a hardware key, because its touch policy is not always" |
| 176 | } |
| 177 | a.notes = append(a.notes, report) |
| 178 | } |
| 179 | if !slices.Contains(holders[string(pub)], name) { |
| 180 | holders[string(pub)] = append(holders[string(pub)], name) |
| 181 | } |
| 182 | if approves { |
| 183 | line := verifierKey(name, pub) |
| 184 | approvers = append(approvers, line) |
| 185 | if isHardware { |
| 186 | hardware = append(hardware, line) |
| 187 | } |
| 188 | approving = append(approving, approvalKey{name, i, pub}) |
| 189 | } |
| 190 | if k.Signs != "" { |
| 191 | signers = append(signers, verifierKey(k.Signs, pub)) |
| 192 | } |
| 193 | if pushes { |
| 194 | blob := strings.Fields(k.Public)[1] |
| 195 | if other, ok := authorizedAs[blob]; ok && other != name { |
| 196 | return a, fmt.Errorf("%s: key %d is also %s's, and one key authorizes one principal", name, i, other) |
| 197 | } |
| 198 | authorizedAs[blob] = name |
| 199 | if tag, ok := declared[blob]; ok && tag != name { |
| 200 | if tag == "" { |
| 201 | tag = "an untagged entry" |
| 202 | } |
| 203 | return a, fmt.Errorf("%s: key %d is also declared on this host as %s, and sshd reads the declared entry first, so the key would never push as %s; tag the declared key as %s or remove it", name, i, tag, name, name) |
| 204 | } |
| 205 | authorized = append(authorized, fmt.Sprintf("environment=%q %s", principalEnv+"="+name, k.Public)) |
| 206 | } |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | for _, k := range approving { |
| 211 | for _, other := range holders[string(k.pub)] { |
| 212 | if other != k.name { |
| 213 | return a, fmt.Errorf("%s: key %d is also %s's, and a key that approves belongs to one principal", k.name, k.index, other) |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | // The state the whole render is refused for: after the expiry cut, |
| 219 | // nobody governs the registry's own stream (dcr-2f03be3). |
| 220 | if !governed { |
| 221 | return a, fmt.Errorf("governanceOrphaned: on %s no unexpired principal holds a grant at a boundary of kind %q", |
| 222 | day.Format(dateLayout), boundaryRegistry) |
| 223 | } |
| 224 | |
| 225 | a.knownSigners, a.signers = artifact(knownSignersHeader, signers) |
| 226 | a.authorizedKeys, a.authorized = artifact(authorizedKeysHeader, authorized) |
| 227 | a.grants, a.granted = artifact(grantsHeader, granted) |
| 228 | a.approvalSigners, a.approvers = artifact(approvalSignersHeader, approvers) |
| 229 | a.approvalHardware, a.hardware = artifact(approvalHardwareHeader, hardware) |
| 230 | |
| 231 | // The approval files are read as verifier keys, by the note reader |
| 232 | // every verifier uses. Reading them with it here means a render never |
| 233 | // writes one a verifier would refuse. |
| 234 | for _, file := range [][]byte{a.approvalSigners, a.approvalHardware} { |
| 235 | if _, err := note.ParseVerifierKeys(file); err != nil { |
| 236 | return a, fmt.Errorf("an approval signers file would not parse: %w", err) |
| 237 | } |
| 238 | } |
| 239 | return a, nil |
| 240 | } |
| 241 | |
| 242 | // hasExpired reads an entry's expiry. The declared day is the first day the |
| 243 | // entry no longer counts, so a compilation on it already omits the entry. |
| 244 | func hasExpired(expires string, day time.Time) (bool, error) { |
| 245 | if expires == "" { |
| 246 | return false, nil |
| 247 | } |
| 248 | end, err := time.Parse(dateLayout, expires) |
| 249 | if err != nil { |
| 250 | return false, fmt.Errorf("expires %q is not a calendar day", expires) |
| 251 | } |
| 252 | return !day.Before(end), nil |
| 253 | } |
| 254 | |
| 255 | // heldKinds answers which boundary kinds the entry holds a grant at. A |
| 256 | // grant naming a boundary the registry does not declare fails the render: |
| 257 | // the schema already refuses one, and a compiler that silently dropped it |
| 258 | // would turn a typo into a quiet loss of access. |
| 259 | func heldKinds(r registry, p principal) (map[string]bool, error) { |
| 260 | held := map[string]bool{} |
| 261 | for _, name := range sortedGrants(p.Grants) { |
| 262 | b, ok := r.Boundaries[p.Grants[name].Boundary] |
| 263 | if !ok { |
| 264 | return nil, fmt.Errorf("grant %s names boundary %q, which the registry does not declare", |
| 265 | name, p.Grants[name].Boundary) |
| 266 | } |
| 267 | held[b.Kind] = true |
| 268 | } |
| 269 | return held, nil |
| 270 | } |
| 271 | |
| 272 | func sortedGrants(g map[string]grant) []string { |
| 273 | names := make([]string, 0, len(g)) |
| 274 | for name := range g { |
| 275 | names = append(names, name) |
| 276 | } |
| 277 | sort.Strings(names) |
| 278 | return names |
| 279 | } |
| 280 | |
| 281 | // artifact writes one file's bytes: the header, then the lines sorted and |
| 282 | // deduplicated. Sorting is what makes a compilation reproducible, so a |
| 283 | // registry that did not change re-renders byte for byte and the atomic |
| 284 | // replace below has nothing to do. |
| 285 | func artifact(header string, lines []string) ([]byte, int) { |
| 286 | sort.Strings(lines) |
| 287 | out := bytes.NewBufferString(header) |
| 288 | previous := "" |
| 289 | count := 0 |
| 290 | for i, line := range lines { |
| 291 | if i > 0 && line == previous { |
| 292 | continue |
| 293 | } |
| 294 | previous = line |
| 295 | count++ |
| 296 | out.WriteString(line) |
| 297 | out.WriteByte('\n') |
| 298 | } |
| 299 | return out.Bytes(), count |
| 300 | } |
| 301 | |
| 302 | // keyHash is the note format's identifier for a name-and-key pair, byte for |
| 303 | // byte what attest computes (attest/sign.go): sha256 over the name, a |
| 304 | // newline, the algorithm byte and the public key, truncated to four bytes. |
| 305 | // The name is inside the hash, which is why a key's signing name is |
| 306 | // recorded per key and getting it wrong compiles a line no verifier |
| 307 | // matches. |
| 308 | func keyHash(name string, pub ed25519.PublicKey) uint32 { |
| 309 | h := sha256.New() |
| 310 | h.Write([]byte(name)) |
| 311 | h.Write([]byte("\n")) |
| 312 | h.Write([]byte{algEd25519}) |
| 313 | h.Write(pub) |
| 314 | return binary.BigEndian.Uint32(h.Sum(nil)) |
| 315 | } |
| 316 | |
| 317 | // verifierKey is one line of the known-signers file. |
| 318 | func verifierKey(name string, pub ed25519.PublicKey) string { |
| 319 | return fmt.Sprintf("%s+%08x+%s", name, keyHash(name, pub), |
| 320 | base64.StdEncoding.EncodeToString(append([]byte{algEd25519}, pub...))) |
| 321 | } |
| 322 | |
| 323 | // sshEd25519Public takes the raw 32-byte public key out of an |
| 324 | // authorized_keys line: base64 of the SSH wire format, which is the |
| 325 | // algorithm name and the key, each length-prefixed. |
| 326 | func sshEd25519Public(line string) (ed25519.PublicKey, error) { |
| 327 | fields := strings.Fields(line) |
| 328 | if len(fields) < 2 || fields[0] != sshEd25519 { |
| 329 | return nil, fmt.Errorf("%q is not an %s public key", line, sshEd25519) |
| 330 | } |
| 331 | blob, err := base64.StdEncoding.DecodeString(fields[1]) |
| 332 | if err != nil { |
| 333 | return nil, fmt.Errorf("%s key: %w", sshEd25519, err) |
| 334 | } |
| 335 | algorithm, rest, err := sshString(blob) |
| 336 | if err != nil { |
| 337 | return nil, err |
| 338 | } |
| 339 | pub, rest, err := sshString(rest) |
| 340 | if err != nil { |
| 341 | return nil, err |
| 342 | } |
| 343 | switch { |
| 344 | case string(algorithm) != sshEd25519: |
| 345 | return nil, fmt.Errorf("key names algorithm %q, not %s", algorithm, sshEd25519) |
| 346 | case len(pub) != ed25519.PublicKeySize: |
| 347 | return nil, fmt.Errorf("key holds %d bytes, not the %d an ed25519 key has", len(pub), ed25519.PublicKeySize) |
| 348 | case len(rest) != 0: |
| 349 | return nil, fmt.Errorf("key carries %d trailing bytes", len(rest)) |
| 350 | } |
| 351 | return ed25519.PublicKey(pub), nil |
| 352 | } |
| 353 | |
| 354 | // sshString reads one length-prefixed field of the SSH wire format. |
| 355 | func sshString(b []byte) (value, rest []byte, err error) { |
| 356 | if len(b) < 4 { |
| 357 | return nil, nil, fmt.Errorf("truncated key blob") |
| 358 | } |
| 359 | n := binary.BigEndian.Uint32(b[:4]) |
| 360 | if uint64(n) > uint64(len(b)-4) { |
| 361 | return nil, nil, fmt.Errorf("key blob claims a %d-byte field it does not hold", n) |
| 362 | } |
| 363 | return b[4 : 4+n], b[4+n:], nil |
| 364 | } |