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