gunk-dev/the-valley

main_test.go

source9787759f09camain's published tip history
38.4 KiB
1package main
2
3// These tests drive the command against real OpenSSH and real git. Every
4// signature that ssh-keygen accepts and this verifier must refuse is made
5// by ssh-keygen itself, and the cases where the two must agree are checked
6// against ssh-keygen's own verdict.
7//
8// Security-key signatures come from OpenSSH's sk-dummy provider: a
9// software authenticator from its regression suite that returns exactly
10// the flags it is asked for. The nix check builds it and names it in
11// SIGVERIFY_SK_PROVIDER. Without it, the security-key cases skip, and the
12// forged signatures in the package tests still cover them.
13//
14// Some cases also record that ssh-keygen or git accepts a signature this
15// verifier refuses. Those are expectations about other tools, kept in
16// subtests named "interop: ...". If a future OpenSSH or git starts
17// refusing silent signatures, only those subtests fail, and the failure
18// says the change is upstream.
19
20import (
21 "bytes"
22 "encoding/base64"
23 "encoding/binary"
24 "errors"
25 "os"
26 "os/exec"
27 "path/filepath"
28 "regexp"
29 "strings"
30 "testing"
31
32 "the-valley/sigverify/internal/skforge"
33)
34
35func TestMain(m *testing.M) {
36 // Nothing here may read the real user's git config or reach their
37 // ssh-agent: a test that signs must sign only with its own keys.
38 home, err := os.MkdirTemp("", "sigverify-test-home")
39 if err != nil {
40 panic(err)
41 }
42 os.Setenv("HOME", home)
43 os.Setenv("GIT_CONFIG_NOSYSTEM", "1")
44 os.Setenv("GIT_CONFIG_GLOBAL", filepath.Join(home, "gitconfig"))
45 for _, v := range []string{"SSH_AUTH_SOCK", "SSH_SK_PROVIDER", "GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_OBJECT_DIRECTORY"} {
46 os.Unsetenv(v)
47 }
48 code := m.Run()
49 os.RemoveAll(home)
50 os.Exit(code)
51}
52
53// skProvider returns the sk-dummy provider, or skips the test.
54func skProvider(t *testing.T) string {
55 t.Helper()
56 p := os.Getenv("SIGVERIFY_SK_PROVIDER")
57 if p == "" {
58 t.Skip("SIGVERIFY_SK_PROVIDER is not set; the nix check sets it to OpenSSH's sk-dummy.so")
59 }
60 if _, err := os.Stat(p); err != nil {
61 t.Fatalf("SIGVERIFY_SK_PROVIDER: %v", err)
62 }
63 return p
64}
65
66// cli runs the command in-process, as main would.
67func cli(t *testing.T, stdin string, args ...string) (stdout, stderr string, code int) {
68 t.Helper()
69 var out, errOut bytes.Buffer
70 code = run(args, strings.NewReader(stdin), &out, &errOut)
71 return out.String(), errOut.String(), code
72}
73
74// refused checks that a run was refused for reason, and that stdout says
75// that and nothing more.
76func refused(t *testing.T, what string, reason string, stdout, stderr string, code int) {
77 t.Helper()
78 if code != exitRefused || stdout != "refused "+reason+"\n" {
79 t.Errorf("%s: exit %d, want a %s refusal and nothing else on stdout:\n%s%s", what, code, reason, stdout, stderr)
80 }
81}
82
83// upstreamAccepts records that another tool accepts a signature this
84// verifier refuses. See the file comment.
85func upstreamAccepts(t *testing.T, tool string, ok bool, out string) {
86 t.Helper()
87 t.Run("interop: "+tool+" accepts it", func(t *testing.T) {
88 if !ok {
89 t.Errorf("an interoperability change, not a sigverify regression: %s now refuses this signature. Update the expectation.\n%s", tool, out)
90 }
91 })
92}
93
94// sh runs a program and returns its combined output and whether it exited
95// zero.
96func sh(t *testing.T, dir, stdin string, env []string, name string, args ...string) (string, bool) {
97 t.Helper()
98 cmd := exec.Command(name, args...)
99 cmd.Dir = dir
100 cmd.Env = append(os.Environ(), env...)
101 cmd.Stdin = strings.NewReader(stdin)
102 out, err := cmd.CombinedOutput()
103 if _, exited := err.(*exec.ExitError); err != nil && !exited {
104 t.Fatalf("%s: %v", name, err)
105 }
106 return string(out), err == nil
107}
108
109func must(t *testing.T, dir string, env []string, name string, args ...string) string {
110 t.Helper()
111 out, ok := sh(t, dir, "", env, name, args...)
112 if !ok {
113 t.Fatalf("%s %s failed:\n%s", name, strings.Join(args, " "), out)
114 }
115 return out
116}
117
118// keygen makes a key pair at dir/name with ssh-keygen.
119func keygen(t *testing.T, dir, name string, env []string, args ...string) string {
120 t.Helper()
121 path := filepath.Join(dir, name)
122 must(t, dir, env, "ssh-keygen", append([]string{"-q", "-N", "", "-C", name, "-f", path}, args...)...)
123 return path
124}
125
126// allowedSigners writes an allowed-signers file of the given lines.
127func allowedSigners(t *testing.T, dir string, lines ...string) string {
128 t.Helper()
129 path := filepath.Join(dir, "allowed_signers")
130 if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o644); err != nil {
131 t.Fatal(err)
132 }
133 return path
134}
135
136func pub(t *testing.T, key string) string {
137 t.Helper()
138 b, err := os.ReadFile(key + ".pub")
139 if err != nil {
140 t.Fatal(err)
141 }
142 return strings.TrimSpace(string(b))
143}
144
145func write(t *testing.T, path, content string) string {
146 t.Helper()
147 if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
148 t.Fatal(err)
149 }
150 return path
151}
152
153// sshSign signs message with ssh-keygen -Y sign and returns the signature
154// file.
155func sshSign(t *testing.T, dir string, env []string, key, namespace, message string, opts ...string) string {
156 t.Helper()
157 msg := write(t, filepath.Join(dir, "message"), message)
158 os.Remove(msg + ".sig")
159 args := []string{"-Y", "sign", "-n", namespace, "-f", key}
160 for _, o := range opts {
161 args = append(args, "-O", o)
162 }
163 must(t, dir, env, "ssh-keygen", append(args, msg)...)
164 sig := filepath.Join(dir, namespace+"-"+filepath.Base(key)+".sig")
165 if err := os.Rename(msg+".sig", sig); err != nil {
166 t.Fatal(err)
167 }
168 return sig
169}
170
171// sshVerify asks ssh-keygen -Y verify for its verdict.
172func sshVerify(t *testing.T, dir, allowed, principal, namespace, sig, message string, opts ...string) (string, bool) {
173 t.Helper()
174 args := []string{"-Y", "verify", "-f", allowed, "-I", principal, "-n", namespace, "-s", sig}
175 for _, o := range opts {
176 args = append(args, "-O", o)
177 }
178 return sh(t, dir, message, nil, "ssh-keygen", args...)
179}
180
181// field returns the value of a "name value" line in the command's output.
182func field(out, name string) string {
183 for _, line := range strings.Split(out, "\n") {
184 if v, ok := strings.CutPrefix(line, name+" "); ok {
185 return v
186 }
187 }
188 return ""
189}
190
191var goodSignature = regexp.MustCompile(`Good "[^"]+" signature for (\S+) with \S+ key (SHA256:\S+)`)
192
193// The interoperability baseline: what ssh-keygen -Y sign writes, this
194// verifies, and both report the same principal and key.
195func TestInteroperatesWithSSHKeygen(t *testing.T) {
196 dir := t.TempDir()
197 const message = "a message ssh-keygen signs\n"
198 for _, c := range []struct {
199 name, keyType string
200 signOpts []string
201 }{
202 {"ed25519", "ed25519", nil},
203 {"ed25519-sha256", "ed25519", []string{"hashalg=sha256"}},
204 {"ecdsa", "ecdsa", nil},
205 {"rsa", "rsa", nil},
206 } {
207 t.Run(c.name, func(t *testing.T) {
208 key := keygen(t, dir, c.name, nil, "-t", c.keyType)
209 allowed := allowedSigners(t, dir, "signer@test.invalid "+pub(t, key))
210 sig := sshSign(t, dir, nil, key, "file", message, c.signOpts...)
211 args := []string{"verify", "--namespace", "file", "--signature", sig,
212 "--allowed-signers", allowed, "--principal", "signer@test.invalid"}
213
214 ref, ok := sshVerify(t, dir, allowed, "signer@test.invalid", "file", sig, message)
215 if !ok {
216 t.Fatalf("ssh-keygen refused its own signature:\n%s", ref)
217 }
218 m := goodSignature.FindStringSubmatch(ref)
219 if m == nil {
220 t.Fatalf("unexpected ssh-keygen output:\n%s", ref)
221 }
222
223 out, errOut, code := cli(t, message, append(args, "--allow-non-sk")...)
224 if code != exitVerified {
225 t.Fatalf("exit %d\n%s%s", code, out, errOut)
226 }
227 if field(out, "principal") != m[1] || field(out, "fingerprint") != m[2] || field(out, "class") != "software" {
228 t.Errorf("ssh-keygen says %s %s; sigverify says\n%s", m[1], m[2], out)
229 }
230
231 // Both refuse the same signature over a changed message.
232 if ref, ok := sshVerify(t, dir, allowed, "signer@test.invalid", "file", sig, message+"!"); ok {
233 t.Fatalf("ssh-keygen accepted a changed message:\n%s", ref)
234 }
235 out, errOut, code = cli(t, message+"!", append(args, "--allow-non-sk")...)
236 refused(t, "a changed message", "bad-signature", out, errOut, code)
237
238 // And a software key is refused outright unless admitted.
239 out, errOut, code = cli(t, message, args...)
240 refused(t, "without --allow-non-sk", "class-not-allowed", out, errOut, code)
241 })
242 }
243}
244
245// Principal patterns, namespaces and validity windows must mean what they
246// mean to ssh-keygen. Each case is put to both, and the verdicts compared.
247func TestAllowedSignersAgreeWithSSHKeygen(t *testing.T) {
248 dir := t.TempDir()
249 const message = "a message\n"
250 key := keygen(t, dir, "signer", nil, "-t", "ed25519")
251 sigs := map[string]string{
252 "git": sshSign(t, dir, nil, key, "git", message),
253 "file": sshSign(t, dir, nil, key, "file", message),
254 }
255 k := pub(t, key)
256 for _, c := range []struct {
257 line, principal, namespace, at string
258 accept bool
259 }{
260 {"a@x.invalid " + k, "a@x.invalid", "git", "", true},
261 {"a@x.invalid,b@x.invalid " + k, "b@x.invalid", "git", "", true},
262 {`"a@x.invalid,b@x.invalid" ` + k, "b@x.invalid", "git", "", true},
263 {"a@x.invalid " + k, "b@x.invalid", "git", "", false},
264 {"*@x.invalid " + k, "anyone@x.invalid", "git", "", true},
265 {"*@x.invalid,!evil@x.invalid " + k, "evil@x.invalid", "git", "", false},
266 {"*@x.invalid,!evil@x.invalid " + k, "good@x.invalid", "git", "", true},
267 {"?@x.invalid " + k, "ab@x.invalid", "git", "", false},
268 {"a*b " + k, "a*xb", "git", "", true},
269 {"*,!a*b " + k, "a*xb", "git", "", false},
270 {`a@x.invalid namespaces="git" ` + k, "a@x.invalid", "git", "", true},
271 {`a@x.invalid namespaces="git" ` + k, "a@x.invalid", "file", "", false},
272 {`a@x.invalid namespaces="fi*" ` + k, "a@x.invalid", "file", "", true},
273 {`a@x.invalid NAMESPACES="git,file" ` + k, "a@x.invalid", "file", "", true},
274 {`a@x.invalid valid-after="20990101" ` + k, "a@x.invalid", "git", "", false},
275 {`a@x.invalid valid-before="20000101" ` + k, "a@x.invalid", "git", "", false},
276 {`a@x.invalid valid-after="20000101",valid-before="20990101" ` + k, "a@x.invalid", "git", "", true},
277 {`a@x.invalid valid-before="20300101Z" ` + k, "a@x.invalid", "git", "20291231Z", true},
278 {`a@x.invalid valid-before="20300101Z" ` + k, "a@x.invalid", "git", "20300102Z", false},
279 {`a@x.invalid valid-after="202601011200Z" ` + k, "a@x.invalid", "git", "202601011159Z", false},
280 {`a@x.invalid valid-after="202601011200Z" ` + k, "a@x.invalid", "git", "202601011200Z", true},
281 {"a@x.invalid cert-authority " + k, "a@x.invalid", "git", "", false},
282 } {
283 allowed := allowedSigners(t, dir, c.line)
284 var opts, flags []string
285 if c.at != "" {
286 opts = []string{"verify-time=" + c.at}
287 flags = []string{"--verify-time", c.at}
288 }
289 ref, refOK := sshVerify(t, dir, allowed, c.principal, c.namespace, sigs[c.namespace], message, opts...)
290 out, errOut, code := cli(t, message, append([]string{"verify", "--namespace", c.namespace,
291 "--signature", sigs[c.namespace], "--allowed-signers", allowed, "--principal", c.principal, "--allow-non-sk"}, flags...)...)
292 if refOK != c.accept {
293 t.Errorf("%q as %s in %s: ssh-keygen accepted=%v, the case expects %v\n%s", c.line, c.principal, c.namespace, refOK, c.accept, ref)
294 }
295 if (code == exitVerified) != refOK || (code != exitVerified && code != exitRefused) {
296 t.Errorf("%q as %s in %s: ssh-keygen accepted=%v, sigverify exit %d\n%s%s", c.line, c.principal, c.namespace, refOK, code, out, errOut)
297 }
298 }
299}
300
301// Principal matching is held to ssh-keygen -Y match-principals, which
302// applies OpenSSH's own pattern matcher to an allowed-signers file and
303// nothing else. Each pattern list is one line, and sigverify must accept
304// a signature for the principal exactly when ssh-keygen matches it.
305func TestPrincipalMatchingAgreesWithSSHKeygen(t *testing.T) {
306 dir := t.TempDir()
307 key := skforge.Ed25519SK("principal matching")
308 const message = "a message\n"
309 sig := write(t, filepath.Join(dir, "sig"), string(key.Sign([]byte(message), "git", 0x01)))
310 for _, c := range []struct {
311 patterns, principal string
312 match bool
313 }{
314 {"a*b", "a*xb", true}, // the review's case: a "*" in the pattern is a wildcard
315 {"a*b", "ab", true},
316 {"a*b", "a", false},
317 {"*,!a*b", "a*xb", false},
318 {"*,!a*b", "c", true},
319 {"!a*b", "c", false},
320 {"a?c", "a?c", true},
321 {"a?c", "abc", true},
322 {"a?c", "ac", false},
323 {"?", "*", true},
324 {"?", "**", false},
325 {"**a", "xa", true},
326 {"*a*a*", "aa", true},
327 {"*a*a*", "a", false},
328 {`a\*`, `a\b`, true},
329 {"a,,b", "b", true},
330 {"!!a", "!a", false},
331 {"A", "a", false},
332 {"release@example.org,!*@evil", "x@evil", false},
333 {"*@example.org", "release@example.org", true},
334 {"*@example.org", "release@example.org.evil", false},
335 } {
336 allowed := allowedSigners(t, dir, `"`+c.patterns+`" `+key.PublicLine())
337 ref, refOK := sh(t, dir, "", nil, "ssh-keygen", "-Y", "match-principals", "-f", allowed, "-I", c.principal)
338 if refOK != c.match {
339 t.Errorf("ssh-keygen: %q against %q matched=%v, the case expects %v\n%s", c.principal, c.patterns, refOK, c.match, ref)
340 }
341 out, errOut, code := cli(t, message, "verify", "--namespace", "git", "--signature", sig,
342 "--allowed-signers", allowed, "--principal", c.principal)
343 if (code == exitVerified) != refOK || (code != exitVerified && code != exitRefused) {
344 t.Errorf("%q against %q: ssh-keygen matched=%v, sigverify exit %d\n%s%s", c.principal, c.patterns, refOK, code, out, errOut)
345 }
346 }
347}
348
349// OpenSSH reads an allowed-signers line as a C string, so a NUL ends it.
350// This line then has no key, and ssh-keygen rejects it. Read as Go bytes,
351// "!release<NUL>x" would be an exclusion that excludes nothing, and the
352// "*" before it would admit release. sigverify refuses the file instead.
353func TestNULLinesAgreeWithSSHKeygen(t *testing.T) {
354 dir := t.TempDir()
355 key := skforge.Ed25519SK("nul lines")
356 const message = "a message\n"
357 sig := write(t, filepath.Join(dir, "sig"), string(key.Sign([]byte(message), "git", 0x01)))
358 allowed := allowedSigners(t, dir, "*,!release\x00x "+key.PublicLine())
359
360 if ref, ok := sh(t, dir, "", nil, "ssh-keygen", "-Y", "match-principals", "-f", allowed, "-I", "release"); ok {
361 t.Errorf("ssh-keygen matched release against a line holding a NUL:\n%s", ref)
362 }
363 out, errOut, code := cli(t, message, "verify", "--namespace", "git", "--signature", sig,
364 "--allowed-signers", allowed, "--principal", "release")
365 if code != exitError || out != "" || !strings.Contains(errOut, "NUL") {
366 t.Errorf("exit %d:\n%s%s", code, out, errOut)
367 }
368}
369
370// The gap this verifier closes. ssh-keygen -Y verify accepts every one of
371// these security-key signatures; sigverify refuses the ones nobody touched.
372func TestSecurityKeysWithSSHKeygen(t *testing.T) {
373 provider := skProvider(t)
374 env := []string{"SSH_SK_PROVIDER=" + provider}
375 dir := t.TempDir()
376 const message = "release v1\n"
377 const principal = "release@test.invalid"
378
379 askpass := write(t, filepath.Join(dir, "askpass"), "#!/bin/sh\necho 1234\n")
380 if err := os.Chmod(askpass, 0o755); err != nil {
381 t.Fatal(err)
382 }
383 pinEnv := append(env, "SSH_ASKPASS="+askpass, "SSH_ASKPASS_REQUIRE=force")
384
385 // verify returns sigverify's report and exit status, and ssh-keygen's
386 // verdict on the same signature. options go on sigverify's line only:
387 // ssh-keygen skips a line with an option it does not know, such as
388 // verify-required.
389 verify := func(t *testing.T, key, options, sig string, extra ...string) (string, int, string, bool) {
390 t.Helper()
391 ref, ok := sshVerify(t, dir, allowedSigners(t, dir, principal+" "+pub(t, key)), principal, "git", sig, message)
392 allowed := allowedSigners(t, dir, principal+" "+options+pub(t, key))
393 out, errOut, code := cli(t, message, append([]string{"verify", "--namespace", "git",
394 "--signature", sig, "--allowed-signers", allowed, "--principal", principal}, extra...)...)
395 return out + errOut, code, ref, ok
396 }
397 accepted := func(t *testing.T, key, options, sig string, extra ...string) string {
398 t.Helper()
399 out, code, ref, ok := verify(t, key, options, sig, extra...)
400 if !ok {
401 t.Fatalf("ssh-keygen refused a genuine, touched signature:\n%s", ref)
402 }
403 if code != exitVerified {
404 t.Fatalf("exit %d:\n%s", code, out)
405 }
406 return out
407 }
408 silent := func(t *testing.T, reason, key, options, sig string, extra ...string) string {
409 t.Helper()
410 out, code, ref, ok := verify(t, key, options, sig, extra...)
411 upstreamAccepts(t, "ssh-keygen -Y verify", ok, ref)
412 if code != exitRefused || !strings.HasPrefix(out, "refused "+reason+"\n") {
413 t.Fatalf("exit %d, want %s:\n%s", code, reason, out)
414 }
415 return out
416 }
417
418 for _, typ := range []string{"ed25519-sk", "ecdsa-sk"} {
419 t.Run(typ+": touched", func(t *testing.T) {
420 key := keygen(t, dir, typ+"-touched", env, "-t", typ)
421 out := accepted(t, key, "", sshSign(t, dir, env, key, "git", message))
422 if field(out, "flags") != "0x01" || field(out, "user-presence") != "yes" || field(out, "class") != "fido-sk" {
423 t.Errorf("report:\n%s", out)
424 }
425 // UV was not asked for, so requiring it refuses.
426 _, code, _, _ := verify(t, key, "", sshSign(t, dir, env, key, "git", message), "--require-uv")
427 if code != exitRefused {
428 t.Errorf("--require-uv: exit %d", code)
429 }
430 })
431
432 t.Run(typ+": generated with no-touch-required", func(t *testing.T) {
433 key := keygen(t, dir, typ+"-notouch", env, "-t", typ, "-O", "no-touch-required")
434 silent(t, "no-user-presence", key, "", sshSign(t, dir, env, key, "git", message))
435 })
436
437 // The attack the verifier exists for. Anything running as the key's
438 // owner can rewrite the key stub on disk so that ssh-keygen stops
439 // asking the authenticator for a touch. (OpenSSH 10.5 does it with
440 // `ssh-keygen -p -O no-touch-required`; this works on every version.)
441 // The key and its allowed-signers line do not change.
442 t.Run(typ+": a stub flipped to no-touch-required", func(t *testing.T) {
443 key := keygen(t, dir, typ+"-flipped", env, "-t", typ)
444 before := accepted(t, key, "", sshSign(t, dir, env, key, "git", message))
445 clearStubFlags(t, key, 0x01)
446 after := silent(t, "no-user-presence", key, "", sshSign(t, dir, env, key, "git", message))
447 if !strings.Contains(after, field(before, "fingerprint")) {
448 t.Errorf("the refusal does not name the key %s:\n%s", field(before, "fingerprint"), after)
449 }
450 })
451 }
452
453 t.Run("a key generated with verify-required", func(t *testing.T) {
454 key := keygen(t, dir, "uv", pinEnv, "-t", "ed25519-sk", "-O", "verify-required")
455 out := accepted(t, key, "verify-required ", sshSign(t, dir, pinEnv, key, "git", message), "--require-uv")
456 if field(out, "flags") != "0x05" || field(out, "user-verification") != "yes" {
457 t.Errorf("report:\n%s", out)
458 }
459 })
460
461 // The same attack one bit over. A release key enrolled with
462 // verify-required, whose stub is rewritten to stop asking for the PIN:
463 // the signature still proves a touch, and no longer proves the PIN.
464 // Its allowed-signers line demands UV, so it is refused without any
465 // flag.
466 t.Run("a verify-required stub with UV cleared", func(t *testing.T) {
467 key := keygen(t, dir, "uv-flipped", pinEnv, "-t", "ed25519-sk", "-O", "verify-required")
468 clearStubFlags(t, key, 0x04)
469 out := silent(t, "no-user-verification", key, "verify-required ", sshSign(t, dir, env, key, "git", message))
470 if !strings.Contains(out, "0x01") {
471 t.Errorf("the refusal does not give the flags:\n%s", out)
472 }
473 })
474}
475
476// clearStubFlags clears flag bits in an unencrypted OpenSSH security-key
477// stub, leaving the key itself unchanged. 0x01 is touch-required, and 0x04
478// is verify-required.
479func clearStubFlags(t *testing.T, path string, mask byte) {
480 t.Helper()
481 const begin, end = "-----BEGIN OPENSSH PRIVATE KEY-----", "-----END OPENSSH PRIVATE KEY-----"
482 raw, err := os.ReadFile(path)
483 if err != nil {
484 t.Fatal(err)
485 }
486 inner := strings.TrimSpace(strings.TrimSuffix(strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(string(raw)), begin)), end))
487 blob, err := base64.StdEncoding.DecodeString(strings.Join(strings.Fields(inner), ""))
488 if err != nil {
489 t.Fatal(err)
490 }
491
492 // openssh-key-v1: magic, cipher, kdf, kdf options, key count, public
493 // key, then the private section. Its security-key entry is two check
494 // integers, the type, the public key (for ECDSA, a curve name and a
495 // point), the application, and then the flags byte.
496 off := len("openssh-key-v1\x00")
497 skip := func() string {
498 n := int(binary.BigEndian.Uint32(blob[off:]))
499 s := string(blob[off+4 : off+4+n])
500 off += 4 + n
501 return s
502 }
503 if cipher := skip(); cipher != "none" {
504 t.Fatalf("the stub is encrypted with %s", cipher)
505 }
506 skip() // kdf
507 skip() // kdf options
508 off += 4 // key count
509 skip() // public key
510 off += 4 // the private section's length
511 off += 8 // check integers
512 switch typ := skip(); typ {
513 case "sk-ssh-ed25519@openssh.com":
514 skip() // public key
515 case "sk-ecdsa-sha2-nistp256@openssh.com":
516 skip() // curve
517 skip() // point
518 default:
519 t.Fatalf("the stub holds a %s key", typ)
520 }
521 skip() // application
522 if blob[off]&mask != mask {
523 t.Fatalf("the stub's flags are 0x%02x, without 0x%02x", blob[off], mask)
524 }
525 blob[off] &^= mask
526
527 enc := base64.StdEncoding.EncodeToString(blob)
528 var b strings.Builder
529 b.WriteString(begin + "\n")
530 for len(enc) > 70 {
531 b.WriteString(enc[:70] + "\n")
532 enc = enc[70:]
533 }
534 b.WriteString(enc + "\n" + end + "\n")
535 if err := os.WriteFile(path, []byte(b.String()), 0o600); err != nil {
536 t.Fatal(err)
537 }
538}
539
540// gitRepo makes a repository with one commit, configured to sign tags with
541// key.
542func gitRepo(t *testing.T, dir, name, key string) string {
543 t.Helper()
544 repo := filepath.Join(dir, name)
545 must(t, dir, nil, "git", "init", "-q", repo)
546 for _, kv := range [][2]string{
547 {"user.name", "Release"}, {"user.email", "release@test.invalid"},
548 {"gpg.format", "ssh"}, {"user.signingKey", key},
549 } {
550 must(t, repo, nil, "git", "config", kv[0], kv[1])
551 }
552 write(t, filepath.Join(repo, "file"), "content of "+name+"\n")
553 must(t, repo, nil, "git", "add", "file")
554 must(t, repo, nil, "git", "commit", "-q", "-m", "a release")
555 return repo
556}
557
558// rev is git rev-parse, with replacement refs honoured as git's default.
559func rev(t *testing.T, repo, name string) string {
560 t.Helper()
561 return strings.TrimSpace(must(t, repo, nil, "git", "rev-parse", name))
562}
563
564// craftTag writes a tag object holding exactly text and signature, which
565// git tag would not make, and points refs/tags/name at it.
566func craftTag(t *testing.T, repo, name, text string, signature []byte) string {
567 t.Helper()
568 path := write(t, filepath.Join(t.TempDir(), "tag"), text+string(signature))
569 id := strings.TrimSpace(must(t, repo, nil, "git", "hash-object", "-t", "tag", "-w", "--literally", path))
570 must(t, repo, nil, "git", "update-ref", "refs/tags/"+name, id)
571 return id
572}
573
574func TestGitTag(t *testing.T) {
575 dir := t.TempDir()
576 key := keygen(t, dir, "release", nil, "-t", "ed25519")
577 const principal = "release@test.invalid"
578 allowed := allowedSigners(t, dir, principal+" "+pub(t, key))
579 repo := gitRepo(t, dir, "repo", key)
580 head := rev(t, repo, "HEAD")
581
582 // The message holds a line that opens like a signature. git takes the
583 // last such line as the signature's start, and so must this.
584 must(t, repo, nil, "git", "tag", "-s", "v1.0.0", "-m",
585 "release 1.0.0\n\n-----BEGIN PGP SIGNATURE-----\nnot a signature\n")
586 if out, ok := sh(t, repo, "", nil, "git", "-c", "gpg.ssh.allowedSignersFile="+allowed, "verify-tag", "v1.0.0"); !ok {
587 t.Fatalf("git verify-tag refused:\n%s", out)
588 }
589
590 tag := func(name string, extra ...string) (string, string, int) {
591 return cli(t, "", append([]string{"git-tag", "--repo", repo, "--tag", name,
592 "--allowed-signers", allowed, "--principal", principal, "--allow-non-sk"}, extra...)...)
593 }
594
595 out, errOut, code := tag("v1.0.0")
596 if code != exitVerified {
597 t.Fatalf("exit %d:\n%s%s", code, out, errOut)
598 }
599 want := "verified\nnamespace git\nprincipal " + principal + "\nclass software\nkey-type ssh-ed25519\n" +
600 "fingerprint " + field(out, "fingerprint") + "\ntag v1.0.0\ncommit " + head + "\n"
601 if out != want {
602 t.Errorf("report:\n%s\nwant:\n%s", out, want)
603 }
604 if _, _, code := tag("refs/tags/v1.0.0"); code != exitVerified {
605 t.Errorf("a full ref name: exit %d", code)
606 }
607
608 out, errOut, code = cli(t, "", "git-tag", "--repo", repo, "--tag", "v1.0.0", "--allowed-signers", allowed, "--principal", principal)
609 refused(t, "without --allow-non-sk", "class-not-allowed", out, errOut, code)
610
611 // A signed tag object published under another name. git verify-tag
612 // is content with it; a release sequence must not be.
613 tagObject := rev(t, repo, "refs/tags/v1.0.0")
614 must(t, repo, nil, "git", "update-ref", "refs/tags/v2.0.0", tagObject)
615 out, errOut, code = tag("v2.0.0")
616 refused(t, "a renamed tag", "tag-name-mismatch", out, errOut, code)
617
618 must(t, repo, nil, "git", "tag", "lightweight")
619 out, errOut, code = tag("lightweight")
620 refused(t, "a lightweight tag", "unsigned", out, errOut, code)
621 must(t, repo, nil, "git", "tag", "-a", "annotated", "-m", "not signed")
622 out, errOut, code = tag("annotated")
623 refused(t, "an unsigned annotated tag", "unsigned", out, errOut, code)
624
625 // Signed tags that point at something other than a commit.
626 blob := strings.TrimSpace(must(t, repo, nil, "git", "hash-object", "-w", "file"))
627 must(t, repo, nil, "git", "tag", "-s", "nested", "v1.0.0", "-m", "a tag of a tag")
628 must(t, repo, nil, "git", "tag", "-s", "tree", "HEAD^{tree}", "-m", "a tag of a tree")
629 must(t, repo, nil, "git", "tag", "-s", "blob", blob, "-m", "a tag of a blob")
630 for _, name := range []string{"nested", "tree", "blob"} {
631 out, errOut, code = tag(name)
632 refused(t, "a tag of a "+name, "target-not-commit", out, errOut, code)
633 }
634
635 // Tags git would not write, signed all the same: a commit that is not
636 // there, and a tree that the tag calls a commit.
637 sign := func(text string) []byte {
638 sig := sshSign(t, dir, nil, key, "git", text)
639 b, err := os.ReadFile(sig)
640 if err != nil {
641 t.Fatal(err)
642 }
643 return b
644 }
645 tagText := func(object, name string) string {
646 return "object " + object + "\ntype commit\ntag " + name + "\ntagger Release <release@test.invalid> 1 +0000\n\ncrafted\n"
647 }
648 missing := strings.Repeat("0", len(head)-1) + "1"
649 craftTag(t, repo, "missing", tagText(missing, "missing"), sign(tagText(missing, "missing")))
650 out, errOut, code = tag("missing")
651 refused(t, "a tag of a missing commit", "target-missing", out, errOut, code)
652 tree := rev(t, repo, "HEAD^{tree}")
653 craftTag(t, repo, "liar", tagText(tree, "liar"), sign(tagText(tree, "liar")))
654 out, errOut, code = tag("liar")
655 refused(t, "a tag calling a tree a commit", "target-not-commit", out, errOut, code)
656
657 // A signed tag whose target was changed afterwards. The refusal must
658 // not repeat the target: it is exactly what nobody signed.
659 raw := must(t, repo, nil, "git", "cat-file", "tag", "v1.0.0")
660 altered := strings.Replace(raw, "tag v1.0.0", "tag altered", 1)
661 altered = strings.Replace(altered, head, missing, 1)
662 payload, signature, _ := strings.Cut(altered, "-----BEGIN SSH SIGNATURE-----")
663 craftTag(t, repo, "altered", payload, []byte("-----BEGIN SSH SIGNATURE-----"+signature))
664 out, errOut, code = tag("altered")
665 refused(t, "an altered target", "bad-signature", out, errOut, code)
666 if strings.Contains(out+errOut, missing) {
667 t.Errorf("the refusal repeats the unsigned target:\n%s%s", out, errOut)
668 }
669
670 // A name git would resolve elsewhere is not a tag. git rev-parse finds
671 // v3.0.0 under refs/remotes; git-tag looks only in refs/tags.
672 must(t, repo, nil, "git", "update-ref", "refs/remotes/v3.0.0", tagObject)
673 if out, errOut, code := tag("v3.0.0"); code != exitError || out != "" {
674 t.Errorf("a ref outside refs/tags: exit %d:\n%s%s", code, out, errOut)
675 }
676 if out, errOut, code := tag("nope"); code != exitError || out != "" {
677 t.Errorf("a missing tag: exit %d:\n%s%s", code, out, errOut)
678 }
679}
680
681// git replacement refs make one object stand in for another wherever git
682// reads it. sigverify reads the objects themselves.
683func TestGitTagIgnoresReplacements(t *testing.T) {
684 dir := t.TempDir()
685 key := keygen(t, dir, "release", nil, "-t", "ed25519")
686 const principal = "release@test.invalid"
687 allowed := allowedSigners(t, dir, principal+" "+pub(t, key))
688 repo := gitRepo(t, dir, "repo", key)
689 head := rev(t, repo, "HEAD")
690 must(t, repo, nil, "git", "tag", "-s", "v1", "-m", "release 1")
691 tagObject := rev(t, repo, "refs/tags/v1")
692 tag := func() (string, string, int) {
693 return cli(t, "", "git-tag", "--repo", repo, "--tag", "v1",
694 "--allowed-signers", allowed, "--principal", principal, "--allow-non-sk")
695 }
696
697 // The signed commit, replaced by a tree. Through git's default
698 // reading it is no longer a commit at all.
699 must(t, repo, nil, "git", "update-ref", "refs/replace/"+head, rev(t, repo, "HEAD^{tree}"))
700 if kind := strings.TrimSpace(must(t, repo, nil, "git", "cat-file", "-t", head)); kind != "tree" {
701 t.Fatalf("the replacement did not take: git reads %s as a %s", head, kind)
702 }
703 if out, errOut, code := tag(); code != exitVerified || field(out, "commit") != head {
704 t.Errorf("a replaced commit: exit %d:\n%s%s", code, out, errOut)
705 }
706
707 // The signed tag object itself, replaced by an unsigned one.
708 must(t, repo, nil, "git", "tag", "-a", "decoy", "-m", "not signed")
709 must(t, repo, nil, "git", "update-ref", "refs/replace/"+tagObject, rev(t, repo, "refs/tags/decoy"))
710 if text := must(t, repo, nil, "git", "cat-file", "tag", tagObject); !strings.Contains(text, "not signed") {
711 t.Fatalf("the replacement did not take:\n%s", text)
712 }
713 if out, errOut, code := tag(); code != exitVerified || field(out, "commit") != head {
714 t.Errorf("a replaced tag object: exit %d:\n%s%s", code, out, errOut)
715 }
716}
717
718// The caller's GIT_* environment does not reach git: GIT_DIR here would
719// otherwise send every read to another repository.
720func TestGitTagIgnoresTheGitEnvironment(t *testing.T) {
721 dir := t.TempDir()
722 key := keygen(t, dir, "release", nil, "-t", "ed25519")
723 const principal = "release@test.invalid"
724 allowed := allowedSigners(t, dir, principal+" "+pub(t, key))
725 repo := gitRepo(t, dir, "repo", key)
726 must(t, repo, nil, "git", "tag", "-s", "v1", "-m", "release 1")
727 decoy := gitRepo(t, dir, "decoy", key)
728 must(t, decoy, nil, "git", "tag", "-s", "v1", "-m", "the decoy's release 1")
729
730 t.Setenv("GIT_DIR", filepath.Join(decoy, ".git"))
731 t.Setenv("GIT_CONFIG_PARAMETERS", "'core.useReplaceRefs'='true'")
732 out, errOut, code := cli(t, "", "git-tag", "--repo", repo, "--tag", "v1",
733 "--allowed-signers", allowed, "--principal", principal, "--allow-non-sk")
734 os.Unsetenv("GIT_DIR")
735 if code != exitVerified || field(out, "commit") != rev(t, repo, "HEAD") {
736 t.Errorf("exit %d, commit %s, want %s:\n%s%s", code, field(out, "commit"), rev(t, repo, "HEAD"), out, errOut)
737 }
738}
739
740// git verify-tag accepts a security-key tag nobody touched; sigverify
741// git-tag does not.
742func TestGitTagWithSecurityKeys(t *testing.T) {
743 provider := skProvider(t)
744 t.Setenv("SSH_SK_PROVIDER", provider)
745 dir := t.TempDir()
746 key := keygen(t, dir, "release", nil, "-t", "ed25519-sk")
747 const principal = "release@test.invalid"
748 allowed := allowedSigners(t, dir, principal+" "+pub(t, key))
749 repo := gitRepo(t, dir, "repo", key)
750 tag := func(name string) (string, string, int) {
751 return cli(t, "", "git-tag", "--repo", repo, "--tag", name, "--allowed-signers", allowed, "--principal", principal)
752 }
753
754 must(t, repo, nil, "git", "tag", "-s", "v1.0.0", "-m", "touched")
755 out, errOut, code := tag("v1.0.0")
756 if code != exitVerified || field(out, "user-presence") != "yes" || field(out, "commit") != rev(t, repo, "HEAD") {
757 t.Fatalf("exit %d:\n%s%s", code, out, errOut)
758 }
759
760 clearStubFlags(t, key, 0x01)
761 must(t, repo, nil, "git", "tag", "-s", "v1.0.1", "-m", "untouched")
762 ref, ok := sh(t, repo, "", nil, "git", "-c", "gpg.ssh.allowedSignersFile="+allowed, "verify-tag", "v1.0.1")
763 upstreamAccepts(t, "git verify-tag", ok, ref)
764 out, errOut, code = tag("v1.0.1")
765 refused(t, "an untouched tag", "no-user-presence", out, errOut, code)
766}
767
768// A TKey signs with the stock signer app through ssh-agent, so what reaches
769// the verifier is an ordinary ssh-ed25519 signature from ssh-keygen -Y
770// sign. This key stands in for one. The TKey's guarantees, a touch per
771// signature and a key that exists only under that app, live in the device
772// and in which public key the line pins, so a software key exercises
773// everything the verifier does with the class.
774func TestTKeyClass(t *testing.T) {
775 dir := t.TempDir()
776 const message = "rotate the release signers\n"
777 tkey := keygen(t, dir, "tkey", nil, "-t", "ed25519")
778 plain := keygen(t, dir, "plain", nil, "-t", "ed25519")
779 allowed := allowedSigners(t, dir,
780 `root@valley.invalid tkey-signer="1.0.0" `+pub(t, tkey),
781 `root@valley.invalid `+pub(t, plain))
782 verify := func(key string, extra ...string) (string, string, int) {
783 return cli(t, message, append([]string{"verify", "--namespace", "trust-root",
784 "--signature", sshSign(t, dir, nil, key, "trust-root", message),
785 "--allowed-signers", allowed, "--principal", "root@valley.invalid"}, extra...)...)
786 }
787
788 out, errOut, code := verify(tkey, "--allow-class", "tkey-signer")
789 if code != exitVerified || field(out, "class") != "tkey-signer" || field(out, "signer-app") != "1.0.0" || field(out, "flags") != "" {
790 t.Errorf("a TKey with its class allowed: exit %d:\n%s%s", code, out, errOut)
791 }
792
793 out, errOut, code = verify(tkey)
794 refused(t, "a TKey by default", "class-not-allowed", out, errOut, code)
795 out, errOut, code = verify(tkey, "--allow-non-sk")
796 refused(t, "a TKey with software keys allowed", "class-not-allowed", out, errOut, code)
797 out, errOut, code = verify(tkey, "--allow-class", "tkey-signer", "--require-uv")
798 refused(t, "a TKey when UV is required", "no-user-verification", out, errOut, code)
799 out, errOut, code = verify(plain, "--allow-class", "tkey-signer")
800 refused(t, "an unmarked key where only a TKey will do", "class-not-allowed", out, errOut, code)
801 out, errOut, code = verify(plain, "--allow-class", "tkey-signer", "--allow-non-sk")
802 if code != exitVerified || field(out, "class") != "software" {
803 t.Errorf("an unmarked key with software allowed is a software key: exit %d:\n%s%s", code, out, errOut)
804 }
805}
806
807// failingWriter is a stdout that cannot be written.
808type failingWriter struct{}
809
810func (failingWriter) Write([]byte) (int, error) { return 0, errors.New("no space left on device") }
811
812// Every refusal exits 1 with its reason alone on stdout, every failure to
813// verify at all exits 2 with nothing on stdout, and a report that cannot
814// be written is a failure. These use forged signatures, so they need no
815// authenticator.
816func TestVerifyExitStatus(t *testing.T) {
817 dir := t.TempDir()
818 key := skforge.Ed25519SK("sigverify cli test")
819 const message = "approve v1\n"
820 const principal = "release@test.invalid"
821 allowed := write(t, filepath.Join(dir, "allowed"), principal+` valid-before="20300101Z" `+key.PublicLine()+"\n")
822 touched := write(t, filepath.Join(dir, "touched.sig"), string(key.Sign([]byte(message), "approval", 0x01)))
823 untouched := write(t, filepath.Join(dir, "untouched.sig"), string(key.Sign([]byte(message), "approval", 0x00)))
824 args := func(sig string, extra ...string) []string {
825 return append([]string{"verify", "--namespace", "approval", "--signature", sig, "--allowed-signers", allowed,
826 "--verify-time", "20291231Z"}, extra...)
827 }
828
829 out, errOut, code := cli(t, message, args(touched, "--principal", principal)...)
830 want := "verified\nnamespace approval\nprincipal " + principal + "\nclass fido-sk\nkey-type sk-ssh-ed25519@openssh.com\n" +
831 "fingerprint " + field(out, "fingerprint") + "\nflags 0x01\nuser-presence yes\n" +
832 "user-verification no\ncounter 305419896\n"
833 if code != exitVerified || out != want || !strings.HasPrefix(field(out, "fingerprint"), "SHA256:") {
834 t.Errorf("exit %d:\n%s%s", code, out, errOut)
835 }
836 if out, _, code := cli(t, message, args(touched, "--any-principal")...); code != exitVerified || field(out, "principal") != principal {
837 t.Errorf("--any-principal: exit %d:\n%s", code, out)
838 }
839
840 for _, c := range []struct {
841 name string
842 stdin string
843 args []string
844 reason string
845 }{
846 {"untouched", message, args(untouched, "--principal", principal), "no-user-presence"},
847 {"UV required", message, args(touched, "--principal", principal, "--require-uv"), "no-user-verification"},
848 {"expired", message, append(args(touched, "--principal", principal), "--verify-time", "20300102Z"), "expired"},
849 {"tampered", message + "!", args(touched, "--principal", principal), "bad-signature"},
850 {"another principal", message, args(touched, "--principal", "x@test.invalid"), "principal-not-allowed"},
851 {"only TKeys accepted", message, args(touched, "--principal", principal, "--allow-class", "tkey-signer"), "class-not-allowed"},
852 } {
853 out, errOut, code := cli(t, c.stdin, c.args...)
854 refused(t, c.name, c.reason, out, errOut, code)
855 if !strings.HasPrefix(errOut, "sigverify: refused ("+c.reason+"): ") {
856 t.Errorf("%s: stderr %q", c.name, errOut)
857 }
858 }
859
860 noTouch := write(t, filepath.Join(dir, "no-touch"), principal+" no-touch-required "+key.PublicLine()+"\n")
861 for name, a := range map[string][]string{
862 "no principal": args(touched),
863 "both principal flags": args(touched, "--principal", principal, "--any-principal"),
864 "an unknown class": args(touched, "--principal", principal, "--allow-class", "yubikey"),
865 "no namespace": {"verify", "--signature", touched, "--allowed-signers", allowed, "--principal", principal},
866 "no allowed signers": {"verify", "--namespace", "approval", "--signature", touched, "--principal", principal},
867 "a missing allowed signers": {"verify", "--namespace", "approval", "--signature", touched, "--allowed-signers", filepath.Join(dir, "absent"), "--principal", principal},
868 "no-touch-required in signers": {"verify", "--namespace", "approval", "--signature", touched, "--allowed-signers", noTouch, "--principal", principal},
869 "a missing signature": {"verify", "--namespace", "approval", "--signature", filepath.Join(dir, "absent"), "--allowed-signers", allowed, "--principal", principal},
870 "a bad verify time": args(touched, "--principal", principal, "--verify-time", "tomorrow"),
871 "an unknown command": {"sign"},
872 "an unknown flag": {"verify", "--no-touch-required"},
873 } {
874 if out, errOut, code := cli(t, message, a...); code != exitError || out != "" {
875 t.Errorf("%s: exit %d:\n%s%s", name, code, out, errOut)
876 }
877 }
878
879 // A report that cannot be written is an error, whatever the verdict:
880 // a full disk must never turn into exit status 0.
881 var errOut2 bytes.Buffer
882 if code := run(args(touched, "--principal", principal), strings.NewReader(message), failingWriter{}, &errOut2); code != exitError {
883 t.Errorf("a verified report that could not be written: exit %d", code)
884 }
885 if code := run(args(untouched, "--principal", principal), strings.NewReader(message), failingWriter{}, &errOut2); code != exitError {
886 t.Errorf("a refusal that could not be written: exit %d", code)
887 }
888 if full, err := os.OpenFile("/dev/full", os.O_WRONLY, 0); err == nil {
889 defer full.Close()
890 if code := run(args(touched, "--principal", principal), strings.NewReader(message), full, &errOut2); code != exitError {
891 t.Errorf("a report written to /dev/full: exit %d", code)
892 }
893 }
894}