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