gunk-dev/the-valley

allowed.go

sourcefe4ab5bf3cabmain's published tip history
12.5 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 one,
21// verify-required, which demands the user-verification bit on every
22// signature by that line's key. It is the same keyword sshd accepts in
23// authorized_keys.
24//
25// A line carrying no-touch-required is an error. User presence is not
26// negotiable here, so a file that asks to waive it is refused whole rather
27// than half-honoured. Any other unknown option, a malformed line, or a key
28// type this package does not read is an error too: ssh-keygen skips a line
29// it cannot parse, and this refuses the file instead, so a typo cannot
30// silently drop a signer's restrictions.
31type AllowedSigners struct {
32 source string
33 lines []signerLine
34}
35
36type signerLine struct {
37 number int
38 principals string
39
40 certAuthority bool
41 // hasNamespaces separates an absent namespaces option from
42 // namespaces="", which permits nothing.
43 hasNamespaces bool
44 namespaces string
45 validAfter int64 // Unix seconds; 0 when absent
46 validBefore int64
47 verifyRequired bool
48
49 key []byte // the public key's wire encoding
50}
51
52// LoadAllowedSigners reads and parses an allowed-signers file.
53func LoadAllowedSigners(path string) (*AllowedSigners, error) {
54 data, err := os.ReadFile(path)
55 if err != nil {
56 return nil, err
57 }
58 return ParseAllowedSigners(path, data)
59}
60
61// ParseAllowedSigners parses allowed-signers lines. source names them in
62// errors and refusals, usually the file's path.
63func ParseAllowedSigners(source string, data []byte) (*AllowedSigners, error) {
64 a := &AllowedSigners{source: source}
65 for i, raw := range strings.Split(string(data), "\n") {
66 line := strings.TrimLeft(raw, " \t\r\n")
67 if line == "" || line[0] == '#' {
68 continue
69 }
70 parsed, err := parseSignerLine(line)
71 if err != nil {
72 return nil, fmt.Errorf("%s:%d: %w", source, i+1, err)
73 }
74 parsed.number = i + 1
75 a.lines = append(a.lines, parsed)
76 }
77 return a, nil
78}
79
80func parseSignerLine(line string) (signerLine, error) {
81 var l signerLine
82 principals, rest, err := principalsField(line)
83 if err != nil {
84 return l, err
85 }
86 l.principals = principals
87
88 // The options field is optional, so the next word is either a key type
89 // or the options.
90 word, _, _ := strings.Cut(rest, " ")
91 word, _, _ = strings.Cut(word, "\t")
92 if !knownKeyType(word) && looksLikeKeyType(word) {
93 return l, fmt.Errorf("keys of type %q are not supported", word)
94 }
95 if !knownKeyType(word) {
96 opts, after, err := optionsField(rest)
97 if err != nil {
98 return l, err
99 }
100 if err := l.parseOptions(opts); err != nil {
101 return l, err
102 }
103 rest = after
104 }
105
106 l.key, err = keyField(rest)
107 return l, err
108}
109
110// principalsField splits off the first field the way OpenSSH's strdelimw
111// does: up to whitespace, or a double-quoted string that may hold spaces.
112func principalsField(line string) (field, rest string, err error) {
113 i := strings.IndexAny(line, " \t\r\n\"")
114 if i < 0 {
115 return "", "", errors.New("the line has principals and no key")
116 }
117 if line[i] == '"' {
118 j := strings.IndexByte(line[i+1:], '"')
119 if j < 0 {
120 return "", "", errors.New("the principals field has no closing quote")
121 }
122 field = line[:i] + line[i+1:i+1+j]
123 rest = line[i+1+j+1:]
124 } else {
125 field, rest = line[:i], line[i+1:]
126 }
127 if field == "" {
128 return "", "", errors.New("the principals field is empty")
129 }
130 return field, strings.TrimLeft(rest, " \t\r\n"), nil
131}
132
133// optionsField splits off the options: everything up to the first space or
134// tab outside double quotes, where \" does not end a quote.
135func optionsField(rest string) (opts, after string, err error) {
136 quoted := false
137 i := 0
138 for ; i < len(rest) && (quoted || (rest[i] != ' ' && rest[i] != '\t')); i++ {
139 switch {
140 case rest[i] == '\\' && i+1 < len(rest) && rest[i+1] == '"':
141 i++
142 case rest[i] == '"':
143 quoted = !quoted
144 }
145 }
146 if quoted {
147 return "", "", errors.New("the options have an unclosed quote")
148 }
149 after = strings.TrimLeft(rest[i:], " \t")
150 if after == "" {
151 return "", "", errors.New("the line has no key")
152 }
153 return rest[:i], after, nil
154}
155
156// parseOptions reads comma-separated options, as sshsigopt_parse does.
157// Keywords are case-insensitive, and every value is double-quoted.
158func (l *signerLine) parseOptions(opts string) error {
159 seen := map[string]bool{}
160 for opts != "" {
161 name := opts
162 if i := strings.IndexAny(opts, "=,"); i >= 0 {
163 name = opts[:i]
164 }
165 opts = opts[len(name):]
166 name = strings.ToLower(name)
167
168 var value string
169 hasValue := strings.HasPrefix(opts, "=")
170 if hasValue {
171 var err error
172 if value, opts, err = dequote(opts[1:]); err != nil {
173 return fmt.Errorf("option %s: %w", name, err)
174 }
175 }
176 if seen[name] {
177 return fmt.Errorf("option %s appears twice", name)
178 }
179 seen[name] = true
180
181 switch {
182 case name == "cert-authority" && !hasValue:
183 l.certAuthority = true
184 case name == "verify-required" && !hasValue:
185 l.verifyRequired = true
186 case name == "namespaces" && hasValue:
187 l.hasNamespaces, l.namespaces = true, value
188 case name == "valid-after" && hasValue:
189 t, err := ParseTime(value)
190 if err != nil {
191 return fmt.Errorf("valid-after: %w", err)
192 }
193 l.validAfter = t.Unix()
194 case name == "valid-before" && hasValue:
195 t, err := ParseTime(value)
196 if err != nil {
197 return fmt.Errorf("valid-before: %w", err)
198 }
199 l.validBefore = t.Unix()
200 case name == "no-touch-required":
201 return errors.New("no-touch-required is refused: this verifier always requires user presence")
202 default:
203 return fmt.Errorf("unknown option %q", name)
204 }
205
206 if opts == "" {
207 break
208 }
209 if opts[0] != ',' {
210 return fmt.Errorf("option %s is followed by %q where a comma belongs", name, opts[0])
211 }
212 if opts = opts[1:]; opts == "" {
213 return errors.New("the options end with a comma")
214 }
215 }
216 if l.validAfter != 0 && l.validBefore != 0 && l.validBefore <= l.validAfter {
217 return errors.New("valid-before is not after valid-after")
218 }
219 return nil
220}
221
222// dequote reads a double-quoted value, where \" stands for a quote, and
223// returns what follows the closing quote.
224func dequote(s string) (value, rest string, err error) {
225 if !strings.HasPrefix(s, `"`) {
226 return "", "", errors.New("the value is not in double quotes")
227 }
228 var b strings.Builder
229 for i := 1; i < len(s); i++ {
230 switch {
231 case s[i] == '\\' && i+1 < len(s) && s[i+1] == '"':
232 b.WriteByte('"')
233 i++
234 case s[i] == '"':
235 return b.String(), s[i+1:], nil
236 default:
237 b.WriteByte(s[i])
238 }
239 }
240 return "", "", errors.New("the value has no closing quote")
241}
242
243// keyField reads "keytype base64 [comment]" and returns the key's wire
244// encoding.
245func keyField(rest string) ([]byte, error) {
246 fields := strings.Fields(rest)
247 if len(fields) < 2 {
248 return nil, errors.New("the line has no key")
249 }
250 typ := fields[0]
251 if !knownKeyType(typ) {
252 return nil, fmt.Errorf("keys of type %q are not supported", typ)
253 }
254 blob, err := base64.StdEncoding.DecodeString(fields[1])
255 if err != nil {
256 return nil, fmt.Errorf("the %s key is not base64: %w", typ, err)
257 }
258 key, err := parsePublicKey(blob)
259 if err != nil {
260 return nil, err
261 }
262 if key.typ != typ {
263 return nil, fmt.Errorf("the key is labelled %s but holds a %s key", typ, key.typ)
264 }
265 return blob, nil
266}
267
268// looksLikeKeyType catches OpenSSH key types this package does not read,
269// such as ssh-dss or a certificate type, so the error names the key rather
270// than calling it an unknown option.
271func looksLikeKeyType(word string) bool {
272 if strings.ContainsAny(word, "=,") {
273 return false
274 }
275 for _, prefix := range []string{"ssh-", "sk-", "ecdsa-", "webauthn-", "rsa-"} {
276 if strings.HasPrefix(word, prefix) {
277 return true
278 }
279 }
280 return strings.HasSuffix(word, "@openssh.com")
281}
282
283func knownKeyType(word string) bool {
284 switch word {
285 case TypeSKEd25519, TypeSKECDSA, TypeEd25519, TypeECDSA256, TypeECDSA384, TypeECDSA521, TypeRSA:
286 return true
287 }
288 return false
289}
290
291// ParseTime reads a time in the form allowed-signers options and
292// `ssh-keygen -O verify-time=` take: YYYYMMDD, YYYYMMDDHHMM or
293// YYYYMMDDHHMMSS, in UTC when followed by Z or UTC and in local time
294// otherwise.
295func ParseTime(s string) (time.Time, error) {
296 loc, digits := time.Local, s
297 if t, ok := strings.CutSuffix(strings.ToUpper(s), "UTC"); ok && len(s) > 3 {
298 loc, digits = time.UTC, s[:len(t)]
299 } else if t, ok := strings.CutSuffix(strings.ToUpper(s), "Z"); ok && len(s) > 1 {
300 loc, digits = time.UTC, s[:len(t)]
301 }
302 layouts := map[int]string{8: "20060102", 12: "200601021504", 14: "20060102150405"}
303 layout, ok := layouts[len(digits)]
304 if !ok {
305 return time.Time{}, fmt.Errorf("%q is not YYYYMMDD[HHMM[SS]][Z]", s)
306 }
307 t, err := time.ParseInLocation(layout, digits, loc)
308 if err != nil {
309 return time.Time{}, fmt.Errorf("%q is not YYYYMMDD[HHMM[SS]][Z]", s)
310 }
311 if t.Unix() <= 0 {
312 return time.Time{}, fmt.Errorf("%q is not after 1970", s)
313 }
314 return t, nil
315}
316
317// lookup finds the lines that let key sign in namespace at time at, for
318// principal if one is given. It mirrors sshsig_check_allowed_keys: a line
319// matches when its key is key, its principals pattern list matches the
320// principal, its namespaces (if any) match the namespace, and at falls in
321// its validity window. Certificate-authority lines never match, because
322// this package does not verify certificates.
323//
324// With no match it returns the most specific refusal any line produced.
325// With a match it returns the first matching line's principals field, and
326// whether any matching line carries verify-required.
327func (a *AllowedSigners) lookup(key []byte, principal, namespace string, at time.Time) (principals string, uvRequired bool, refusal *Refusal) {
328 refusal = &Refusal{Reason: UnknownKey, Detail: fmt.Sprintf("no line in %s lists this key", a.source)}
329 rank := 0
330 note := func(r int, reason Reason, detail string) {
331 if r > rank {
332 rank, refusal = r, &Refusal{Reason: reason, Detail: detail}
333 }
334 }
335 now := at.Unix()
336 found := false
337 for _, l := range a.lines {
338 if l.certAuthority || !bytes.Equal(l.key, key) {
339 continue
340 }
341 where := fmt.Sprintf("%s:%d", a.source, l.number)
342 switch {
343 case principal != "" && matchPatternList(principal, l.principals) != 1:
344 note(1, PrincipalNotAllowed, fmt.Sprintf("%s lists this key for %q, which does not match %q", where, l.principals, principal))
345 case l.hasNamespaces && matchPatternList(namespace, l.namespaces) != 1:
346 note(2, NamespaceNotAllowed, fmt.Sprintf("%s allows this key only in namespaces %q, which do not match %q", where, l.namespaces, namespace))
347 case l.validAfter != 0 && now < l.validAfter:
348 note(3, NotYetValid, fmt.Sprintf("%s makes this key valid only from %s, and the verify time is %s", where, stamp(l.validAfter), stamp(now)))
349 case l.validBefore != 0 && now > l.validBefore:
350 note(3, Expired, fmt.Sprintf("%s made this key valid only until %s, and the verify time is %s", where, stamp(l.validBefore), stamp(now)))
351 default:
352 if !found {
353 principals = l.principals
354 if principal != "" {
355 principals = principal
356 }
357 }
358 found = true
359 uvRequired = uvRequired || l.verifyRequired
360 }
361 }
362 if !found {
363 return "", false, refusal
364 }
365 return principals, uvRequired, nil
366}
367
368func stamp(unix int64) string {
369 return time.Unix(unix, 0).UTC().Format(time.RFC3339)
370}
371
372// matchPatternList is OpenSSH's match_pattern_list. It returns 1 when s
373// matches a pattern in the comma-separated list, -1 when it matches a
374// pattern negated with "!", which overrides any positive match, and 0
375// otherwise. Matching is case-sensitive.
376func matchPatternList(s, list string) int {
377 if list == "" {
378 return 0
379 }
380 positive := 0
381 for _, pattern := range strings.Split(list, ",") {
382 negated := strings.HasPrefix(pattern, "!")
383 if negated {
384 pattern = pattern[1:]
385 }
386 if matchPattern(s, pattern) {
387 if negated {
388 return -1
389 }
390 positive = 1
391 }
392 }
393 return positive
394}
395
396// matchPattern is OpenSSH's match_pattern: "*" matches any run of bytes,
397// "?" matches one byte, and every other byte matches itself.
398func matchPattern(s, pattern string) bool {
399 si, pi := 0, 0
400 star, mark := -1, 0
401 for si < len(s) {
402 switch {
403 case pi < len(pattern) && (pattern[pi] == '?' || pattern[pi] == s[si]):
404 si++
405 pi++
406 case pi < len(pattern) && pattern[pi] == '*':
407 star, mark = pi, si
408 pi++
409 case star >= 0:
410 mark++
411 si, pi = mark, star+1
412 default:
413 return false
414 }
415 }
416 for pi < len(pattern) && pattern[pi] == '*' {
417 pi++
418 }
419 return pi == len(pattern)
420}