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

View as plain text