github.com/emmansun/gmsm@v0.29.1/smx509/parser.go (about)

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