parser.mx raw

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