gunk-dev/the-valley

allowed.go

source79a631efa975main's published tip history
15.8 KiB
1package sigverify
2
3import (
4 "bytes"
5 "encoding/base64"
6 "errors"
7 "fmt"
8 "os"
9 "strings"
10 "time"
11)
12
13// AllowedSigners is a parsed allowed-signers file, in the format
14// ssh-keygen(1) describes under ALLOWED SIGNERS. Each line is
15//
16// principals [options] keytype base64-key [comment]
17//
18// The principals field is a comma-separated pattern list. The options are
19// the four OpenSSH defines: cert-authority, namespaces="list",
20// valid-after="time" and valid-before="time". This package adds two:
21//
22// - verify-required demands the user-verification bit on every signature
23// by that line's key. It is the same keyword sshd accepts in
24// authorized_keys.
25// - tkey-signer, or tkey-signer="version", marks the line's key as a
26// Tillitis TKey running the touch-requiring signer app. The version is
27// bookkeeping: it is reported, and never compared with anything.
28//
29// Every line has a signer class. A security key is fido-sk. An ssh-ed25519
30// key on a tkey-signer line is tkey-signer. Any other key is software. A
31// caller names the classes it accepts, and a line of any other class never
32// authorizes a signature.
33//
34// A line carrying no-touch-required is an error. User presence is not
35// negotiable here, so a file that asks to waive it is refused whole rather
36// than half-honoured. Any other unknown option, a malformed line, or a key
37// type this package does not read is an error too: ssh-keygen skips a line
38// it cannot parse, and this refuses the file instead, so a typo cannot
39// silently drop a signer's restrictions.
40type AllowedSigners struct {
41 source string
42 lines []signerLine
43}
44
45type signerLine struct {
46 number int
47 principals string
48
49 certAuthority bool
50 // hasNamespaces separates an absent namespaces option from
51 // namespaces="", which permits nothing.
52 hasNamespaces bool
53 namespaces string
54 validAfter int64 // Unix seconds; 0 when absent
55 validBefore int64
56 verifyRequired bool
57 tkeySigner bool
58 signerApp string // the tkey-signer value, if any
59
60 key []byte // the public key's wire encoding
61 class Class
62}
63
64// LoadAllowedSigners reads and parses an allowed-signers file.
65func LoadAllowedSigners(path string) (*AllowedSigners, error) {
66 data, err := os.ReadFile(path)
67 if err != nil {
68 return nil, err
69 }
70 return ParseAllowedSigners(path, data)
71}
72
73// ParseAllowedSigners parses allowed-signers lines. source names them in
74// errors and refusals, usually the file's path.
75func ParseAllowedSigners(source string, data []byte) (*AllowedSigners, error) {
76 a := &AllowedSigners{source: source}
77 for i, raw := range strings.Split(string(data), "\n") {
78 line := strings.TrimLeft(raw, " \t\r\n")
79 if line == "" || line[0] == '#' {
80 continue
81 }
82 parsed, err := parseSignerLine(line)
83 if err != nil {
84 return nil, fmt.Errorf("%s:%d: %w", source, i+1, err)
85 }
86 parsed.number = i + 1
87 a.lines = append(a.lines, parsed)
88 }
89 return a, nil
90}
91
92func parseSignerLine(line string) (signerLine, error) {
93 var l signerLine
94 principals, rest, err := principalsField(line)
95 if err != nil {
96 return l, err
97 }
98 l.principals = principals
99
100 // The options field is optional, so the next word is either a key type
101 // or the options.
102 word, _, _ := strings.Cut(rest, " ")
103 word, _, _ = strings.Cut(word, "\t")
104 if !knownKeyType(word) && looksLikeKeyType(word) {
105 return l, fmt.Errorf("keys of type %q are not supported", word)
106 }
107 if !knownKeyType(word) {
108 opts, after, err := optionsField(rest)
109 if err != nil {
110 return l, err
111 }
112 if err := l.parseOptions(opts); err != nil {
113 return l, err
114 }
115 rest = after
116 }
117
118 var keyType string
119 if l.key, keyType, err = keyField(rest); err != nil {
120 return l, err
121 }
122 switch {
123 case keyType == TypeSKEd25519 || keyType == TypeSKECDSA:
124 if l.tkeySigner {
125 return l, fmt.Errorf("tkey-signer marks a TKey's ssh-ed25519 key, and this is a %s key", keyType)
126 }
127 l.class = ClassFIDO
128 case l.tkeySigner:
129 if keyType != TypeEd25519 {
130 return l, fmt.Errorf("tkey-signer marks a TKey's ssh-ed25519 key, and this is a %s key", keyType)
131 }
132 if l.verifyRequired {
133 return l, errors.New("verify-required cannot hold for a tkey-signer line: a TKey signature cannot prove user verification")
134 }
135 if l.certAuthority {
136 return l, errors.New("a tkey-signer line cannot be a cert-authority")
137 }
138 l.class = ClassTKey
139 default:
140 l.class = ClassSoftware
141 }
142 return l, nil
143}
144
145// principalsField splits off the first field the way OpenSSH's strdelimw
146// does: up to whitespace, or a double-quoted string that may hold spaces.
147func principalsField(line string) (field, rest string, err error) {
148 i := strings.IndexAny(line, " \t\r\n\"")
149 if i < 0 {
150 return "", "", errors.New("the line has principals and no key")
151 }
152 if line[i] == '"' {
153 j := strings.IndexByte(line[i+1:], '"')
154 if j < 0 {
155 return "", "", errors.New("the principals field has no closing quote")
156 }
157 field = line[:i] + line[i+1:i+1+j]
158 rest = line[i+1+j+1:]
159 } else {
160 field, rest = line[:i], line[i+1:]
161 }
162 if field == "" {
163 return "", "", errors.New("the principals field is empty")
164 }
165 return field, strings.TrimLeft(rest, " \t\r\n"), nil
166}
167
168// optionsField splits off the options: everything up to the first space or
169// tab outside double quotes, where \" does not end a quote.
170func optionsField(rest string) (opts, after string, err error) {
171 quoted := false
172 i := 0
173 for ; i < len(rest) && (quoted || (rest[i] != ' ' && rest[i] != '\t')); i++ {
174 switch {
175 case rest[i] == '\\' && i+1 < len(rest) && rest[i+1] == '"':
176 i++
177 case rest[i] == '"':
178 quoted = !quoted
179 }
180 }
181 if quoted {
182 return "", "", errors.New("the options have an unclosed quote")
183 }
184 after = strings.TrimLeft(rest[i:], " \t")
185 if after == "" {
186 return "", "", errors.New("the line has no key")
187 }
188 return rest[:i], after, nil
189}
190
191// parseOptions reads comma-separated options, as sshsigopt_parse does.
192// Keywords are case-insensitive, and every value is double-quoted.
193func (l *signerLine) parseOptions(opts string) error {
194 seen := map[string]bool{}
195 for opts != "" {
196 name := opts
197 if i := strings.IndexAny(opts, "=,"); i >= 0 {
198 name = opts[:i]
199 }
200 opts = opts[len(name):]
201 name = strings.ToLower(name)
202
203 var value string
204 hasValue := strings.HasPrefix(opts, "=")
205 if hasValue {
206 var err error
207 if value, opts, err = dequote(opts[1:]); err != nil {
208 return fmt.Errorf("option %s: %w", name, err)
209 }
210 }
211 if seen[name] {
212 return fmt.Errorf("option %s appears twice", name)
213 }
214 seen[name] = true
215
216 switch {
217 case name == "cert-authority" && !hasValue:
218 l.certAuthority = true
219 case name == "verify-required" && !hasValue:
220 l.verifyRequired = true
221 case name == "tkey-signer":
222 if hasValue && !validSignerApp(value) {
223 return fmt.Errorf("tkey-signer=%q is not a version: use 1 to 64 letters, digits and . _ + : -", value)
224 }
225 l.tkeySigner, l.signerApp = true, value
226 case name == "namespaces" && hasValue:
227 l.hasNamespaces, l.namespaces = true, value
228 case name == "valid-after" && hasValue:
229 t, err := ParseTime(value)
230 if err != nil {
231 return fmt.Errorf("valid-after: %w", err)
232 }
233 l.validAfter = t.Unix()
234 case name == "valid-before" && hasValue:
235 t, err := ParseTime(value)
236 if err != nil {
237 return fmt.Errorf("valid-before: %w", err)
238 }
239 l.validBefore = t.Unix()
240 case name == "no-touch-required":
241 return errors.New("no-touch-required is refused: this verifier always requires user presence")
242 default:
243 return fmt.Errorf("unknown option %q", name)
244 }
245
246 if opts == "" {
247 break
248 }
249 if opts[0] != ',' {
250 return fmt.Errorf("option %s is followed by %q where a comma belongs", name, opts[0])
251 }
252 if opts = opts[1:]; opts == "" {
253 return errors.New("the options end with a comma")
254 }
255 }
256 if l.validAfter != 0 && l.validBefore != 0 && l.validBefore <= l.validAfter {
257 return errors.New("valid-before is not after valid-after")
258 }
259 return nil
260}
261
262// dequote reads a double-quoted value, where \" stands for a quote, and
263// returns what follows the closing quote.
264func dequote(s string) (value, rest string, err error) {
265 if !strings.HasPrefix(s, `"`) {
266 return "", "", errors.New("the value is not in double quotes")
267 }
268 var b strings.Builder
269 for i := 1; i < len(s); i++ {
270 switch {
271 case s[i] == '\\' && i+1 < len(s) && s[i+1] == '"':
272 b.WriteByte('"')
273 i++
274 case s[i] == '"':
275 return b.String(), s[i+1:], nil
276 default:
277 b.WriteByte(s[i])
278 }
279 }
280 return "", "", errors.New("the value has no closing quote")
281}
282
283// validSignerApp holds a tkey-signer version to a plain token.
284func validSignerApp(v string) bool {
285 if len(v) == 0 || len(v) > 64 {
286 return false
287 }
288 for _, c := range v {
289 ok := c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("._+:-", c)
290 if !ok {
291 return false
292 }
293 }
294 return true
295}
296
297// keyField reads "keytype base64 [comment]" and returns the key's wire
298// encoding and type.
299func keyField(rest string) ([]byte, string, error) {
300 fields := strings.Fields(rest)
301 if len(fields) < 2 {
302 return nil, "", errors.New("the line has no key")
303 }
304 typ := fields[0]
305 if !knownKeyType(typ) {
306 return nil, "", fmt.Errorf("keys of type %q are not supported", typ)
307 }
308 blob, err := base64.StdEncoding.Strict().DecodeString(fields[1])
309 if err != nil {
310 return nil, "", fmt.Errorf("the %s key is not canonical base64: %w", typ, err)
311 }
312 key, err := parsePublicKey(blob)
313 if err != nil {
314 return nil, "", err
315 }
316 if key.typ != typ {
317 return nil, "", fmt.Errorf("the key is labelled %s but holds a %s key", typ, key.typ)
318 }
319 return blob, typ, nil
320}
321
322// looksLikeKeyType catches OpenSSH key types this package does not read,
323// such as ssh-dss or a certificate type, so the error names the key rather
324// than calling it an unknown option.
325func looksLikeKeyType(word string) bool {
326 if strings.ContainsAny(word, "=,") {
327 return false
328 }
329 for _, prefix := range []string{"ssh-", "sk-", "ecdsa-", "webauthn-", "rsa-"} {
330 if strings.HasPrefix(word, prefix) {
331 return true
332 }
333 }
334 return strings.HasSuffix(word, "@openssh.com")
335}
336
337func knownKeyType(word string) bool {
338 switch word {
339 case TypeSKEd25519, TypeSKECDSA, TypeEd25519, TypeECDSA256, TypeECDSA384, TypeECDSA521, TypeRSA:
340 return true
341 }
342 return false
343}
344
345// ParseTime reads a time in the form allowed-signers options and
346// `ssh-keygen -O verify-time=` take: YYYYMMDD, YYYYMMDDHHMM or
347// YYYYMMDDHHMMSS, in UTC when followed by Z or UTC and in local time
348// otherwise.
349func ParseTime(s string) (time.Time, error) {
350 loc, digits := time.Local, s
351 if t, ok := strings.CutSuffix(strings.ToUpper(s), "UTC"); ok && len(s) > 3 {
352 loc, digits = time.UTC, s[:len(t)]
353 } else if t, ok := strings.CutSuffix(strings.ToUpper(s), "Z"); ok && len(s) > 1 {
354 loc, digits = time.UTC, s[:len(t)]
355 }
356 layouts := map[int]string{8: "20060102", 12: "200601021504", 14: "20060102150405"}
357 layout, ok := layouts[len(digits)]
358 if !ok {
359 return time.Time{}, fmt.Errorf("%q is not YYYYMMDD[HHMM[SS]][Z]", s)
360 }
361 t, err := time.ParseInLocation(layout, digits, loc)
362 if err != nil {
363 return time.Time{}, fmt.Errorf("%q is not YYYYMMDD[HHMM[SS]][Z]", s)
364 }
365 if t.Unix() <= 0 {
366 return time.Time{}, fmt.Errorf("%q is not after 1970", s)
367 }
368 return t, nil
369}
370
371// request is what lookup matches lines against.
372type request struct {
373 key []byte
374 principal string // empty only when any principal will do
375 namespace string
376 at time.Time
377 classes map[Class]bool
378}
379
380// match is what the lines that matched a request say about it.
381type match struct {
382 principal string
383 class Class
384 signerApp string
385 uvRequired bool
386}
387
388// lookup finds the lines that let a key sign. It mirrors
389// sshsig_check_allowed_keys, and adds the signer class. A line matches
390// when:
391//
392// - its key is the request's key
393// - its class is one the request accepts
394// - its principals pattern list matches the principal, unless any
395// principal will do
396// - its namespaces, if present, match the namespace
397// - the request's time falls in its validity window
398//
399// Certificate-authority lines never match, because this package does not
400// verify certificates.
401//
402// With no match, lookup returns the most specific refusal any line
403// produced. With a match, it reports the first matching line's class and
404// signer app, and the principal: the requested one, or with any principal
405// that line's principals field. UV is required if any matching line
406// carries verify-required, so the strictest line holds.
407func (a *AllowedSigners) lookup(req request) (*match, *Refusal) {
408 refusal := &Refusal{Reason: UnknownKey, Detail: fmt.Sprintf("no line in %s lists this key", a.source)}
409 rank := 0
410 note := func(r int, reason Reason, detail string) {
411 if r > rank {
412 rank, refusal = r, &Refusal{Reason: reason, Detail: detail}
413 }
414 }
415 now := req.at.Unix()
416 var m *match
417 for _, l := range a.lines {
418 if l.certAuthority || !bytes.Equal(l.key, req.key) {
419 continue
420 }
421 where := fmt.Sprintf("%s:%d", a.source, l.number)
422 switch {
423 case !req.classes[l.class]:
424 note(1, ClassNotAllowed, fmt.Sprintf("%s lists this key as a %s signer, and this call accepts only %s", where, l.class, classList(req.classes)))
425 case req.principal != "" && matchPatternList(req.principal, l.principals) != 1:
426 note(2, PrincipalNotAllowed, fmt.Sprintf("%s lists this key for %q, which does not match %q", where, l.principals, req.principal))
427 case l.hasNamespaces && matchPatternList(req.namespace, l.namespaces) != 1:
428 note(3, NamespaceNotAllowed, fmt.Sprintf("%s allows this key only in namespaces %q, which do not match %q", where, l.namespaces, req.namespace))
429 case l.validAfter != 0 && now < l.validAfter:
430 note(4, NotYetValid, fmt.Sprintf("%s makes this key valid only from %s, and the verify time is %s", where, stamp(l.validAfter), stamp(now)))
431 case l.validBefore != 0 && now > l.validBefore:
432 note(4, Expired, fmt.Sprintf("%s made this key valid only until %s, and the verify time is %s", where, stamp(l.validBefore), stamp(now)))
433 default:
434 if m == nil {
435 m = &match{principal: req.principal, class: l.class, signerApp: l.signerApp}
436 if m.principal == "" {
437 m.principal = l.principals
438 }
439 }
440 m.uvRequired = m.uvRequired || l.verifyRequired
441 }
442 }
443 if m == nil {
444 return nil, refusal
445 }
446 return m, nil
447}
448
449func stamp(unix int64) string {
450 return time.Unix(unix, 0).UTC().Format(time.RFC3339)
451}
452
453// matchPatternList is OpenSSH's match_pattern_list, transliterated. It
454// returns 1 when s matches a pattern in the comma-separated list, -1 when
455// it matches a pattern negated with "!", which overrides any positive
456// match, and 0 otherwise. Matching is case-sensitive. As in OpenSSH, a
457// pattern of 1023 bytes or more makes the whole list match nothing.
458func matchPatternList(s, list string) int {
459 const maxPattern = 1024 - 1 // OpenSSH's sub[1024] buffer, less its NUL
460 positive := 0
461 for i := 0; i < len(list); {
462 negated := list[i] == '!'
463 if negated {
464 i++
465 }
466 j := i
467 for j < len(list) && j-i < maxPattern && list[j] != ',' {
468 j++
469 }
470 if j-i >= maxPattern {
471 return 0
472 }
473 pattern := list[i:j]
474 i = j
475 if i < len(list) && list[i] == ',' {
476 i++
477 }
478 if matchPattern(s, pattern) {
479 if negated {
480 return -1
481 }
482 positive = 1
483 }
484 }
485 return positive
486}
487
488// matchPattern is OpenSSH's match_pattern, transliterated: "*" matches any
489// run of bytes, "?" matches one byte, and every other byte matches itself.
490// A "*" or "?" in the pattern is always a wildcard, even where s holds the
491// same byte.
492func matchPattern(s, pattern string) bool {
493 for {
494 if pattern == "" {
495 return s == ""
496 }
497 if pattern[0] == '*' {
498 pattern = strings.TrimLeft(pattern, "*")
499 if pattern == "" {
500 return true
501 }
502 if pattern[0] != '?' {
503 for i := 0; i < len(s); i++ {
504 if s[i] == pattern[0] && matchPattern(s[i+1:], pattern[1:]) {
505 return true
506 }
507 }
508 return false
509 }
510 for i := 0; i < len(s); i++ {
511 if matchPattern(s[i:], pattern) {
512 return true
513 }
514 }
515 return false
516 }
517 if s == "" {
518 return false
519 }
520 if pattern[0] != '?' && pattern[0] != s[0] {
521 return false
522 }
523 s, pattern = s[1:], pattern[1:]
524 }
525}