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