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