github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/crypto/x509/parser.go (about) 1 // Copyright 2021 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package x509 6 7 import ( 8 "bytes" 9 "crypto/dsa" 10 "crypto/ecdh" 11 "crypto/ecdsa" 12 "crypto/ed25519" 13 "crypto/elliptic" 14 "crypto/rsa" 15 "crypto/x509/pkix" 16 "encoding/asn1" 17 "errors" 18 "fmt" 19 "math/big" 20 "net" 21 "net/url" 22 "strconv" 23 "strings" 24 "time" 25 "unicode/utf16" 26 "unicode/utf8" 27 28 "golang.org/x/crypto/cryptobyte" 29 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1" 30 ) 31 32 // isPrintable reports whether the given b is in the ASN.1 PrintableString set. 33 // This is a simplified version of encoding/asn1.isPrintable. 34 func isPrintable(b byte) bool { 35 return 'a' <= b && b <= 'z' || 36 'A' <= b && b <= 'Z' || 37 '0' <= b && b <= '9' || 38 '\'' <= b && b <= ')' || 39 '+' <= b && b <= '/' || 40 b == ' ' || 41 b == ':' || 42 b == '=' || 43 b == '?' || 44 // This is technically not allowed in a PrintableString. 45 // However, x509 certificates with wildcard strings don't 46 // always use the correct string type so we permit it. 47 b == '*' || 48 // This is not technically allowed either. However, not 49 // only is it relatively common, but there are also a 50 // handful of CA certificates that contain it. At least 51 // one of which will not expire until 2027. 52 b == '&' 53 } 54 55 // parseASN1String parses the ASN.1 string types T61String, PrintableString, 56 // UTF8String, BMPString, IA5String, and NumericString. This is mostly copied 57 // from the respective encoding/asn1.parse... methods, rather than just 58 // increasing the API surface of that package. 59 func parseASN1String(tag cryptobyte_asn1.Tag, value []byte) (string, error) { 60 switch tag { 61 case cryptobyte_asn1.T61String: 62 return string(value), nil 63 case cryptobyte_asn1.PrintableString: 64 for _, b := range value { 65 if !isPrintable(b) { 66 return "", errors.New("invalid PrintableString") 67 } 68 } 69 return string(value), nil 70 case cryptobyte_asn1.UTF8String: 71 if !utf8.Valid(value) { 72 return "", errors.New("invalid UTF-8 string") 73 } 74 return string(value), nil 75 case cryptobyte_asn1.Tag(asn1.TagBMPString): 76 if len(value)%2 != 0 { 77 return "", errors.New("invalid BMPString") 78 } 79 80 // Strip terminator if present. 81 if l := len(value); l >= 2 && value[l-1] == 0 && value[l-2] == 0 { 82 value = value[:l-2] 83 } 84 85 s := make([]uint16, 0, len(value)/2) 86 for len(value) > 0 { 87 s = append(s, uint16(value[0])<<8+uint16(value[1])) 88 value = value[2:] 89 } 90 91 return string(utf16.Decode(s)), nil 92 case cryptobyte_asn1.IA5String: 93 s := string(value) 94 if isIA5String(s) != nil { 95 return "", errors.New("invalid IA5String") 96 } 97 return s, nil 98 case cryptobyte_asn1.Tag(asn1.TagNumericString): 99 for _, b := range value { 100 if !('0' <= b && b <= '9' || b == ' ') { 101 return "", errors.New("invalid NumericString") 102 } 103 } 104 return string(value), nil 105 } 106 return "", fmt.Errorf("unsupported string type: %v", tag) 107 } 108 109 // parseName parses a DER encoded Name as defined in RFC 5280. We may 110 // want to export this function in the future for use in crypto/tls. 111 func parseName(raw cryptobyte.String) (*pkix.RDNSequence, error) { 112 if !raw.ReadASN1(&raw, cryptobyte_asn1.SEQUENCE) { 113 return nil, errors.New("x509: invalid RDNSequence") 114 } 115 116 var rdnSeq pkix.RDNSequence 117 for !raw.Empty() { 118 var rdnSet pkix.RelativeDistinguishedNameSET 119 var set cryptobyte.String 120 if !raw.ReadASN1(&set, cryptobyte_asn1.SET) { 121 return nil, errors.New("x509: invalid RDNSequence") 122 } 123 for !set.Empty() { 124 var atav cryptobyte.String 125 if !set.ReadASN1(&atav, cryptobyte_asn1.SEQUENCE) { 126 return nil, errors.New("x509: invalid RDNSequence: invalid attribute") 127 } 128 var attr pkix.AttributeTypeAndValue 129 if !atav.ReadASN1ObjectIdentifier(&attr.Type) { 130 return nil, errors.New("x509: invalid RDNSequence: invalid attribute type") 131 } 132 var rawValue cryptobyte.String 133 var valueTag cryptobyte_asn1.Tag 134 if !atav.ReadAnyASN1(&rawValue, &valueTag) { 135 return nil, errors.New("x509: invalid RDNSequence: invalid attribute value") 136 } 137 var err error 138 attr.Value, err = parseASN1String(valueTag, rawValue) 139 if err != nil { 140 return nil, fmt.Errorf("x509: invalid RDNSequence: invalid attribute value: %s", err) 141 } 142 rdnSet = append(rdnSet, attr) 143 } 144 145 rdnSeq = append(rdnSeq, rdnSet) 146 } 147 148 return &rdnSeq, nil 149 } 150 151 func parseAI(der cryptobyte.String) (pkix.AlgorithmIdentifier, error) { 152 ai := pkix.AlgorithmIdentifier{} 153 if !der.ReadASN1ObjectIdentifier(&ai.Algorithm) { 154 return ai, errors.New("x509: malformed OID") 155 } 156 if der.Empty() { 157 return ai, nil 158 } 159 var params cryptobyte.String 160 var tag cryptobyte_asn1.Tag 161 if !der.ReadAnyASN1Element(¶ms, &tag) { 162 return ai, errors.New("x509: malformed parameters") 163 } 164 ai.Parameters.Tag = int(tag) 165 ai.Parameters.FullBytes = params 166 return ai, nil 167 } 168 169 func parseTime(der *cryptobyte.String) (time.Time, error) { 170 var t time.Time 171 switch { 172 case der.PeekASN1Tag(cryptobyte_asn1.UTCTime): 173 if !der.ReadASN1UTCTime(&t) { 174 return t, errors.New("x509: malformed UTCTime") 175 } 176 case der.PeekASN1Tag(cryptobyte_asn1.GeneralizedTime): 177 if !der.ReadASN1GeneralizedTime(&t) { 178 return t, errors.New("x509: malformed GeneralizedTime") 179 } 180 default: 181 return t, errors.New("x509: unsupported time format") 182 } 183 return t, nil 184 } 185 186 func parseValidity(der cryptobyte.String) (time.Time, time.Time, error) { 187 notBefore, err := parseTime(&der) 188 if err != nil { 189 return time.Time{}, time.Time{}, err 190 } 191 notAfter, err := parseTime(&der) 192 if err != nil { 193 return time.Time{}, time.Time{}, err 194 } 195 196 return notBefore, notAfter, nil 197 } 198 199 func parseExtension(der cryptobyte.String) (pkix.Extension, error) { 200 var ext pkix.Extension 201 if !der.ReadASN1ObjectIdentifier(&ext.Id) { 202 return ext, errors.New("x509: malformed extension OID field") 203 } 204 if der.PeekASN1Tag(cryptobyte_asn1.BOOLEAN) { 205 if !der.ReadASN1Boolean(&ext.Critical) { 206 return ext, errors.New("x509: malformed extension critical field") 207 } 208 } 209 var val cryptobyte.String 210 if !der.ReadASN1(&val, cryptobyte_asn1.OCTET_STRING) { 211 return ext, errors.New("x509: malformed extension value field") 212 } 213 ext.Value = val 214 return ext, nil 215 } 216 217 func parsePublicKey(keyData *publicKeyInfo) (any, error) { 218 oid := keyData.Algorithm.Algorithm 219 params := keyData.Algorithm.Parameters 220 der := cryptobyte.String(keyData.PublicKey.RightAlign()) 221 switch { 222 case oid.Equal(oidPublicKeyRSA): 223 // RSA public keys must have a NULL in the parameters. 224 // See RFC 3279, Section 2.3.1. 225 if !bytes.Equal(params.FullBytes, asn1.NullBytes) { 226 return nil, errors.New("x509: RSA key missing NULL parameters") 227 } 228 229 p := &pkcs1PublicKey{N: new(big.Int)} 230 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) { 231 return nil, errors.New("x509: invalid RSA public key") 232 } 233 if !der.ReadASN1Integer(p.N) { 234 return nil, errors.New("x509: invalid RSA modulus") 235 } 236 if !der.ReadASN1Integer(&p.E) { 237 return nil, errors.New("x509: invalid RSA public exponent") 238 } 239 240 if p.N.Sign() <= 0 { 241 return nil, errors.New("x509: RSA modulus is not a positive number") 242 } 243 if p.E <= 0 { 244 return nil, errors.New("x509: RSA public exponent is not a positive number") 245 } 246 247 pub := &rsa.PublicKey{ 248 E: p.E, 249 N: p.N, 250 } 251 return pub, nil 252 case oid.Equal(oidPublicKeyECDSA): 253 paramsDer := cryptobyte.String(params.FullBytes) 254 namedCurveOID := new(asn1.ObjectIdentifier) 255 if !paramsDer.ReadASN1ObjectIdentifier(namedCurveOID) { 256 return nil, errors.New("x509: invalid ECDSA parameters") 257 } 258 namedCurve := namedCurveFromOID(*namedCurveOID) 259 if namedCurve == nil { 260 return nil, errors.New("x509: unsupported elliptic curve") 261 } 262 x, y := elliptic.Unmarshal(namedCurve, der) 263 if x == nil { 264 return nil, errors.New("x509: failed to unmarshal elliptic curve point") 265 } 266 pub := &ecdsa.PublicKey{ 267 Curve: namedCurve, 268 X: x, 269 Y: y, 270 } 271 return pub, nil 272 case oid.Equal(oidPublicKeyEd25519): 273 // RFC 8410, Section 3 274 // > For all of the OIDs, the parameters MUST be absent. 275 if len(params.FullBytes) != 0 { 276 return nil, errors.New("x509: Ed25519 key encoded with illegal parameters") 277 } 278 if len(der) != ed25519.PublicKeySize { 279 return nil, errors.New("x509: wrong Ed25519 public key size") 280 } 281 return ed25519.PublicKey(der), nil 282 case oid.Equal(oidPublicKeyX25519): 283 // RFC 8410, Section 3 284 // > For all of the OIDs, the parameters MUST be absent. 285 if len(params.FullBytes) != 0 { 286 return nil, errors.New("x509: X25519 key encoded with illegal parameters") 287 } 288 return ecdh.X25519().NewPublicKey(der) 289 case oid.Equal(oidPublicKeyDSA): 290 y := new(big.Int) 291 if !der.ReadASN1Integer(y) { 292 return nil, errors.New("x509: invalid DSA public key") 293 } 294 pub := &dsa.PublicKey{ 295 Y: y, 296 Parameters: dsa.Parameters{ 297 P: new(big.Int), 298 Q: new(big.Int), 299 G: new(big.Int), 300 }, 301 } 302 paramsDer := cryptobyte.String(params.FullBytes) 303 if !paramsDer.ReadASN1(¶msDer, cryptobyte_asn1.SEQUENCE) || 304 !paramsDer.ReadASN1Integer(pub.Parameters.P) || 305 !paramsDer.ReadASN1Integer(pub.Parameters.Q) || 306 !paramsDer.ReadASN1Integer(pub.Parameters.G) { 307 return nil, errors.New("x509: invalid DSA parameters") 308 } 309 if pub.Y.Sign() <= 0 || pub.Parameters.P.Sign() <= 0 || 310 pub.Parameters.Q.Sign() <= 0 || pub.Parameters.G.Sign() <= 0 { 311 return nil, errors.New("x509: zero or negative DSA parameter") 312 } 313 return pub, nil 314 default: 315 return nil, errors.New("x509: unknown public key algorithm") 316 } 317 } 318 319 func parseKeyUsageExtension(der cryptobyte.String) (KeyUsage, error) { 320 var usageBits asn1.BitString 321 if !der.ReadASN1BitString(&usageBits) { 322 return 0, errors.New("x509: invalid key usage") 323 } 324 325 var usage int 326 for i := 0; i < 9; i++ { 327 if usageBits.At(i) != 0 { 328 usage |= 1 << uint(i) 329 } 330 } 331 return KeyUsage(usage), nil 332 } 333 334 func parseBasicConstraintsExtension(der cryptobyte.String) (bool, int, error) { 335 var isCA bool 336 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) { 337 return false, 0, errors.New("x509: invalid basic constraints") 338 } 339 if der.PeekASN1Tag(cryptobyte_asn1.BOOLEAN) { 340 if !der.ReadASN1Boolean(&isCA) { 341 return false, 0, errors.New("x509: invalid basic constraints") 342 } 343 } 344 maxPathLen := -1 345 if der.PeekASN1Tag(cryptobyte_asn1.INTEGER) { 346 if !der.ReadASN1Integer(&maxPathLen) { 347 return false, 0, errors.New("x509: invalid basic constraints") 348 } 349 } 350 351 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285) 352 return isCA, maxPathLen, nil 353 } 354 355 func forEachSAN(der cryptobyte.String, callback func(tag int, data []byte) error) error { 356 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) { 357 return errors.New("x509: invalid subject alternative names") 358 } 359 for !der.Empty() { 360 var san cryptobyte.String 361 var tag cryptobyte_asn1.Tag 362 if !der.ReadAnyASN1(&san, &tag) { 363 return errors.New("x509: invalid subject alternative name") 364 } 365 if err := callback(int(tag^0x80), san); err != nil { 366 return err 367 } 368 } 369 370 return nil 371 } 372 373 func parseSANExtension(der cryptobyte.String) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) { 374 err = forEachSAN(der, func(tag int, data []byte) error { 375 switch tag { 376 case nameTypeEmail: 377 email := string(data) 378 if err := isIA5String(email); err != nil { 379 return errors.New("x509: SAN rfc822Name is malformed") 380 } 381 emailAddresses = append(emailAddresses, email) 382 case nameTypeDNS: 383 name := string(data) 384 if err := isIA5String(name); err != nil { 385 return errors.New("x509: SAN dNSName is malformed") 386 } 387 dnsNames = append(dnsNames, string(name)) 388 case nameTypeURI: 389 uriStr := string(data) 390 if err := isIA5String(uriStr); err != nil { 391 return errors.New("x509: SAN uniformResourceIdentifier is malformed") 392 } 393 uri, err := url.Parse(uriStr) 394 if err != nil { 395 return fmt.Errorf("x509: cannot parse URI %q: %s", uriStr, err) 396 } 397 if len(uri.Host) > 0 { 398 if _, ok := domainToReverseLabels(uri.Host); !ok { 399 return fmt.Errorf("x509: cannot parse URI %q: invalid domain", uriStr) 400 } 401 } 402 uris = append(uris, uri) 403 case nameTypeIP: 404 switch len(data) { 405 case net.IPv4len, net.IPv6len: 406 ipAddresses = append(ipAddresses, data) 407 default: 408 return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data))) 409 } 410 } 411 412 return nil 413 }) 414 415 return 416 } 417 418 func parseExtKeyUsageExtension(der cryptobyte.String) ([]ExtKeyUsage, []asn1.ObjectIdentifier, error) { 419 var extKeyUsages []ExtKeyUsage 420 var unknownUsages []asn1.ObjectIdentifier 421 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) { 422 return nil, nil, errors.New("x509: invalid extended key usages") 423 } 424 for !der.Empty() { 425 var eku asn1.ObjectIdentifier 426 if !der.ReadASN1ObjectIdentifier(&eku) { 427 return nil, nil, errors.New("x509: invalid extended key usages") 428 } 429 if extKeyUsage, ok := extKeyUsageFromOID(eku); ok { 430 extKeyUsages = append(extKeyUsages, extKeyUsage) 431 } else { 432 unknownUsages = append(unknownUsages, eku) 433 } 434 } 435 return extKeyUsages, unknownUsages, nil 436 } 437 438 func parseCertificatePoliciesExtension(der cryptobyte.String) ([]asn1.ObjectIdentifier, error) { 439 var oids []asn1.ObjectIdentifier 440 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) { 441 return nil, errors.New("x509: invalid certificate policies") 442 } 443 for !der.Empty() { 444 var cp cryptobyte.String 445 if !der.ReadASN1(&cp, cryptobyte_asn1.SEQUENCE) { 446 return nil, errors.New("x509: invalid certificate policies") 447 } 448 var oid asn1.ObjectIdentifier 449 if !cp.ReadASN1ObjectIdentifier(&oid) { 450 return nil, errors.New("x509: invalid certificate policies") 451 } 452 oids = append(oids, oid) 453 } 454 455 return oids, nil 456 } 457 458 // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits. 459 func isValidIPMask(mask []byte) bool { 460 seenZero := false 461 462 for _, b := range mask { 463 if seenZero { 464 if b != 0 { 465 return false 466 } 467 468 continue 469 } 470 471 switch b { 472 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe: 473 seenZero = true 474 case 0xff: 475 default: 476 return false 477 } 478 } 479 480 return true 481 } 482 483 func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) { 484 // RFC 5280, 4.2.1.10 485 486 // NameConstraints ::= SEQUENCE { 487 // permittedSubtrees [0] GeneralSubtrees OPTIONAL, 488 // excludedSubtrees [1] GeneralSubtrees OPTIONAL } 489 // 490 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree 491 // 492 // GeneralSubtree ::= SEQUENCE { 493 // base GeneralName, 494 // minimum [0] BaseDistance DEFAULT 0, 495 // maximum [1] BaseDistance OPTIONAL } 496 // 497 // BaseDistance ::= INTEGER (0..MAX) 498 499 outer := cryptobyte.String(e.Value) 500 var toplevel, permitted, excluded cryptobyte.String 501 var havePermitted, haveExcluded bool 502 if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) || 503 !outer.Empty() || 504 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) || 505 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) || 506 !toplevel.Empty() { 507 return false, errors.New("x509: invalid NameConstraints extension") 508 } 509 510 if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 { 511 // From RFC 5280, Section 4.2.1.10: 512 // “either the permittedSubtrees field 513 // or the excludedSubtrees MUST be 514 // present” 515 return false, errors.New("x509: empty name constraints extension") 516 } 517 518 getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) { 519 for !subtrees.Empty() { 520 var seq, value cryptobyte.String 521 var tag cryptobyte_asn1.Tag 522 if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) || 523 !seq.ReadAnyASN1(&value, &tag) { 524 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension") 525 } 526 527 var ( 528 dnsTag = cryptobyte_asn1.Tag(2).ContextSpecific() 529 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific() 530 ipTag = cryptobyte_asn1.Tag(7).ContextSpecific() 531 uriTag = cryptobyte_asn1.Tag(6).ContextSpecific() 532 ) 533 534 switch tag { 535 case dnsTag: 536 domain := string(value) 537 if err := isIA5String(domain); err != nil { 538 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error()) 539 } 540 541 trimmedDomain := domain 542 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' { 543 // constraints can have a leading 544 // period to exclude the domain 545 // itself, but that's not valid in a 546 // normal domain name. 547 trimmedDomain = trimmedDomain[1:] 548 } 549 if _, ok := domainToReverseLabels(trimmedDomain); !ok { 550 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain) 551 } 552 dnsNames = append(dnsNames, domain) 553 554 case ipTag: 555 l := len(value) 556 var ip, mask []byte 557 558 switch l { 559 case 8: 560 ip = value[:4] 561 mask = value[4:] 562 563 case 32: 564 ip = value[:16] 565 mask = value[16:] 566 567 default: 568 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l) 569 } 570 571 if !isValidIPMask(mask) { 572 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask) 573 } 574 575 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)}) 576 577 case emailTag: 578 constraint := string(value) 579 if err := isIA5String(constraint); err != nil { 580 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error()) 581 } 582 583 // If the constraint contains an @ then 584 // it specifies an exact mailbox name. 585 if strings.Contains(constraint, "@") { 586 if _, ok := parseRFC2821Mailbox(constraint); !ok { 587 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint) 588 } 589 } else { 590 // Otherwise it's a domain name. 591 domain := constraint 592 if len(domain) > 0 && domain[0] == '.' { 593 domain = domain[1:] 594 } 595 if _, ok := domainToReverseLabels(domain); !ok { 596 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint) 597 } 598 } 599 emails = append(emails, constraint) 600 601 case uriTag: 602 domain := string(value) 603 if err := isIA5String(domain); err != nil { 604 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error()) 605 } 606 607 if net.ParseIP(domain) != nil { 608 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain) 609 } 610 611 trimmedDomain := domain 612 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' { 613 // constraints can have a leading 614 // period to exclude the domain itself, 615 // but that's not valid in a normal 616 // domain name. 617 trimmedDomain = trimmedDomain[1:] 618 } 619 if _, ok := domainToReverseLabels(trimmedDomain); !ok { 620 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain) 621 } 622 uriDomains = append(uriDomains, domain) 623 624 default: 625 unhandled = true 626 } 627 } 628 629 return dnsNames, ips, emails, uriDomains, nil 630 } 631 632 if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil { 633 return false, err 634 } 635 if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil { 636 return false, err 637 } 638 out.PermittedDNSDomainsCritical = e.Critical 639 640 return unhandled, nil 641 } 642 643 func processExtensions(out *Certificate) error { 644 var err error 645 for _, e := range out.Extensions { 646 unhandled := false 647 648 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 { 649 switch e.Id[3] { 650 case 15: 651 out.KeyUsage, err = parseKeyUsageExtension(e.Value) 652 if err != nil { 653 return err 654 } 655 case 19: 656 out.IsCA, out.MaxPathLen, err = parseBasicConstraintsExtension(e.Value) 657 if err != nil { 658 return err 659 } 660 out.BasicConstraintsValid = true 661 out.MaxPathLenZero = out.MaxPathLen == 0 662 case 17: 663 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value) 664 if err != nil { 665 return err 666 } 667 668 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 { 669 // If we didn't parse anything then we do the critical check, below. 670 unhandled = true 671 } 672 673 case 30: 674 unhandled, err = parseNameConstraintsExtension(out, e) 675 if err != nil { 676 return err 677 } 678 679 case 31: 680 // RFC 5280, 4.2.1.13 681 682 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint 683 // 684 // DistributionPoint ::= SEQUENCE { 685 // distributionPoint [0] DistributionPointName OPTIONAL, 686 // reasons [1] ReasonFlags OPTIONAL, 687 // cRLIssuer [2] GeneralNames OPTIONAL } 688 // 689 // DistributionPointName ::= CHOICE { 690 // fullName [0] GeneralNames, 691 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName } 692 val := cryptobyte.String(e.Value) 693 if !val.ReadASN1(&val, cryptobyte_asn1.SEQUENCE) { 694 return errors.New("x509: invalid CRL distribution points") 695 } 696 for !val.Empty() { 697 var dpDER cryptobyte.String 698 if !val.ReadASN1(&dpDER, cryptobyte_asn1.SEQUENCE) { 699 return errors.New("x509: invalid CRL distribution point") 700 } 701 var dpNameDER cryptobyte.String 702 var dpNamePresent bool 703 if !dpDER.ReadOptionalASN1(&dpNameDER, &dpNamePresent, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific()) { 704 return errors.New("x509: invalid CRL distribution point") 705 } 706 if !dpNamePresent { 707 continue 708 } 709 if !dpNameDER.ReadASN1(&dpNameDER, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific()) { 710 return errors.New("x509: invalid CRL distribution point") 711 } 712 for !dpNameDER.Empty() { 713 if !dpNameDER.PeekASN1Tag(cryptobyte_asn1.Tag(6).ContextSpecific()) { 714 break 715 } 716 var uri cryptobyte.String 717 if !dpNameDER.ReadASN1(&uri, cryptobyte_asn1.Tag(6).ContextSpecific()) { 718 return errors.New("x509: invalid CRL distribution point") 719 } 720 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(uri)) 721 } 722 } 723 724 case 35: 725 // RFC 5280, 4.2.1.1 726 val := cryptobyte.String(e.Value) 727 var akid cryptobyte.String 728 if !val.ReadASN1(&akid, cryptobyte_asn1.SEQUENCE) { 729 return errors.New("x509: invalid authority key identifier") 730 } 731 if akid.PeekASN1Tag(cryptobyte_asn1.Tag(0).ContextSpecific()) { 732 if !akid.ReadASN1(&akid, cryptobyte_asn1.Tag(0).ContextSpecific()) { 733 return errors.New("x509: invalid authority key identifier") 734 } 735 out.AuthorityKeyId = akid 736 } 737 case 37: 738 out.ExtKeyUsage, out.UnknownExtKeyUsage, err = parseExtKeyUsageExtension(e.Value) 739 if err != nil { 740 return err 741 } 742 case 14: 743 // RFC 5280, 4.2.1.2 744 val := cryptobyte.String(e.Value) 745 var skid cryptobyte.String 746 if !val.ReadASN1(&skid, cryptobyte_asn1.OCTET_STRING) { 747 return errors.New("x509: invalid subject key identifier") 748 } 749 out.SubjectKeyId = skid 750 case 32: 751 out.PolicyIdentifiers, err = parseCertificatePoliciesExtension(e.Value) 752 if err != nil { 753 return err 754 } 755 default: 756 // Unknown extensions are recorded if critical. 757 unhandled = true 758 } 759 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) { 760 // RFC 5280 4.2.2.1: Authority Information Access 761 val := cryptobyte.String(e.Value) 762 if !val.ReadASN1(&val, cryptobyte_asn1.SEQUENCE) { 763 return errors.New("x509: invalid authority info access") 764 } 765 for !val.Empty() { 766 var aiaDER cryptobyte.String 767 if !val.ReadASN1(&aiaDER, cryptobyte_asn1.SEQUENCE) { 768 return errors.New("x509: invalid authority info access") 769 } 770 var method asn1.ObjectIdentifier 771 if !aiaDER.ReadASN1ObjectIdentifier(&method) { 772 return errors.New("x509: invalid authority info access") 773 } 774 if !aiaDER.PeekASN1Tag(cryptobyte_asn1.Tag(6).ContextSpecific()) { 775 continue 776 } 777 if !aiaDER.ReadASN1(&aiaDER, cryptobyte_asn1.Tag(6).ContextSpecific()) { 778 return errors.New("x509: invalid authority info access") 779 } 780 switch { 781 case method.Equal(oidAuthorityInfoAccessOcsp): 782 out.OCSPServer = append(out.OCSPServer, string(aiaDER)) 783 case method.Equal(oidAuthorityInfoAccessIssuers): 784 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(aiaDER)) 785 } 786 } 787 } else { 788 // Unknown extensions are recorded if critical. 789 unhandled = true 790 } 791 792 if e.Critical && unhandled { 793 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id) 794 } 795 } 796 797 return nil 798 } 799 800 func parseCertificate(der []byte) (*Certificate, error) { 801 cert := &Certificate{} 802 803 input := cryptobyte.String(der) 804 // we read the SEQUENCE including length and tag bytes so that 805 // we can populate Certificate.Raw, before unwrapping the 806 // SEQUENCE so it can be operated on 807 if !input.ReadASN1Element(&input, cryptobyte_asn1.SEQUENCE) { 808 return nil, errors.New("x509: malformed certificate") 809 } 810 cert.Raw = input 811 if !input.ReadASN1(&input, cryptobyte_asn1.SEQUENCE) { 812 return nil, errors.New("x509: malformed certificate") 813 } 814 815 var tbs cryptobyte.String 816 // do the same trick again as above to extract the raw 817 // bytes for Certificate.RawTBSCertificate 818 if !input.ReadASN1Element(&tbs, cryptobyte_asn1.SEQUENCE) { 819 return nil, errors.New("x509: malformed tbs certificate") 820 } 821 cert.RawTBSCertificate = tbs 822 if !tbs.ReadASN1(&tbs, cryptobyte_asn1.SEQUENCE) { 823 return nil, errors.New("x509: malformed tbs certificate") 824 } 825 826 if !tbs.ReadOptionalASN1Integer(&cert.Version, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific(), 0) { 827 return nil, errors.New("x509: malformed version") 828 } 829 if cert.Version < 0 { 830 return nil, errors.New("x509: malformed version") 831 } 832 // for backwards compat reasons Version is one-indexed, 833 // rather than zero-indexed as defined in 5280 834 cert.Version++ 835 if cert.Version > 3 { 836 return nil, errors.New("x509: invalid version") 837 } 838 839 serial := new(big.Int) 840 if !tbs.ReadASN1Integer(serial) { 841 return nil, errors.New("x509: malformed serial number") 842 } 843 // we ignore the presence of negative serial numbers because 844 // of their prevalence, despite them being invalid 845 // TODO(rolandshoemaker): revisit this decision, there are currently 846 // only 10 trusted certificates with negative serial numbers 847 // according to censys.io. 848 cert.SerialNumber = serial 849 850 var sigAISeq cryptobyte.String 851 if !tbs.ReadASN1(&sigAISeq, cryptobyte_asn1.SEQUENCE) { 852 return nil, errors.New("x509: malformed signature algorithm identifier") 853 } 854 // Before parsing the inner algorithm identifier, extract 855 // the outer algorithm identifier and make sure that they 856 // match. 857 var outerSigAISeq cryptobyte.String 858 if !input.ReadASN1(&outerSigAISeq, cryptobyte_asn1.SEQUENCE) { 859 return nil, errors.New("x509: malformed algorithm identifier") 860 } 861 if !bytes.Equal(outerSigAISeq, sigAISeq) { 862 return nil, errors.New("x509: inner and outer signature algorithm identifiers don't match") 863 } 864 sigAI, err := parseAI(sigAISeq) 865 if err != nil { 866 return nil, err 867 } 868 cert.SignatureAlgorithm = getSignatureAlgorithmFromAI(sigAI) 869 870 var issuerSeq cryptobyte.String 871 if !tbs.ReadASN1Element(&issuerSeq, cryptobyte_asn1.SEQUENCE) { 872 return nil, errors.New("x509: malformed issuer") 873 } 874 cert.RawIssuer = issuerSeq 875 issuerRDNs, err := parseName(issuerSeq) 876 if err != nil { 877 return nil, err 878 } 879 cert.Issuer.FillFromRDNSequence(issuerRDNs) 880 881 var validity cryptobyte.String 882 if !tbs.ReadASN1(&validity, cryptobyte_asn1.SEQUENCE) { 883 return nil, errors.New("x509: malformed validity") 884 } 885 cert.NotBefore, cert.NotAfter, err = parseValidity(validity) 886 if err != nil { 887 return nil, err 888 } 889 890 var subjectSeq cryptobyte.String 891 if !tbs.ReadASN1Element(&subjectSeq, cryptobyte_asn1.SEQUENCE) { 892 return nil, errors.New("x509: malformed issuer") 893 } 894 cert.RawSubject = subjectSeq 895 subjectRDNs, err := parseName(subjectSeq) 896 if err != nil { 897 return nil, err 898 } 899 cert.Subject.FillFromRDNSequence(subjectRDNs) 900 901 var spki cryptobyte.String 902 if !tbs.ReadASN1Element(&spki, cryptobyte_asn1.SEQUENCE) { 903 return nil, errors.New("x509: malformed spki") 904 } 905 cert.RawSubjectPublicKeyInfo = spki 906 if !spki.ReadASN1(&spki, cryptobyte_asn1.SEQUENCE) { 907 return nil, errors.New("x509: malformed spki") 908 } 909 var pkAISeq cryptobyte.String 910 if !spki.ReadASN1(&pkAISeq, cryptobyte_asn1.SEQUENCE) { 911 return nil, errors.New("x509: malformed public key algorithm identifier") 912 } 913 pkAI, err := parseAI(pkAISeq) 914 if err != nil { 915 return nil, err 916 } 917 cert.PublicKeyAlgorithm = getPublicKeyAlgorithmFromOID(pkAI.Algorithm) 918 var spk asn1.BitString 919 if !spki.ReadASN1BitString(&spk) { 920 return nil, errors.New("x509: malformed subjectPublicKey") 921 } 922 if cert.PublicKeyAlgorithm != UnknownPublicKeyAlgorithm { 923 cert.PublicKey, err = parsePublicKey(&publicKeyInfo{ 924 Algorithm: pkAI, 925 PublicKey: spk, 926 }) 927 if err != nil { 928 return nil, err 929 } 930 } 931 932 if cert.Version > 1 { 933 if !tbs.SkipOptionalASN1(cryptobyte_asn1.Tag(1).ContextSpecific()) { 934 return nil, errors.New("x509: malformed issuerUniqueID") 935 } 936 if !tbs.SkipOptionalASN1(cryptobyte_asn1.Tag(2).ContextSpecific()) { 937 return nil, errors.New("x509: malformed subjectUniqueID") 938 } 939 if cert.Version == 3 { 940 var extensions cryptobyte.String 941 var present bool 942 if !tbs.ReadOptionalASN1(&extensions, &present, cryptobyte_asn1.Tag(3).Constructed().ContextSpecific()) { 943 return nil, errors.New("x509: malformed extensions") 944 } 945 if present { 946 seenExts := make(map[string]bool) 947 if !extensions.ReadASN1(&extensions, cryptobyte_asn1.SEQUENCE) { 948 return nil, errors.New("x509: malformed extensions") 949 } 950 for !extensions.Empty() { 951 var extension cryptobyte.String 952 if !extensions.ReadASN1(&extension, cryptobyte_asn1.SEQUENCE) { 953 return nil, errors.New("x509: malformed extension") 954 } 955 ext, err := parseExtension(extension) 956 if err != nil { 957 return nil, err 958 } 959 oidStr := ext.Id.String() 960 if seenExts[oidStr] { 961 return nil, errors.New("x509: certificate contains duplicate extensions") 962 } 963 seenExts[oidStr] = true 964 cert.Extensions = append(cert.Extensions, ext) 965 } 966 err = processExtensions(cert) 967 if err != nil { 968 return nil, err 969 } 970 } 971 } 972 } 973 974 var signature asn1.BitString 975 if !input.ReadASN1BitString(&signature) { 976 return nil, errors.New("x509: malformed signature") 977 } 978 cert.Signature = signature.RightAlign() 979 980 return cert, nil 981 } 982 983 // ParseCertificate parses a single certificate from the given ASN.1 DER data. 984 func ParseCertificate(der []byte) (*Certificate, error) { 985 cert, err := parseCertificate(der) 986 if err != nil { 987 return nil, err 988 } 989 if len(der) != len(cert.Raw) { 990 return nil, errors.New("x509: trailing data") 991 } 992 return cert, err 993 } 994 995 // ParseCertificates parses one or more certificates from the given ASN.1 DER 996 // data. The certificates must be concatenated with no intermediate padding. 997 func ParseCertificates(der []byte) ([]*Certificate, error) { 998 var certs []*Certificate 999 for len(der) > 0 { 1000 cert, err := parseCertificate(der) 1001 if err != nil { 1002 return nil, err 1003 } 1004 certs = append(certs, cert) 1005 der = der[len(cert.Raw):] 1006 } 1007 return certs, nil 1008 } 1009 1010 // The X.509 standards confusingly 1-indexed the version names, but 0-indexed 1011 // the actual encoded version, so the version for X.509v2 is 1. 1012 const x509v2Version = 1 1013 1014 // ParseRevocationList parses a X509 v2 Certificate Revocation List from the given 1015 // ASN.1 DER data. 1016 func ParseRevocationList(der []byte) (*RevocationList, error) { 1017 rl := &RevocationList{} 1018 1019 input := cryptobyte.String(der) 1020 // we read the SEQUENCE including length and tag bytes so that 1021 // we can populate RevocationList.Raw, before unwrapping the 1022 // SEQUENCE so it can be operated on 1023 if !input.ReadASN1Element(&input, cryptobyte_asn1.SEQUENCE) { 1024 return nil, errors.New("x509: malformed crl") 1025 } 1026 rl.Raw = input 1027 if !input.ReadASN1(&input, cryptobyte_asn1.SEQUENCE) { 1028 return nil, errors.New("x509: malformed crl") 1029 } 1030 1031 var tbs cryptobyte.String 1032 // do the same trick again as above to extract the raw 1033 // bytes for Certificate.RawTBSCertificate 1034 if !input.ReadASN1Element(&tbs, cryptobyte_asn1.SEQUENCE) { 1035 return nil, errors.New("x509: malformed tbs crl") 1036 } 1037 rl.RawTBSRevocationList = tbs 1038 if !tbs.ReadASN1(&tbs, cryptobyte_asn1.SEQUENCE) { 1039 return nil, errors.New("x509: malformed tbs crl") 1040 } 1041 1042 var version int 1043 if !tbs.PeekASN1Tag(cryptobyte_asn1.INTEGER) { 1044 return nil, errors.New("x509: unsupported crl version") 1045 } 1046 if !tbs.ReadASN1Integer(&version) { 1047 return nil, errors.New("x509: malformed crl") 1048 } 1049 if version != x509v2Version { 1050 return nil, fmt.Errorf("x509: unsupported crl version: %d", version) 1051 } 1052 1053 var sigAISeq cryptobyte.String 1054 if !tbs.ReadASN1(&sigAISeq, cryptobyte_asn1.SEQUENCE) { 1055 return nil, errors.New("x509: malformed signature algorithm identifier") 1056 } 1057 // Before parsing the inner algorithm identifier, extract 1058 // the outer algorithm identifier and make sure that they 1059 // match. 1060 var outerSigAISeq cryptobyte.String 1061 if !input.ReadASN1(&outerSigAISeq, cryptobyte_asn1.SEQUENCE) { 1062 return nil, errors.New("x509: malformed algorithm identifier") 1063 } 1064 if !bytes.Equal(outerSigAISeq, sigAISeq) { 1065 return nil, errors.New("x509: inner and outer signature algorithm identifiers don't match") 1066 } 1067 sigAI, err := parseAI(sigAISeq) 1068 if err != nil { 1069 return nil, err 1070 } 1071 rl.SignatureAlgorithm = getSignatureAlgorithmFromAI(sigAI) 1072 1073 var signature asn1.BitString 1074 if !input.ReadASN1BitString(&signature) { 1075 return nil, errors.New("x509: malformed signature") 1076 } 1077 rl.Signature = signature.RightAlign() 1078 1079 var issuerSeq cryptobyte.String 1080 if !tbs.ReadASN1Element(&issuerSeq, cryptobyte_asn1.SEQUENCE) { 1081 return nil, errors.New("x509: malformed issuer") 1082 } 1083 rl.RawIssuer = issuerSeq 1084 issuerRDNs, err := parseName(issuerSeq) 1085 if err != nil { 1086 return nil, err 1087 } 1088 rl.Issuer.FillFromRDNSequence(issuerRDNs) 1089 1090 rl.ThisUpdate, err = parseTime(&tbs) 1091 if err != nil { 1092 return nil, err 1093 } 1094 if tbs.PeekASN1Tag(cryptobyte_asn1.GeneralizedTime) || tbs.PeekASN1Tag(cryptobyte_asn1.UTCTime) { 1095 rl.NextUpdate, err = parseTime(&tbs) 1096 if err != nil { 1097 return nil, err 1098 } 1099 } 1100 1101 if tbs.PeekASN1Tag(cryptobyte_asn1.SEQUENCE) { 1102 var revokedSeq cryptobyte.String 1103 if !tbs.ReadASN1(&revokedSeq, cryptobyte_asn1.SEQUENCE) { 1104 return nil, errors.New("x509: malformed crl") 1105 } 1106 for !revokedSeq.Empty() { 1107 rce := RevocationListEntry{} 1108 1109 var certSeq cryptobyte.String 1110 if !revokedSeq.ReadASN1Element(&certSeq, cryptobyte_asn1.SEQUENCE) { 1111 return nil, errors.New("x509: malformed crl") 1112 } 1113 rce.Raw = certSeq 1114 if !certSeq.ReadASN1(&certSeq, cryptobyte_asn1.SEQUENCE) { 1115 return nil, errors.New("x509: malformed crl") 1116 } 1117 1118 rce.SerialNumber = new(big.Int) 1119 if !certSeq.ReadASN1Integer(rce.SerialNumber) { 1120 return nil, errors.New("x509: malformed serial number") 1121 } 1122 rce.RevocationTime, err = parseTime(&certSeq) 1123 if err != nil { 1124 return nil, err 1125 } 1126 var extensions cryptobyte.String 1127 var present bool 1128 if !certSeq.ReadOptionalASN1(&extensions, &present, cryptobyte_asn1.SEQUENCE) { 1129 return nil, errors.New("x509: malformed extensions") 1130 } 1131 if present { 1132 for !extensions.Empty() { 1133 var extension cryptobyte.String 1134 if !extensions.ReadASN1(&extension, cryptobyte_asn1.SEQUENCE) { 1135 return nil, errors.New("x509: malformed extension") 1136 } 1137 ext, err := parseExtension(extension) 1138 if err != nil { 1139 return nil, err 1140 } 1141 if ext.Id.Equal(oidExtensionReasonCode) { 1142 val := cryptobyte.String(ext.Value) 1143 if !val.ReadASN1Enum(&rce.ReasonCode) { 1144 return nil, fmt.Errorf("x509: malformed reasonCode extension") 1145 } 1146 } 1147 rce.Extensions = append(rce.Extensions, ext) 1148 } 1149 } 1150 1151 rl.RevokedCertificateEntries = append(rl.RevokedCertificateEntries, rce) 1152 rcDeprecated := pkix.RevokedCertificate{ 1153 SerialNumber: rce.SerialNumber, 1154 RevocationTime: rce.RevocationTime, 1155 Extensions: rce.Extensions, 1156 } 1157 rl.RevokedCertificates = append(rl.RevokedCertificates, rcDeprecated) 1158 } 1159 } 1160 1161 var extensions cryptobyte.String 1162 var present bool 1163 if !tbs.ReadOptionalASN1(&extensions, &present, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific()) { 1164 return nil, errors.New("x509: malformed extensions") 1165 } 1166 if present { 1167 if !extensions.ReadASN1(&extensions, cryptobyte_asn1.SEQUENCE) { 1168 return nil, errors.New("x509: malformed extensions") 1169 } 1170 for !extensions.Empty() { 1171 var extension cryptobyte.String 1172 if !extensions.ReadASN1(&extension, cryptobyte_asn1.SEQUENCE) { 1173 return nil, errors.New("x509: malformed extension") 1174 } 1175 ext, err := parseExtension(extension) 1176 if err != nil { 1177 return nil, err 1178 } 1179 if ext.Id.Equal(oidExtensionAuthorityKeyId) { 1180 rl.AuthorityKeyId = ext.Value 1181 } else if ext.Id.Equal(oidExtensionCRLNumber) { 1182 value := cryptobyte.String(ext.Value) 1183 rl.Number = new(big.Int) 1184 if !value.ReadASN1Integer(rl.Number) { 1185 return nil, errors.New("x509: malformed crl number") 1186 } 1187 } 1188 rl.Extensions = append(rl.Extensions, ext) 1189 } 1190 } 1191 1192 return rl, nil 1193 }