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

View as plain text