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

View as plain text