gunk-dev/the-valley

main.go

source8c40ee5f164cmain's published tip history
13.2 KiB
1// sigverify verifies OpenSSH signatures and refuses a FIDO security-key
2// signature that was made without a touch. See ../../README.md.
3package main
4
5import (
6 "bytes"
7 "errors"
8 "flag"
9 "fmt"
10 "io"
11 "os"
12 "os/exec"
13 "strings"
14
15 "the-valley/sigverify"
16)
17
18// gitProgram is the git the git-tag command runs. The Nix package sets it
19// at build time to an absolute store path, so a shipped sigverify never
20// looks git up on PATH. A plain `go build` leaves it to PATH.
21var gitProgram = "git"
22
23const usage = `usage: sigverify <command> [flags]
24
25 verify verify an SSH signature over the message on stdin
26 git-tag verify the SSH signature on an annotated git tag
27 help print this message
28
29Both commands accept a signature only if all of these hold:
30
31 - it is a valid SSHSIG over the message, in the expected namespace
32 - an allowed-signers line lists its key, in a signer class the call
33 accepts, for the principal, in that namespace, at the verify time
34 - a security key's signature has the user-presence bit set; nothing
35 turns this off
36 - the signature proves user verification, if --require-uv is given or
37 the signer's line carries verify-required
38
39Signer classes: an allowed-signers line names a fido-sk signer (a FIDO
40security key), a tkey-signer (an ssh-ed25519 key on a line marked
41tkey-signer), or a software key (anything else). By default only fido-sk
42signers are accepted.
43
44On success stdout is "verified" followed by "name value" lines describing
45the signature. On refusal stdout is exactly one line, "refused <reason>",
46and stderr gives the reason again with a sentence saying why. On error
47sigverify prints nothing to stdout, but a write that fails partway can
48leave part of a report there. So a caller must discard stdout whenever
49the exit status is not 0. The reasons are listed in sigverify/README.md.
50
51exit status:
52 0 verified, and the whole report was written to stdout
53 1 refused
54 2 error: bad usage, an unreadable file, an invalid allowed-signers
55 file, a git failure, or a failure to write the report
56
57verify flags:
58 --namespace NS the namespace the signature must carry (required)
59 --signature FILE the armored or raw signature (required)
60
61git-tag flags:
62 --repo DIR the repository (default ".")
63 --tag NAME the tag, resolved as refs/tags/NAME (required)
64
65flags for both:
66 --allowed-signers FILE the OpenSSH allowed-signers file (required)
67 --principal ID the identity the signature must be valid for
68 (required, unless --any-principal is given)
69 --any-principal accept any line that lists the key, whatever
70 principals it names, even "!*"
71 --allow-class CLASS accept signers of CLASS: fido-sk, tkey-signer or
72 software. Repeat for more than one. Giving it
73 replaces the default, fido-sk.
74 --allow-non-sk also accept software keys, which prove nothing
75 about presence: adds software to the accepted
76 classes, whichever they are
77 --require-uv require user verification; only a security key
78 can prove it
79 --verify-time TIME judge validity at TIME, as YYYYMMDD[HHMM[SS]][Z]
80 (default: now)
81
82git-tag reads the tag object with git, splits it into payload and
83signature exactly as git verify-tag does, and verifies in the "git"
84namespace. It then refuses a tag signed under a different name than NAME,
85and a tag that does not point at a commit present in the repository. On
86success it prints the commit id, and the caller must use exactly that
87commit. git runs with replacement refs disabled and with no inherited
88GIT_* variables or user or system configuration. Validity is judged at
89the verify time, not the tagger date: the signer chooses the tagger date.
90`
91
92const (
93 exitVerified = 0
94 exitRefused = 1
95 exitError = 2
96)
97
98func main() {
99 os.Exit(run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
100}
101
102func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
103 if len(args) < 1 {
104 fmt.Fprint(stderr, usage)
105 return exitError
106 }
107 var c *command
108 switch args[0] {
109 case "verify":
110 c = newCommand("verify", stderr)
111 c.fs.StringVar(&c.namespace, "namespace", "", "")
112 c.fs.StringVar(&c.signature, "signature", "", "")
113 case "git-tag":
114 c = newCommand("git-tag", stderr)
115 c.fs.StringVar(&c.repo, "repo", ".", "")
116 c.fs.StringVar(&c.tag, "tag", "", "")
117 case "help", "-h", "--help":
118 return emit(stdout, stderr, []byte(usage), exitVerified)
119 default:
120 fmt.Fprintf(stderr, "sigverify: unknown command %q\n\n%s", args[0], usage)
121 return exitError
122 }
123 if err := c.fs.Parse(args[1:]); err != nil {
124 return exitError
125 }
126 if c.fs.NArg() != 0 {
127 fmt.Fprintf(stderr, "sigverify %s: unexpected argument %q\n", args[0], c.fs.Arg(0))
128 return exitError
129 }
130
131 var out report
132 var err error
133 if args[0] == "verify" {
134 out, err = c.verify(stdin)
135 } else {
136 out, err = c.gitTag()
137 }
138
139 // A refusal reports its reason and nothing else. What a refused
140 // signature names, such as a tag's target, is unauthenticated, and a
141 // caller that misreads the exit status must find nothing to act on.
142 var refusal *sigverify.Refusal
143 switch {
144 case errors.As(err, &refusal):
145 fmt.Fprintf(stderr, "sigverify: refused (%s): %s\n", refusal.Reason, refusal.Detail)
146 return emit(stdout, stderr, []byte("refused "+string(refusal.Reason)+"\n"), exitRefused)
147 case err != nil:
148 fmt.Fprintf(stderr, "sigverify %s: %v\n", args[0], err)
149 return exitError
150 }
151 var b bytes.Buffer
152 b.WriteString("verified\n")
153 out.write(&b)
154 return emit(stdout, stderr, b.Bytes(), exitVerified)
155}
156
157// emit writes the whole of out to stdout in one write, and returns code
158// only if that write succeeded. A report that did not reach its reader is
159// an error, so a full disk or a closed pipe can never yield exit status 0.
160// A write can fail after part of out is written, and that part stays on
161// stdout. That is why callers discard stdout on any nonzero exit status.
162func emit(stdout, stderr io.Writer, out []byte, code int) int {
163 if _, err := stdout.Write(out); err != nil {
164 fmt.Fprintf(stderr, "sigverify: writing the report: %v\n", err)
165 return exitError
166 }
167 return code
168}
169
170// command holds one invocation's flags.
171type command struct {
172 fs *flag.FlagSet
173
174 allowedSigners string
175 principal string
176 anyPrincipal bool
177 classes classFlag
178 allowNonSK bool
179 requireUV bool
180 verifyTime string
181
182 namespace string // verify
183 signature string
184
185 repo string // git-tag
186 tag string
187}
188
189func newCommand(name string, stderr io.Writer) *command {
190 c := &command{fs: flag.NewFlagSet(name, flag.ContinueOnError)}
191 c.fs.SetOutput(stderr)
192 c.fs.Usage = func() { fmt.Fprint(stderr, usage) }
193 c.fs.StringVar(&c.allowedSigners, "allowed-signers", "", "")
194 c.fs.StringVar(&c.principal, "principal", "", "")
195 c.fs.BoolVar(&c.anyPrincipal, "any-principal", false, "")
196 c.fs.Var(&c.classes, "allow-class", "")
197 c.fs.BoolVar(&c.allowNonSK, "allow-non-sk", false, "")
198 c.fs.BoolVar(&c.requireUV, "require-uv", false, "")
199 c.fs.StringVar(&c.verifyTime, "verify-time", "", "")
200 return c
201}
202
203// classFlag collects repeated --allow-class flags.
204type classFlag []sigverify.Class
205
206func (f *classFlag) String() string { return fmt.Sprint(*f) }
207
208func (f *classFlag) Set(name string) error {
209 c, err := sigverify.ParseClass(name)
210 if err != nil {
211 return err
212 }
213 *f = append(*f, c)
214 return nil
215}
216
217// setup loads what both commands share: the allowed signers and the
218// options.
219func (c *command) setup() (*sigverify.AllowedSigners, sigverify.Options, error) {
220 opts := sigverify.Options{
221 Principal: c.principal,
222 AnyPrincipal: c.anyPrincipal,
223 Policy: sigverify.Policy{
224 Classes: c.classes,
225 AllowNonSK: c.allowNonSK,
226 RequireUV: c.requireUV,
227 },
228 }
229 switch {
230 case c.allowedSigners == "":
231 return nil, opts, errors.New("--allowed-signers is required")
232 case c.principal == "" && !c.anyPrincipal:
233 return nil, opts, errors.New("--principal is required; pass --any-principal to accept any principal the key is listed under")
234 case c.principal != "" && c.anyPrincipal:
235 return nil, opts, errors.New("--principal and --any-principal cannot both be given")
236 }
237 if c.verifyTime != "" {
238 t, err := sigverify.ParseTime(c.verifyTime)
239 if err != nil {
240 return nil, opts, fmt.Errorf("--verify-time: %w", err)
241 }
242 opts.Time = t
243 }
244 signers, err := sigverify.LoadAllowedSigners(c.allowedSigners)
245 return signers, opts, err
246}
247
248func (c *command) verify(stdin io.Reader) (report, error) {
249 if c.namespace == "" {
250 return nil, errors.New("--namespace is required")
251 }
252 if c.signature == "" {
253 return nil, errors.New("--signature is required")
254 }
255 signers, opts, err := c.setup()
256 if err != nil {
257 return nil, err
258 }
259 opts.Namespace = c.namespace
260 signature, err := os.ReadFile(c.signature)
261 if err != nil {
262 return nil, err
263 }
264 message, err := io.ReadAll(stdin)
265 if err != nil {
266 return nil, fmt.Errorf("reading the message: %w", err)
267 }
268 result, err := sigverify.Verify(signers, message, signature, opts)
269 if err != nil {
270 return nil, err
271 }
272 return resultLines(result), nil
273}
274
275func (c *command) gitTag() (report, error) {
276 name := strings.TrimPrefix(c.tag, "refs/tags/")
277 if name == "" {
278 return nil, errors.New("--tag is required")
279 }
280 signers, opts, err := c.setup()
281 if err != nil {
282 return nil, err
283 }
284
285 // show-ref --verify takes only a full ref name, so refs/tags/NAME
286 // cannot resolve to a branch or anything else that happens to share
287 // the name.
288 ref := "refs/tags/" + name
289 shown, err := git(c.repo, "", "show-ref", "--verify", ref)
290 if err != nil {
291 return nil, fmt.Errorf("no tag %s: %w", ref, err)
292 }
293 id, _, _ := strings.Cut(strings.TrimSpace(string(shown)), " ")
294 switch kind, err := objectType(c.repo, id); {
295 case err != nil:
296 return nil, err
297 case kind != "tag":
298 return nil, &sigverify.Refusal{
299 Reason: sigverify.Unsigned,
300 Detail: fmt.Sprintf("%s is a lightweight tag pointing at a %s, and carries no signature", ref, kind),
301 }
302 }
303 object, err := git(c.repo, "", "cat-file", "tag", id)
304 if err != nil {
305 return nil, err
306 }
307
308 result, tag, err := sigverify.VerifyTag(signers, object, name, opts)
309 if err != nil {
310 return nil, err
311 }
312
313 // The signature says the tag points at a commit. The repository must
314 // hold that commit, as itself and not a replacement.
315 switch kind, err := objectType(c.repo, tag.Commit); {
316 case err != nil:
317 return nil, err
318 case kind == "missing":
319 return nil, &sigverify.Refusal{
320 Reason: sigverify.TargetMissing, Signer: &result.Signer,
321 Detail: "the signed tag points at a commit this repository does not hold",
322 }
323 case kind != "commit":
324 return nil, &sigverify.Refusal{
325 Reason: sigverify.TargetNotCommit, Signer: &result.Signer,
326 Detail: fmt.Sprintf("the signed tag says it points at a commit, and the object is a %s", kind),
327 }
328 }
329 return append(resultLines(result), [2]string{"tag", tag.Name}, [2]string{"commit", tag.Commit}), nil
330}
331
332// objectType returns the type of the object id in repo, or "missing".
333func objectType(repo, id string) (string, error) {
334 out, err := git(repo, id+"\n", "cat-file", "--batch-check=%(objecttype)")
335 if err != nil {
336 return "", err
337 }
338 // batch-check answers "<id> missing" for an absent object.
339 kind := strings.TrimSpace(string(out))
340 if strings.HasSuffix(kind, " missing") {
341 return "missing", nil
342 }
343 return kind, nil
344}
345
346// gitEnv is the whole environment git runs in. Nothing is inherited: a
347// GIT_DIR, GIT_OBJECT_DIRECTORY or GIT_CONFIG_PARAMETERS in the caller's
348// environment could point git at other objects or change how it reads
349// them. User and system configuration are not read, and replacement refs
350// are off.
351var gitEnv = []string{
352 "GIT_CONFIG_NOSYSTEM=1",
353 "GIT_CONFIG_SYSTEM=/dev/null",
354 "GIT_CONFIG_GLOBAL=/dev/null",
355 "GIT_NO_REPLACE_OBJECTS=1",
356 "GIT_ATTR_NOSYSTEM=1",
357 "GIT_TERMINAL_PROMPT=0",
358 "LC_ALL=C",
359}
360
361// git runs git in repo with stdin as its input, and returns its stdout.
362// Its stderr becomes the error.
363func git(repo, stdin string, args ...string) ([]byte, error) {
364 cmd := exec.Command(gitProgram, append([]string{"--no-replace-objects", "-C", repo}, args...)...)
365 cmd.Env = gitEnv
366 cmd.Stdin = strings.NewReader(stdin)
367 var stderr bytes.Buffer
368 cmd.Stderr = &stderr
369 out, err := cmd.Output()
370 if err != nil {
371 if msg := strings.TrimSpace(stderr.String()); msg != "" {
372 return nil, fmt.Errorf("git %s: %s", args[0], msg)
373 }
374 return nil, fmt.Errorf("git %s: %w", args[0], err)
375 }
376 return out, nil
377}
378
379// report is the "name value" lines printed after "verified".
380type report [][2]string
381
382func (r report) write(w io.Writer) {
383 for _, l := range r {
384 fmt.Fprintf(w, "%s %s\n", l[0], l[1])
385 }
386}
387
388func resultLines(r *sigverify.Result) report {
389 lines := report{
390 {"namespace", r.Namespace},
391 {"principal", r.Principal},
392 {"class", string(r.Class)},
393 {"key-type", r.KeyType},
394 {"fingerprint", r.Fingerprint},
395 }
396 if r.Class == sigverify.ClassFIDO {
397 lines = append(lines,
398 [2]string{"flags", fmt.Sprintf("0x%02x", r.Flags)},
399 [2]string{"user-presence", yesNo(r.UserPresent())},
400 [2]string{"user-verification", yesNo(r.UserVerified())},
401 [2]string{"counter", fmt.Sprint(r.Counter)},
402 )
403 }
404 if r.SignerApp != "" {
405 lines = append(lines, [2]string{"signer-app", r.SignerApp})
406 }
407 return lines
408}
409
410func yesNo(b bool) string {
411 if b {
412 return "yes"
413 }
414 return "no"
415}