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