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