Debian Codegraph @

internal/legacy/x509/parser.go

raw symbols SCIP
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 legacyx509
6
7 import (
8 "bytes"
9 "crypto/dsa"
10 "crypto/ecdsa"
11 "crypto/ed25519"
12 "crypto/elliptic"
13 "crypto/rsa"
14 "crypto/x509/pkix"
15 "encoding/asn1"
16 "errors"
17 "fmt"
18 "math/big"
19 "net"
20 "net/url"
21 "strconv"
22 "strings"
23 "time"
24 "unicode/utf16"
25 "unicode/utf8"
26
27 "github.com/smallstep/pkcs7/internal/cryptobyte"
28 cryptobyte_asn1 "github.com/smallstep/pkcs7/internal/cryptobyte/asn1"
29
30 stdx509 "crypto/x509"
31 )
32
33 // ParseCertificates parses one or more certificates from the given ASN.1 DER
34 // data. The certificates must be concatenated with no intermediate padding.
35 func ParseCertificates(der []byte) ([]*stdx509.Certificate, error) {
36 var certs []*stdx509.Certificate
37 for len(der) > 0 {
38 cert, err := parseCertificate(der)
39 if err != nil {
40 return nil, err
41 }
42 certs = append(certs, cert)
43 der = der[len(cert.Raw):]
44 }
45 return certs, nil
46 }
47
48 // isPrintable reports whether the given b is in the ASN.1 PrintableString set.
49 // This is a simplified version of encoding/asn1.isPrintable.
50 func isPrintable(b byte) bool {
51 return 'a' <= b && b <= 'z' ||
52 'A' <= b && b <= 'Z' ||
53 '0' <= b && b <= '9' ||
54 '\'' <= b && b <= ')' ||
55 '+' <= b && b <= '/' ||
56 b == ' ' ||
57 b == ':' ||
58 b == '=' ||
59 b == '?' ||
60 // This is technically not allowed in a PrintableString.
61 // However, x509 certificates with wildcard strings don't
62 // always use the correct string type so we permit it.
63 b == '*' ||
64 // This is not technically allowed either. However, not
65 // only is it relatively common, but there are also a
66 // handful of CA certificates that contain it. At least
67 // one of which will not expire until 2027.
68 b == '&'
69 }
70
71 // parseASN1String parses the ASN.1 string types T61String, PrintableString,
72 // UTF8String, BMPString, IA5String, and NumericString. This is mostly copied
73 // from the respective encoding/asn1.parse... methods, rather than just
74 // increasing the API surface of that package.
75 func parseASN1String(tag cryptobyte_asn1.Tag, value []byte) (string, error) {
76 switch tag {
77 case cryptobyte_asn1.T61String:
78 return string(value), nil
79 case cryptobyte_asn1.PrintableString:
80 for _, b := range value {
81 if !isPrintable(b) {
82 return "", errors.New("invalid PrintableString")
83 }
84 }
85 return string(value), nil
86 case cryptobyte_asn1.UTF8String:
87 if !utf8.Valid(value) {
88 return "", errors.New("invalid UTF-8 string")
89 }
90 return string(value), nil
91 case cryptobyte_asn1.Tag(asn1.TagBMPString):
92 if len(value)%2 != 0 {
93 return "", errors.New("invalid BMPString")
94 }
95
96 // Strip terminator if present.
97 if l := len(value); l >= 2 && value[l-1] == 0 && value[l-2] == 0 {
98 value = value[:l-2]
99 }
100
101 s := make([]uint16, 0, len(value)/2)
102 for len(value) > 0 {
103 s = append(s, uint16(value[0])<<8+uint16(value[1]))
104 value = value[2:]
105 }
106
107 return string(utf16.Decode(s)), nil
108 case cryptobyte_asn1.IA5String:
109 s := string(value)
110 if isIA5String(s) != nil {
111 return "", errors.New("invalid IA5String")
112 }
113 return s, nil
114 case cryptobyte_asn1.Tag(asn1.TagNumericString):
115 for _, b := range value {
116 if !('0' <= b && b <= '9' || b == ' ') {
117 return "", errors.New("invalid NumericString")
118 }
119 }
120 return string(value), nil
121 }
122 return "", fmt.Errorf("unsupported string type: %v", tag)
123 }
124
125 // parseName parses a DER encoded Name as defined in RFC 5280. We may
126 // want to export this function in the future for use in crypto/tls.
127 func parseName(raw cryptobyte.String) (*pkix.RDNSequence, error) {
128 if !raw.ReadASN1(&raw, cryptobyte_asn1.SEQUENCE) {
129 return nil, errors.New("x509: invalid RDNSequence")
130 }
131
132 var rdnSeq pkix.RDNSequence
133 for !raw.Empty() {
134 var rdnSet pkix.RelativeDistinguishedNameSET
135 var set cryptobyte.String
136 if !raw.ReadASN1(&set, cryptobyte_asn1.SET) {
137 return nil, errors.New("x509: invalid RDNSequence")
138 }
139 for !set.Empty() {
140 var atav cryptobyte.String
141 if !set.ReadASN1(&atav, cryptobyte_asn1.SEQUENCE) {
142 return nil, errors.New("x509: invalid RDNSequence: invalid attribute")
143 }
144 var attr pkix.AttributeTypeAndValue
145 if !atav.ReadASN1ObjectIdentifier(&attr.Type) {
146 return nil, errors.New("x509: invalid RDNSequence: invalid attribute type")
147 }
148 var rawValue cryptobyte.String
149 var valueTag cryptobyte_asn1.Tag
150 if !atav.ReadAnyASN1(&rawValue, &valueTag) {
151 return nil, errors.New("x509: invalid RDNSequence: invalid attribute value")
152 }
153 var err error
154 attr.Value, err = parseASN1String(valueTag, rawValue)
155 if err != nil {
156 return nil, fmt.Errorf("x509: invalid RDNSequence: invalid attribute value: %s", err)
157 }
158 rdnSet = append(rdnSet, attr)
159 }
160
161 rdnSeq = append(rdnSeq, rdnSet)
162 }
163
164 return &rdnSeq, nil
165 }
166
167 func parseAI(der cryptobyte.String) (pkix.AlgorithmIdentifier, error) {
168 ai := pkix.AlgorithmIdentifier{}
169 if !der.ReadASN1ObjectIdentifier(&ai.Algorithm) {
170 return ai, errors.New("x509: malformed OID")
171 }
172 if der.Empty() {
173 return ai, nil
174 }
175 var params cryptobyte.String
176 var tag cryptobyte_asn1.Tag
177 if !der.ReadAnyASN1Element(&params, &tag) {
178 return ai, errors.New("x509: malformed parameters")
179 }
180 ai.Parameters.Tag = int(tag)
181 ai.Parameters.FullBytes = params
182 return ai, nil
183 }
184
185 func parseTime(der *cryptobyte.String) (time.Time, error) {
186 var t time.Time
187 switch {
188 case der.PeekASN1Tag(cryptobyte_asn1.UTCTime):
189 if !der.ReadASN1UTCTime(&t) {
190 return t, errors.New("x509: malformed UTCTime")
191 }
192 case der.PeekASN1Tag(cryptobyte_asn1.GeneralizedTime):
193 if !der.ReadASN1GeneralizedTime(&t) {
194 return t, errors.New("x509: malformed GeneralizedTime")
195 }
196 default:
197 return t, errors.New("x509: unsupported time format")
198 }
199 return t, nil
200 }
201
202 func parseValidity(der cryptobyte.String) (time.Time, time.Time, error) {
203 notBefore, err := parseTime(&der)
204 if err != nil {
205 return time.Time{}, time.Time{}, err
206 }
207 notAfter, err := parseTime(&der)
208 if err != nil {
209 return time.Time{}, time.Time{}, err
210 }
211
212 return notBefore, notAfter, nil
213 }
214
215 func parseExtension(der cryptobyte.String) (pkix.Extension, error) {
216 var ext pkix.Extension
217 if !der.ReadASN1ObjectIdentifier(&ext.Id) {
218 return ext, errors.New("x509: malformed extension OID field")
219 }
220 if der.PeekASN1Tag(cryptobyte_asn1.BOOLEAN) {
221 if !der.ReadASN1Boolean(&ext.Critical) {
222 return ext, errors.New("x509: malformed extension critical field")
223 }
224 }
225 var val cryptobyte.String
226 if !der.ReadASN1(&val, cryptobyte_asn1.OCTET_STRING) {
227 return ext, errors.New("x509: malformed extension value field")
228 }
229 ext.Value = val
230 return ext, nil
231 }
232
233 func parsePublicKey(keyData *publicKeyInfo) (interface{}, error) {
234 oid := keyData.Algorithm.Algorithm
235 params := keyData.Algorithm.Parameters
236 der := cryptobyte.String(keyData.PublicKey.RightAlign())
237 switch {
238 case oid.Equal(oidPublicKeyRSA):
239 // RSA public keys must have a NULL in the parameters.
240 // See RFC 3279, Section 2.3.1.
241 if !bytes.Equal(params.FullBytes, asn1.NullBytes) {
242 return nil, errors.New("x509: RSA key missing NULL parameters")
243 }
244
245 p := &pkcs1PublicKey{N: new(big.Int)}
246 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
247 return nil, errors.New("x509: invalid RSA public key")
248 }
249 if !der.ReadASN1Integer(p.N) {
250 return nil, errors.New("x509: invalid RSA modulus")
251 }
252 if !der.ReadASN1Integer(&p.E) {
253 return nil, errors.New("x509: invalid RSA public exponent")
254 }
255
256 if p.N.Sign() <= 0 {
257 return nil, errors.New("x509: RSA modulus is not a positive number")
258 }
259 if p.E <= 0 {
260 return nil, errors.New("x509: RSA public exponent is not a positive number")
261 }
262
263 pub := &rsa.PublicKey{
264 E: p.E,
265 N: p.N,
266 }
267 return pub, nil
268 case oid.Equal(oidPublicKeyECDSA):
269 paramsDer := cryptobyte.String(params.FullBytes)
270 namedCurveOID := new(asn1.ObjectIdentifier)
271 if !paramsDer.ReadASN1ObjectIdentifier(namedCurveOID) {
272 return nil, errors.New("x509: invalid ECDSA parameters")
273 }
274 namedCurve := namedCurveFromOID(*namedCurveOID)
275 if namedCurve == nil {
276 return nil, errors.New("x509: unsupported elliptic curve")
277 }
278 x, y := elliptic.Unmarshal(namedCurve, der)
279 if x == nil {
280 return nil, errors.New("x509: failed to unmarshal elliptic curve point")
281 }
282 pub := &ecdsa.PublicKey{
283 Curve: namedCurve,
284 X: x,
285 Y: y,
286 }
287 return pub, nil
288 case oid.Equal(oidPublicKeyEd25519):
289 // RFC 8410, Section 3
290 // > For all of the OIDs, the parameters MUST be absent.
291 if len(params.FullBytes) != 0 {
292 return nil, errors.New("x509: Ed25519 key encoded with illegal parameters")
293 }
294 if len(der) != ed25519.PublicKeySize {
295 return nil, errors.New("x509: wrong Ed25519 public key size")
296 }
297 return ed25519.PublicKey(der), nil
298 // case oid.Equal(oidPublicKeyX25519):
299 // // RFC 8410, Section 3
300 // // > For all of the OIDs, the parameters MUST be absent.
301 // if len(params.FullBytes) != 0 {
302 // return nil, errors.New("x509: X25519 key encoded with illegal parameters")
303 // }
304 // return ecdh.X25519().NewPublicKey(der)
305 case oid.Equal(oidPublicKeyDSA):
306 y := new(big.Int)
307 if !der.ReadASN1Integer(y) {
308 return nil, errors.New("x509: invalid DSA public key")
309 }
310 pub := &dsa.PublicKey{
311 Y: y,
312 Parameters: dsa.Parameters{
313 P: new(big.Int),
314 Q: new(big.Int),
315 G: new(big.Int),
316 },
317 }
318 paramsDer := cryptobyte.String(params.FullBytes)
319 if !paramsDer.ReadASN1(&paramsDer, cryptobyte_asn1.SEQUENCE) ||
320 !paramsDer.ReadASN1Integer(pub.Parameters.P) ||
321 !paramsDer.ReadASN1Integer(pub.Parameters.Q) ||
322 !paramsDer.ReadASN1Integer(pub.Parameters.G) {
323 return nil, errors.New("x509: invalid DSA parameters")
324 }
325 if pub.Y.Sign() <= 0 || pub.Parameters.P.Sign() <= 0 ||
326 pub.Parameters.Q.Sign() <= 0 || pub.Parameters.G.Sign() <= 0 {
327 return nil, errors.New("x509: zero or negative DSA parameter")
328 }
329 return pub, nil
330 default:
331 return nil, errors.New("x509: unknown public key algorithm")
332 }
333 }
334
335 func parseKeyUsageExtension(der cryptobyte.String) (stdx509.KeyUsage, error) {
336 var usageBits asn1.BitString
337 if !der.ReadASN1BitString(&usageBits) {
338 return 0, errors.New("x509: invalid key usage")
339 }
340
341 var usage int
342 for i := 0; i < 9; i++ {
343 if usageBits.At(i) != 0 {
344 usage |= 1 << uint(i)
345 }
346 }
347 return stdx509.KeyUsage(usage), nil
348 }
349
350 func parseBasicConstraintsExtension(der cryptobyte.String) (bool, int, error) {
351 var isCA bool
352 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
353 return false, 0, errors.New("x509: invalid basic constraints")
354 }
355 if der.PeekASN1Tag(cryptobyte_asn1.BOOLEAN) {
356 if !der.ReadASN1Boolean(&isCA) {
357 return false, 0, errors.New("x509: invalid basic constraints")
358 }
359 }
360 maxPathLen := -1
361 if der.PeekASN1Tag(cryptobyte_asn1.INTEGER) {
362 if !der.ReadASN1Integer(&maxPathLen) {
363 return false, 0, errors.New("x509: invalid basic constraints")
364 }
365 }
366
367 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
368 return isCA, maxPathLen, nil
369 }
370
371 func forEachSAN(der cryptobyte.String, callback func(tag int, data []byte) error) error {
372 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
373 return errors.New("x509: invalid subject alternative names")
374 }
375 for !der.Empty() {
376 var san cryptobyte.String
377 var tag cryptobyte_asn1.Tag
378 if !der.ReadAnyASN1(&san, &tag) {
379 return errors.New("x509: invalid subject alternative name")
380 }
381 if err := callback(int(tag^0x80), san); err != nil {
382 return err
383 }
384 }
385
386 return nil
387 }
388
389 func parseSANExtension(der cryptobyte.String) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
390 err = forEachSAN(der, func(tag int, data []byte) error {
391 switch tag {
392 case nameTypeEmail:
393 email := string(data)
394 if err := isIA5String(email); err != nil {
395 return errors.New("x509: SAN rfc822Name is malformed")
396 }
397 emailAddresses = append(emailAddresses, email)
398 case nameTypeDNS:
399 name := string(data)
400 if err := isIA5String(name); err != nil {
401 return errors.New("x509: SAN dNSName is malformed")
402 }
403 dnsNames = append(dnsNames, string(name))
404 case nameTypeURI:
405 uriStr := string(data)
406 if err := isIA5String(uriStr); err != nil {
407 return errors.New("x509: SAN uniformResourceIdentifier is malformed")
408 }
409 uri, err := url.Parse(uriStr)
410 if err != nil {
411 return fmt.Errorf("x509: cannot parse URI %q: %s", uriStr, err)
412 }
413 if len(uri.Host) > 0 {
414 if _, ok := domainToReverseLabels(uri.Host); !ok {
415 return fmt.Errorf("x509: cannot parse URI %q: invalid domain", uriStr)
416 }
417 }
418 uris = append(uris, uri)
419 case nameTypeIP:
420 switch len(data) {
421 case net.IPv4len, net.IPv6len:
422 ipAddresses = append(ipAddresses, data)
423 default:
424 return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
425 }
426 }
427
428 return nil
429 })
430
431 return
432 }
433
434 func parseAuthorityKeyIdentifier(e pkix.Extension) ([]byte, error) {
435 // RFC 5280, Section 4.2.1.1
436 // if e.Critical {
437 // // Conforming CAs MUST mark this extension as non-critical
438 // return nil, errors.New("x509: authority key identifier incorrectly marked critical")
439 // }
440 val := cryptobyte.String(e.Value)
441 var akid cryptobyte.String
442 if !val.ReadASN1(&akid, cryptobyte_asn1.SEQUENCE) {
443 return nil, errors.New("x509: invalid authority key identifier")
444 }
445 if akid.PeekASN1Tag(cryptobyte_asn1.Tag(0).ContextSpecific()) {
446 if !akid.ReadASN1(&akid, cryptobyte_asn1.Tag(0).ContextSpecific()) {
447 return nil, errors.New("x509: invalid authority key identifier")
448 }
449 return akid, nil
450 }
451 return nil, nil
452 }
453
454 func parseExtKeyUsageExtension(der cryptobyte.String) ([]stdx509.ExtKeyUsage, []asn1.ObjectIdentifier, error) {
455 var extKeyUsages []stdx509.ExtKeyUsage
456 var unknownUsages []asn1.ObjectIdentifier
457 if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
458 return nil, nil, errors.New("x509: invalid extended key usages")
459 }
460 for !der.Empty() {
461 var eku asn1.ObjectIdentifier
462 if !der.ReadASN1ObjectIdentifier(&eku) {
463 return nil, nil, errors.New("x509: invalid extended key usages")
464 }
465 if extKeyUsage, ok := extKeyUsageFromOID(eku); ok {
466 extKeyUsages = append(extKeyUsages, stdx509.ExtKeyUsage(extKeyUsage))
467 } else {
468 unknownUsages = append(unknownUsages, eku)
469 }
470 }
471 return extKeyUsages, unknownUsages, nil
472 }
473
474 // func parseCertificatePoliciesExtension(der cryptobyte.String) ([]OID, error) {
475 // var oids []OID
476 // if !der.ReadASN1(&der, cryptobyte_asn1.SEQUENCE) {
477 // return nil, errors.New("x509: invalid certificate policies")
478 // }
479 // for !der.Empty() {
480 // var cp cryptobyte.String
481 // var OIDBytes cryptobyte.String
482 // if !der.ReadASN1(&cp, cryptobyte_asn1.SEQUENCE) || !cp.ReadASN1(&OIDBytes, cryptobyte_asn1.OBJECT_IDENTIFIER) {
483 // return nil, errors.New("x509: invalid certificate policies")
484 // }
485 // oid, ok := newOIDFromDER(OIDBytes)
486 // if !ok {
487 // return nil, errors.New("x509: invalid certificate policies")
488 // }
489 // oids = append(oids, oid)
490 // }
491 // return oids, nil
492 // }
493
494 // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
495 func isValidIPMask(mask []byte) bool {
496 seenZero := false
497
498 for _, b := range mask {
499 if seenZero {
500 if b != 0 {
501 return false
502 }
503
504 continue
505 }
506
507 switch b {
508 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
509 seenZero = true
510 case 0xff:
511 default:
512 return false
513 }
514 }
515
516 return true
517 }
518
519 func parseNameConstraintsExtension(out *stdx509.Certificate, e pkix.Extension) (unhandled bool, err error) {
520 // RFC 5280, 4.2.1.10
521
522 // NameConstraints ::= SEQUENCE {
523 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
524 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
525 //
526 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
527 //
528 // GeneralSubtree ::= SEQUENCE {
529 // base GeneralName,
530 // minimum [0] BaseDistance DEFAULT 0,
531 // maximum [1] BaseDistance OPTIONAL }
532 //
533 // BaseDistance ::= INTEGER (0..MAX)
534
535 outer := cryptobyte.String(e.Value)
536 var toplevel, permitted, excluded cryptobyte.String
537 var havePermitted, haveExcluded bool
538 if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
539 !outer.Empty() ||
540 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
541 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
542 !toplevel.Empty() {
543 return false, errors.New("x509: invalid NameConstraints extension")
544 }
545
546 if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
547 // From RFC 5280, Section 4.2.1.10:
548 // “either the permittedSubtrees field
549 // or the excludedSubtrees MUST be
550 // present”
551 return false, errors.New("x509: empty name constraints extension")
552 }
553
554 getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
555 for !subtrees.Empty() {
556 var seq, value cryptobyte.String
557 var tag cryptobyte_asn1.Tag
558 if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
559 !seq.ReadAnyASN1(&value, &tag) {
560 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
561 }
562
563 var (
564 dnsTag = cryptobyte_asn1.Tag(2).ContextSpecific()
565 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
566 ipTag = cryptobyte_asn1.Tag(7).ContextSpecific()
567 uriTag = cryptobyte_asn1.Tag(6).ContextSpecific()
568 )
569
570 switch tag {
571 case dnsTag:
572 domain := string(value)
573 if err := isIA5String(domain); err != nil {
574 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
575 }
576
577 trimmedDomain := domain
578 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
579 // constraints can have a leading
580 // period to exclude the domain
581 // itself, but that's not valid in a
582 // normal domain name.
583 trimmedDomain = trimmedDomain[1:]
584 }
585 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
586 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
587 }
588 dnsNames = append(dnsNames, domain)
589
590 case ipTag:
591 l := len(value)
592 var ip, mask []byte
593
594 switch l {
595 case 8:
596 ip = value[:4]
597 mask = value[4:]
598
599 case 32:
600 ip = value[:16]
601 mask = value[16:]
602
603 default:
604 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
605 }
606
607 if !isValidIPMask(mask) {
608 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
609 }
610
611 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
612
613 case emailTag:
614 constraint := string(value)
615 if err := isIA5String(constraint); err != nil {
616 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
617 }
618
619 // If the constraint contains an @ then
620 // it specifies an exact mailbox name.
621 if strings.Contains(constraint, "@") {
622 if _, ok := parseRFC2821Mailbox(constraint); !ok {
623 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
624 }
625 } else {
626 // Otherwise it's a domain name.
627 domain := constraint
628 if len(domain) > 0 && domain[0] == '.' {
629 domain = domain[1:]
630 }
631 if _, ok := domainToReverseLabels(domain); !ok {
632 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
633 }
634 }
635 emails = append(emails, constraint)
636
637 case uriTag:
638 domain := string(value)
639 if err := isIA5String(domain); err != nil {
640 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
641 }
642
643 if net.ParseIP(domain) != nil {
644 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
645 }
646
647 trimmedDomain := domain
648 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
649 // constraints can have a leading
650 // period to exclude the domain itself,
651 // but that's not valid in a normal
652 // domain name.
653 trimmedDomain = trimmedDomain[1:]
654 }
655 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
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 *stdx509.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 37:
766 out.ExtKeyUsage, out.UnknownExtKeyUsage, err = parseExtKeyUsageExtension(e.Value)
767 if err != nil {
768 return err
769 }
770 case 14:
771 // RFC 5280, 4.2.1.2
772 if e.Critical {
773 // Conforming CAs MUST mark this extension as non-critical
774 return errors.New("x509: subject key identifier incorrectly marked critical")
775 }
776 val := cryptobyte.String(e.Value)
777 var skid cryptobyte.String
778 if !val.ReadASN1(&skid, cryptobyte_asn1.OCTET_STRING) {
779 return errors.New("x509: invalid subject key identifier")
780 }
781 out.SubjectKeyId = skid
782 // case 32:
783 // out.Policies, err = parseCertificatePoliciesExtension(e.Value)
784 // if err != nil {
785 // return err
786 // }
787 // out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, 0, len(out.Policies))
788 // for _, oid := range out.Policies {
789 // if oid, ok := oid.toASN1OID(); ok {
790 // out.PolicyIdentifiers = append(out.PolicyIdentifiers, oid)
791 // }
792 // }
793 default:
794 // Unknown extensions are recorded if critical.
795 unhandled = true
796 }
797 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
798 // RFC 5280 4.2.2.1: Authority Information Access
799 if e.Critical {
800 // Conforming CAs MUST mark this extension as non-critical
801 return errors.New("x509: authority info access incorrectly marked critical")
802 }
803 val := cryptobyte.String(e.Value)
804 if !val.ReadASN1(&val, cryptobyte_asn1.SEQUENCE) {
805 return errors.New("x509: invalid authority info access")
806 }
807 for !val.Empty() {
808 var aiaDER cryptobyte.String
809 if !val.ReadASN1(&aiaDER, cryptobyte_asn1.SEQUENCE) {
810 return errors.New("x509: invalid authority info access")
811 }
812 var method asn1.ObjectIdentifier
813 if !aiaDER.ReadASN1ObjectIdentifier(&method) {
814 return errors.New("x509: invalid authority info access")
815 }
816 if !aiaDER.PeekASN1Tag(cryptobyte_asn1.Tag(6).ContextSpecific()) {
817 continue
818 }
819 if !aiaDER.ReadASN1(&aiaDER, cryptobyte_asn1.Tag(6).ContextSpecific()) {
820 return errors.New("x509: invalid authority info access")
821 }
822 switch {
823 case method.Equal(oidAuthorityInfoAccessOcsp):
824 out.OCSPServer = append(out.OCSPServer, string(aiaDER))
825 case method.Equal(oidAuthorityInfoAccessIssuers):
826 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(aiaDER))
827 }
828 }
829 } else {
830 // Unknown extensions are recorded if critical.
831 unhandled = true
832 }
833
834 if e.Critical && unhandled {
835 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
836 }
837 }
838
839 return nil
840 }
841
842 var x509negativeserial = legacyGodebugSetting(0) // replaces godebug.New("x509negativeserial")
843
844 func parseCertificate(der []byte) (*stdx509.Certificate, error) {
845 cert := &stdx509.Certificate{}
846
847 input := cryptobyte.String(der)
848 // we read the SEQUENCE including length and tag bytes so that
849 // we can populate Certificate.Raw, before unwrapping the
850 // SEQUENCE so it can be operated on
851 if !input.ReadASN1Element(&input, cryptobyte_asn1.SEQUENCE) {
852 return nil, errors.New("x509: malformed certificate")
853 }
854 cert.Raw = input
855 if !input.ReadASN1(&input, cryptobyte_asn1.SEQUENCE) {
856 return nil, errors.New("x509: malformed certificate")
857 }
858
859 var tbs cryptobyte.String
860 // do the same trick again as above to extract the raw
861 // bytes for Certificate.RawTBSCertificate
862 if !input.ReadASN1Element(&tbs, cryptobyte_asn1.SEQUENCE) {
863 return nil, errors.New("x509: malformed tbs certificate")
864 }
865 cert.RawTBSCertificate = tbs
866 if !tbs.ReadASN1(&tbs, cryptobyte_asn1.SEQUENCE) {
867 return nil, errors.New("x509: malformed tbs certificate")
868 }
869
870 if !tbs.ReadOptionalASN1Integer(&cert.Version, cryptobyte_asn1.Tag(0).Constructed().ContextSpecific(), 0) {
871 return nil, errors.New("x509: malformed version")
872 }
873 if cert.Version < 0 {
874 return nil, errors.New("x509: malformed version")
875 }
876 // for backwards compat reasons Version is one-indexed,
877 // rather than zero-indexed as defined in 5280
878 cert.Version++
879 if cert.Version > 3 {
880 return nil, errors.New("x509: invalid version")
881 }
882
883 serial := new(big.Int)
884 if !tbs.ReadASN1Integer(serial) {
885 return nil, errors.New("x509: malformed serial number")
886 }
887 if serial.Sign() == -1 {
888 if x509negativeserial.Value() != "1" {
889 return nil, errors.New("x509: negative serial number")
890 } else {
891 x509negativeserial.IncNonDefault()
892 }
893 }
894 cert.SerialNumber = serial
895
896 var sigAISeq cryptobyte.String
897 if !tbs.ReadASN1(&sigAISeq, cryptobyte_asn1.SEQUENCE) {
898 return nil, errors.New("x509: malformed signature algorithm identifier")
899 }
900 // Before parsing the inner algorithm identifier, extract
901 // the outer algorithm identifier and make sure that they
902 // match.
903 var outerSigAISeq cryptobyte.String
904 if !input.ReadASN1(&outerSigAISeq, cryptobyte_asn1.SEQUENCE) {
905 return nil, errors.New("x509: malformed algorithm identifier")
906 }
907 if !bytes.Equal(outerSigAISeq, sigAISeq) {
908 return nil, errors.New("x509: inner and outer signature algorithm identifiers don't match")
909 }
910 sigAI, err := parseAI(sigAISeq)
911 if err != nil {
912 return nil, err
913 }
914 cert.SignatureAlgorithm = getSignatureAlgorithmFromAI(sigAI)
915
916 var issuerSeq cryptobyte.String
917 if !tbs.ReadASN1Element(&issuerSeq, cryptobyte_asn1.SEQUENCE) {
918 return nil, errors.New("x509: malformed issuer")
919 }
920 cert.RawIssuer = issuerSeq
921 issuerRDNs, err := parseName(issuerSeq)
922 if err != nil {
923 return nil, err
924 }
925 cert.Issuer.FillFromRDNSequence(issuerRDNs)
926
927 var validity cryptobyte.String
928 if !tbs.ReadASN1(&validity, cryptobyte_asn1.SEQUENCE) {
929 return nil, errors.New("x509: malformed validity")
930 }
931 cert.NotBefore, cert.NotAfter, err = parseValidity(validity)
932 if err != nil {
933 return nil, err
934 }
935
936 var subjectSeq cryptobyte.String
937 if !tbs.ReadASN1Element(&subjectSeq, cryptobyte_asn1.SEQUENCE) {
938 return nil, errors.New("x509: malformed issuer")
939 }
940 cert.RawSubject = subjectSeq
941 subjectRDNs, err := parseName(subjectSeq)
942 if err != nil {
943 return nil, err
944 }
945 cert.Subject.FillFromRDNSequence(subjectRDNs)
946
947 var spki cryptobyte.String
948 if !tbs.ReadASN1Element(&spki, cryptobyte_asn1.SEQUENCE) {
949 return nil, errors.New("x509: malformed spki")
950 }
951 cert.RawSubjectPublicKeyInfo = spki
952 if !spki.ReadASN1(&spki, cryptobyte_asn1.SEQUENCE) {
953 return nil, errors.New("x509: malformed spki")
954 }
955 var pkAISeq cryptobyte.String
956 if !spki.ReadASN1(&pkAISeq, cryptobyte_asn1.SEQUENCE) {
957 return nil, errors.New("x509: malformed public key algorithm identifier")
958 }
959 pkAI, err := parseAI(pkAISeq)
960 if err != nil {
961 return nil, err
962 }
963 cert.PublicKeyAlgorithm = getPublicKeyAlgorithmFromOID(pkAI.Algorithm)
964 var spk asn1.BitString
965 if !spki.ReadASN1BitString(&spk) {
966 return nil, errors.New("x509: malformed subjectPublicKey")
967 }
968 if cert.PublicKeyAlgorithm != stdx509.UnknownPublicKeyAlgorithm {
969 cert.PublicKey, err = parsePublicKey(&publicKeyInfo{
970 Algorithm: pkAI,
971 PublicKey: spk,
972 })
973 if err != nil {
974 return nil, err
975 }
976 }
977
978 if cert.Version > 1 {
979 if !tbs.SkipOptionalASN1(cryptobyte_asn1.Tag(1).ContextSpecific()) {
980 return nil, errors.New("x509: malformed issuerUniqueID")
981 }
982 if !tbs.SkipOptionalASN1(cryptobyte_asn1.Tag(2).ContextSpecific()) {
983 return nil, errors.New("x509: malformed subjectUniqueID")
984 }
985 if cert.Version == 3 {
986 var extensions cryptobyte.String
987 var present bool
988 if !tbs.ReadOptionalASN1(&extensions, &present, cryptobyte_asn1.Tag(3).Constructed().ContextSpecific()) {
989 return nil, errors.New("x509: malformed extensions")
990 }
991 if present {
992 seenExts := make(map[string]bool)
993 if !extensions.ReadASN1(&extensions, cryptobyte_asn1.SEQUENCE) {
994 return nil, errors.New("x509: malformed extensions")
995 }
996 for !extensions.Empty() {
997 var extension cryptobyte.String
998 if !extensions.ReadASN1(&extension, cryptobyte_asn1.SEQUENCE) {
999 return nil, errors.New("x509: malformed extension")
1000 }
1001 ext, err := parseExtension(extension)
1002 if err != nil {
1003 return nil, err
1004 }
1005 oidStr := ext.Id.String()
1006 if seenExts[oidStr] {
1007 return nil, fmt.Errorf("x509: certificate contains duplicate extension with OID %q", oidStr)
1008 }
1009 seenExts[oidStr] = true
1010 cert.Extensions = append(cert.Extensions, ext)
1011 }
1012 err = processExtensions(cert)
1013 if err != nil {
1014 return nil, err
1015 }
1016 }
1017 }
1018 }
1019
1020 var signature asn1.BitString
1021 if !input.ReadASN1BitString(&signature) {
1022 return nil, errors.New("x509: malformed signature")
1023 }
1024 cert.Signature = signature.RightAlign()
1025
1026 return cert, nil
1027 }