Source file src/crypto/x509/parser.go

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

View as plain text