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

View as plain text