1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package x509
22
23 import (
24 "bytes"
25 "crypto"
26 "crypto/ecdh"
27 "crypto/ecdsa"
28 "crypto/ed25519"
29 "crypto/elliptic"
30 "crypto/rsa"
31 "crypto/sha1"
32 "crypto/x509/pkix"
33 "encoding/asn1"
34 "encoding/pem"
35 "errors"
36 "fmt"
37 "internal/godebug"
38 "io"
39 "math/big"
40 "net"
41 "net/url"
42 "strconv"
43 "time"
44 "unicode"
45
46
47
48 _ "crypto/sha1"
49 _ "crypto/sha256"
50 _ "crypto/sha512"
51
52 "golang.org/x/crypto/cryptobyte"
53 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
54 )
55
56
57
58 type pkixPublicKey struct {
59 Algo pkix.AlgorithmIdentifier
60 BitString asn1.BitString
61 }
62
63
64
65
66
67
68
69
70
71 func ParsePKIXPublicKey(derBytes []byte) (pub any, err error) {
72 var pki publicKeyInfo
73 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
74 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
75 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
76 }
77 return nil, err
78 } else if len(rest) != 0 {
79 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
80 }
81 return parsePublicKey(&pki)
82 }
83
84 func marshalPublicKey(pub any) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
85 switch pub := pub.(type) {
86 case *rsa.PublicKey:
87 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
88 N: pub.N,
89 E: pub.E,
90 })
91 if err != nil {
92 return nil, pkix.AlgorithmIdentifier{}, err
93 }
94 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
95
96
97 publicKeyAlgorithm.Parameters = asn1.NullRawValue
98 case *ecdsa.PublicKey:
99 oid, ok := oidFromNamedCurve(pub.Curve)
100 if !ok {
101 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
102 }
103 if !pub.Curve.IsOnCurve(pub.X, pub.Y) {
104 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: invalid elliptic curve public key")
105 }
106 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
107 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
108 var paramBytes []byte
109 paramBytes, err = asn1.Marshal(oid)
110 if err != nil {
111 return
112 }
113 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
114 case ed25519.PublicKey:
115 publicKeyBytes = pub
116 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
117 case *ecdh.PublicKey:
118 publicKeyBytes = pub.Bytes()
119 if pub.Curve() == ecdh.X25519() {
120 publicKeyAlgorithm.Algorithm = oidPublicKeyX25519
121 } else {
122 oid, ok := oidFromECDHCurve(pub.Curve())
123 if !ok {
124 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
125 }
126 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
127 var paramBytes []byte
128 paramBytes, err = asn1.Marshal(oid)
129 if err != nil {
130 return
131 }
132 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
133 }
134 default:
135 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
136 }
137
138 return publicKeyBytes, publicKeyAlgorithm, nil
139 }
140
141
142
143
144
145
146
147
148
149
150 func MarshalPKIXPublicKey(pub any) ([]byte, error) {
151 var publicKeyBytes []byte
152 var publicKeyAlgorithm pkix.AlgorithmIdentifier
153 var err error
154
155 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
156 return nil, err
157 }
158
159 pkix := pkixPublicKey{
160 Algo: publicKeyAlgorithm,
161 BitString: asn1.BitString{
162 Bytes: publicKeyBytes,
163 BitLength: 8 * len(publicKeyBytes),
164 },
165 }
166
167 ret, _ := asn1.Marshal(pkix)
168 return ret, nil
169 }
170
171
172
173 type certificate struct {
174 TBSCertificate tbsCertificate
175 SignatureAlgorithm pkix.AlgorithmIdentifier
176 SignatureValue asn1.BitString
177 }
178
179 type tbsCertificate struct {
180 Raw asn1.RawContent
181 Version int `asn1:"optional,explicit,default:0,tag:0"`
182 SerialNumber *big.Int
183 SignatureAlgorithm pkix.AlgorithmIdentifier
184 Issuer asn1.RawValue
185 Validity validity
186 Subject asn1.RawValue
187 PublicKey publicKeyInfo
188 UniqueId asn1.BitString `asn1:"optional,tag:1"`
189 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
190 Extensions []pkix.Extension `asn1:"omitempty,optional,explicit,tag:3"`
191 }
192
193 type dsaAlgorithmParameters struct {
194 P, Q, G *big.Int
195 }
196
197 type validity struct {
198 NotBefore, NotAfter time.Time
199 }
200
201 type publicKeyInfo struct {
202 Raw asn1.RawContent
203 Algorithm pkix.AlgorithmIdentifier
204 PublicKey asn1.BitString
205 }
206
207
208 type authKeyId struct {
209 Id []byte `asn1:"optional,tag:0"`
210 }
211
212 type SignatureAlgorithm int
213
214 const (
215 UnknownSignatureAlgorithm SignatureAlgorithm = iota
216
217 MD2WithRSA
218 MD5WithRSA
219 SHA1WithRSA
220 SHA256WithRSA
221 SHA384WithRSA
222 SHA512WithRSA
223 DSAWithSHA1
224 DSAWithSHA256
225 ECDSAWithSHA1
226 ECDSAWithSHA256
227 ECDSAWithSHA384
228 ECDSAWithSHA512
229 SHA256WithRSAPSS
230 SHA384WithRSAPSS
231 SHA512WithRSAPSS
232 PureEd25519
233 )
234
235 func (algo SignatureAlgorithm) isRSAPSS() bool {
236 for _, details := range signatureAlgorithmDetails {
237 if details.algo == algo {
238 return details.isRSAPSS
239 }
240 }
241 return false
242 }
243
244 func (algo SignatureAlgorithm) hashFunc() crypto.Hash {
245 for _, details := range signatureAlgorithmDetails {
246 if details.algo == algo {
247 return details.hash
248 }
249 }
250 return crypto.Hash(0)
251 }
252
253 func (algo SignatureAlgorithm) String() string {
254 for _, details := range signatureAlgorithmDetails {
255 if details.algo == algo {
256 return details.name
257 }
258 }
259 return strconv.Itoa(int(algo))
260 }
261
262 type PublicKeyAlgorithm int
263
264 const (
265 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
266 RSA
267 DSA
268 ECDSA
269 Ed25519
270 )
271
272 var publicKeyAlgoName = [...]string{
273 RSA: "RSA",
274 DSA: "DSA",
275 ECDSA: "ECDSA",
276 Ed25519: "Ed25519",
277 }
278
279 func (algo PublicKeyAlgorithm) String() string {
280 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
281 return publicKeyAlgoName[algo]
282 }
283 return strconv.Itoa(int(algo))
284 }
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334 var (
335 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
336 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
337 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
338 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
339 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
340 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
341 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
342 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
343 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
344 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
345 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
346 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
347 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
348
349 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
350 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
351 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
352
353 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
354
355
356
357
358 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
359 )
360
361 var signatureAlgorithmDetails = []struct {
362 algo SignatureAlgorithm
363 name string
364 oid asn1.ObjectIdentifier
365 params asn1.RawValue
366 pubKeyAlgo PublicKeyAlgorithm
367 hash crypto.Hash
368 isRSAPSS bool
369 }{
370 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, asn1.NullRawValue, RSA, crypto.MD5, false},
371 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, asn1.NullRawValue, RSA, crypto.SHA1, false},
372 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, asn1.NullRawValue, RSA, crypto.SHA1, false},
373 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, asn1.NullRawValue, RSA, crypto.SHA256, false},
374 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, asn1.NullRawValue, RSA, crypto.SHA384, false},
375 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, asn1.NullRawValue, RSA, crypto.SHA512, false},
376 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, pssParametersSHA256, RSA, crypto.SHA256, true},
377 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, pssParametersSHA384, RSA, crypto.SHA384, true},
378 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, pssParametersSHA512, RSA, crypto.SHA512, true},
379 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, emptyRawValue, DSA, crypto.SHA1, false},
380 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, emptyRawValue, DSA, crypto.SHA256, false},
381 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, emptyRawValue, ECDSA, crypto.SHA1, false},
382 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, emptyRawValue, ECDSA, crypto.SHA256, false},
383 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, emptyRawValue, ECDSA, crypto.SHA384, false},
384 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, emptyRawValue, ECDSA, crypto.SHA512, false},
385 {PureEd25519, "Ed25519", oidSignatureEd25519, emptyRawValue, Ed25519, crypto.Hash(0) , false},
386 }
387
388 var emptyRawValue = asn1.RawValue{}
389
390
391
392
393
394
395
396
397 var (
398 pssParametersSHA256 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 162, 3, 2, 1, 32}}
399 pssParametersSHA384 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 162, 3, 2, 1, 48}}
400 pssParametersSHA512 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 162, 3, 2, 1, 64}}
401 )
402
403
404
405 type pssParameters struct {
406
407
408
409 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
410 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
411 SaltLength int `asn1:"explicit,tag:2"`
412 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
413 }
414
415 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
416 if ai.Algorithm.Equal(oidSignatureEd25519) {
417
418
419 if len(ai.Parameters.FullBytes) != 0 {
420 return UnknownSignatureAlgorithm
421 }
422 }
423
424 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
425 for _, details := range signatureAlgorithmDetails {
426 if ai.Algorithm.Equal(details.oid) {
427 return details.algo
428 }
429 }
430 return UnknownSignatureAlgorithm
431 }
432
433
434
435
436 var params pssParameters
437 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
438 return UnknownSignatureAlgorithm
439 }
440
441 var mgf1HashFunc pkix.AlgorithmIdentifier
442 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
443 return UnknownSignatureAlgorithm
444 }
445
446
447
448
449
450
451 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
452 !params.MGF.Algorithm.Equal(oidMGF1) ||
453 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
454 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
455 params.TrailerField != 1 {
456 return UnknownSignatureAlgorithm
457 }
458
459 switch {
460 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
461 return SHA256WithRSAPSS
462 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
463 return SHA384WithRSAPSS
464 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
465 return SHA512WithRSAPSS
466 }
467
468 return UnknownSignatureAlgorithm
469 }
470
471 var (
472
473
474
475
476
477
478
479
480
481 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
482 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
483
484
485
486
487 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
488
489
490
491
492 oidPublicKeyX25519 = asn1.ObjectIdentifier{1, 3, 101, 110}
493 oidPublicKeyEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
494 )
495
496
497
498
499 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
500 switch {
501 case oid.Equal(oidPublicKeyRSA):
502 return RSA
503 case oid.Equal(oidPublicKeyDSA):
504 return DSA
505 case oid.Equal(oidPublicKeyECDSA):
506 return ECDSA
507 case oid.Equal(oidPublicKeyEd25519):
508 return Ed25519
509 }
510 return UnknownPublicKeyAlgorithm
511 }
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529 var (
530 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
531 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
532 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
533 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
534 )
535
536 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
537 switch {
538 case oid.Equal(oidNamedCurveP224):
539 return elliptic.P224()
540 case oid.Equal(oidNamedCurveP256):
541 return elliptic.P256()
542 case oid.Equal(oidNamedCurveP384):
543 return elliptic.P384()
544 case oid.Equal(oidNamedCurveP521):
545 return elliptic.P521()
546 }
547 return nil
548 }
549
550 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
551 switch curve {
552 case elliptic.P224():
553 return oidNamedCurveP224, true
554 case elliptic.P256():
555 return oidNamedCurveP256, true
556 case elliptic.P384():
557 return oidNamedCurveP384, true
558 case elliptic.P521():
559 return oidNamedCurveP521, true
560 }
561
562 return nil, false
563 }
564
565 func oidFromECDHCurve(curve ecdh.Curve) (asn1.ObjectIdentifier, bool) {
566 switch curve {
567 case ecdh.X25519():
568 return oidPublicKeyX25519, true
569 case ecdh.P256():
570 return oidNamedCurveP256, true
571 case ecdh.P384():
572 return oidNamedCurveP384, true
573 case ecdh.P521():
574 return oidNamedCurveP521, true
575 }
576
577 return nil, false
578 }
579
580
581
582 type KeyUsage int
583
584 const (
585 KeyUsageDigitalSignature KeyUsage = 1 << iota
586 KeyUsageContentCommitment
587 KeyUsageKeyEncipherment
588 KeyUsageDataEncipherment
589 KeyUsageKeyAgreement
590 KeyUsageCertSign
591 KeyUsageCRLSign
592 KeyUsageEncipherOnly
593 KeyUsageDecipherOnly
594 )
595
596
597
598
599
600
601
602
603
604
605
606
607
608 var (
609 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
610 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
611 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
612 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
613 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
614 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
615 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
616 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
617 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
618 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
619 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
620 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
621 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
622 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
623 )
624
625
626
627 type ExtKeyUsage int
628
629 const (
630 ExtKeyUsageAny ExtKeyUsage = iota
631 ExtKeyUsageServerAuth
632 ExtKeyUsageClientAuth
633 ExtKeyUsageCodeSigning
634 ExtKeyUsageEmailProtection
635 ExtKeyUsageIPSECEndSystem
636 ExtKeyUsageIPSECTunnel
637 ExtKeyUsageIPSECUser
638 ExtKeyUsageTimeStamping
639 ExtKeyUsageOCSPSigning
640 ExtKeyUsageMicrosoftServerGatedCrypto
641 ExtKeyUsageNetscapeServerGatedCrypto
642 ExtKeyUsageMicrosoftCommercialCodeSigning
643 ExtKeyUsageMicrosoftKernelCodeSigning
644 )
645
646
647 var extKeyUsageOIDs = []struct {
648 extKeyUsage ExtKeyUsage
649 oid asn1.ObjectIdentifier
650 }{
651 {ExtKeyUsageAny, oidExtKeyUsageAny},
652 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
653 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
654 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
655 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
656 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
657 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
658 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
659 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
660 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
661 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
662 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
663 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
664 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
665 }
666
667 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
668 for _, pair := range extKeyUsageOIDs {
669 if oid.Equal(pair.oid) {
670 return pair.extKeyUsage, true
671 }
672 }
673 return
674 }
675
676 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
677 for _, pair := range extKeyUsageOIDs {
678 if eku == pair.extKeyUsage {
679 return pair.oid, true
680 }
681 }
682 return
683 }
684
685
686 type Certificate struct {
687 Raw []byte
688 RawTBSCertificate []byte
689 RawSubjectPublicKeyInfo []byte
690 RawSubject []byte
691 RawIssuer []byte
692
693 Signature []byte
694 SignatureAlgorithm SignatureAlgorithm
695
696 PublicKeyAlgorithm PublicKeyAlgorithm
697 PublicKey any
698
699 Version int
700 SerialNumber *big.Int
701 Issuer pkix.Name
702 Subject pkix.Name
703 NotBefore, NotAfter time.Time
704 KeyUsage KeyUsage
705
706
707
708
709
710 Extensions []pkix.Extension
711
712
713
714
715
716 ExtraExtensions []pkix.Extension
717
718
719
720
721
722
723
724
725
726 UnhandledCriticalExtensions []asn1.ObjectIdentifier
727
728 ExtKeyUsage []ExtKeyUsage
729 UnknownExtKeyUsage []asn1.ObjectIdentifier
730
731
732
733 BasicConstraintsValid bool
734 IsCA bool
735
736
737
738
739
740
741
742
743
744
745
746
747
748 MaxPathLen int
749
750
751
752
753 MaxPathLenZero bool
754
755 SubjectKeyId []byte
756 AuthorityKeyId []byte
757
758
759 OCSPServer []string
760 IssuingCertificateURL []string
761
762
763
764
765 DNSNames []string
766 EmailAddresses []string
767 IPAddresses []net.IP
768 URIs []*url.URL
769
770
771 PermittedDNSDomainsCritical bool
772 PermittedDNSDomains []string
773 ExcludedDNSDomains []string
774 PermittedIPRanges []*net.IPNet
775 ExcludedIPRanges []*net.IPNet
776 PermittedEmailAddresses []string
777 ExcludedEmailAddresses []string
778 PermittedURIDomains []string
779 ExcludedURIDomains []string
780
781
782 CRLDistributionPoints []string
783
784
785
786
787
788
789
790
791 PolicyIdentifiers []asn1.ObjectIdentifier
792
793
794
795
796
797 Policies []OID
798
799
800
801
802
803
804
805
806
807
808
809
810
811 InhibitAnyPolicy int
812
813
814
815 InhibitAnyPolicyZero bool
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831 InhibitPolicyMapping int
832
833
834
835 InhibitPolicyMappingZero bool
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854 RequireExplicitPolicy int
855
856
857
858 RequireExplicitPolicyZero bool
859
860
861 PolicyMappings []PolicyMapping
862 }
863
864
865 type PolicyMapping struct {
866
867
868 IssuerDomainPolicy OID
869
870
871 SubjectDomainPolicy OID
872 }
873
874
875
876 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
877
878
879
880 type InsecureAlgorithmError SignatureAlgorithm
881
882 func (e InsecureAlgorithmError) Error() string {
883 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
884 }
885
886
887
888
889 type ConstraintViolationError struct{}
890
891 func (ConstraintViolationError) Error() string {
892 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
893 }
894
895 func (c *Certificate) Equal(other *Certificate) bool {
896 if c == nil || other == nil {
897 return c == other
898 }
899 return bytes.Equal(c.Raw, other.Raw)
900 }
901
902 func (c *Certificate) hasSANExtension() bool {
903 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
904 }
905
906
907
908
909
910 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
911
912
913
914
915
916 if parent.Version == 3 && !parent.BasicConstraintsValid ||
917 parent.BasicConstraintsValid && !parent.IsCA {
918 return ConstraintViolationError{}
919 }
920
921 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
922 return ConstraintViolationError{}
923 }
924
925 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
926 return ErrUnsupportedAlgorithm
927 }
928
929 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature, parent.PublicKey, false)
930 }
931
932
933
934
935
936
937
938
939 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
940 return checkSignature(algo, signed, signature, c.PublicKey, true)
941 }
942
943 func (c *Certificate) hasNameConstraints() bool {
944 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
945 }
946
947 func (c *Certificate) getSANExtension() []byte {
948 for _, e := range c.Extensions {
949 if e.Id.Equal(oidExtensionSubjectAltName) {
950 return e.Value
951 }
952 }
953 return nil
954 }
955
956 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {
957 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
958 }
959
960
961
962 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error) {
963 var hashType crypto.Hash
964 var pubKeyAlgo PublicKeyAlgorithm
965
966 for _, details := range signatureAlgorithmDetails {
967 if details.algo == algo {
968 hashType = details.hash
969 pubKeyAlgo = details.pubKeyAlgo
970 break
971 }
972 }
973
974 switch hashType {
975 case crypto.Hash(0):
976 if pubKeyAlgo != Ed25519 {
977 return ErrUnsupportedAlgorithm
978 }
979 case crypto.MD5:
980 return InsecureAlgorithmError(algo)
981 case crypto.SHA1:
982
983 if !allowSHA1 {
984 return InsecureAlgorithmError(algo)
985 }
986 fallthrough
987 default:
988 if !hashType.Available() {
989 return ErrUnsupportedAlgorithm
990 }
991 h := hashType.New()
992 h.Write(signed)
993 signed = h.Sum(nil)
994 }
995
996 switch pub := publicKey.(type) {
997 case *rsa.PublicKey:
998 if pubKeyAlgo != RSA {
999 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1000 }
1001 if algo.isRSAPSS() {
1002 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
1003 } else {
1004 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
1005 }
1006 case *ecdsa.PublicKey:
1007 if pubKeyAlgo != ECDSA {
1008 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1009 }
1010 if !ecdsa.VerifyASN1(pub, signed, signature) {
1011 return errors.New("x509: ECDSA verification failure")
1012 }
1013 return
1014 case ed25519.PublicKey:
1015 if pubKeyAlgo != Ed25519 {
1016 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1017 }
1018 if !ed25519.Verify(pub, signed, signature) {
1019 return errors.New("x509: Ed25519 verification failure")
1020 }
1021 return
1022 }
1023 return ErrUnsupportedAlgorithm
1024 }
1025
1026
1027
1028
1029 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
1030 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
1031 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
1032 }
1033
1034 type UnhandledCriticalExtension struct{}
1035
1036 func (h UnhandledCriticalExtension) Error() string {
1037 return "x509: unhandled critical extension"
1038 }
1039
1040 type basicConstraints struct {
1041 IsCA bool `asn1:"optional"`
1042 MaxPathLen int `asn1:"optional,default:-1"`
1043 }
1044
1045
1046 type policyInformation struct {
1047 Policy asn1.ObjectIdentifier
1048
1049 }
1050
1051 const (
1052 nameTypeEmail = 1
1053 nameTypeDNS = 2
1054 nameTypeURI = 6
1055 nameTypeIP = 7
1056 )
1057
1058
1059 type authorityInfoAccess struct {
1060 Method asn1.ObjectIdentifier
1061 Location asn1.RawValue
1062 }
1063
1064
1065 type distributionPoint struct {
1066 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
1067 Reason asn1.BitString `asn1:"optional,tag:1"`
1068 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
1069 }
1070
1071 type distributionPointName struct {
1072 FullName []asn1.RawValue `asn1:"optional,tag:0"`
1073 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
1074 }
1075
1076 func reverseBitsInAByte(in byte) byte {
1077 b1 := in>>4 | in<<4
1078 b2 := b1>>2&0x33 | b1<<2&0xcc
1079 b3 := b2>>1&0x55 | b2<<1&0xaa
1080 return b3
1081 }
1082
1083
1084
1085
1086 func asn1BitLength(bitString []byte) int {
1087 bitLen := len(bitString) * 8
1088
1089 for i := range bitString {
1090 b := bitString[len(bitString)-i-1]
1091
1092 for bit := uint(0); bit < 8; bit++ {
1093 if (b>>bit)&1 == 1 {
1094 return bitLen
1095 }
1096 bitLen--
1097 }
1098 }
1099
1100 return 0
1101 }
1102
1103 var (
1104 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1105 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1106 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1107 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1108 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1109 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1110 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1111 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1112 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1113 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1114 oidExtensionCRLNumber = []int{2, 5, 29, 20}
1115 oidExtensionReasonCode = []int{2, 5, 29, 21}
1116 )
1117
1118 var (
1119 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1120 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1121 )
1122
1123
1124
1125 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1126 for _, e := range extensions {
1127 if e.Id.Equal(oid) {
1128 return true
1129 }
1130 }
1131 return false
1132 }
1133
1134
1135
1136 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1137 var rawValues []asn1.RawValue
1138 for _, name := range dnsNames {
1139 if err := isIA5String(name); err != nil {
1140 return nil, err
1141 }
1142 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1143 }
1144 for _, email := range emailAddresses {
1145 if err := isIA5String(email); err != nil {
1146 return nil, err
1147 }
1148 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1149 }
1150 for _, rawIP := range ipAddresses {
1151
1152 ip := rawIP.To4()
1153 if ip == nil {
1154 ip = rawIP
1155 }
1156 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1157 }
1158 for _, uri := range uris {
1159 uriStr := uri.String()
1160 if err := isIA5String(uriStr); err != nil {
1161 return nil, err
1162 }
1163 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1164 }
1165 return asn1.Marshal(rawValues)
1166 }
1167
1168 func isIA5String(s string) error {
1169 for _, r := range s {
1170
1171 if r > unicode.MaxASCII {
1172 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1173 }
1174 }
1175
1176 return nil
1177 }
1178
1179 var x509usepolicies = godebug.New("x509usepolicies")
1180
1181 func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1182 ret = make([]pkix.Extension, 10 )
1183 n := 0
1184
1185 if template.KeyUsage != 0 &&
1186 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1187 ret[n], err = marshalKeyUsage(template.KeyUsage)
1188 if err != nil {
1189 return nil, err
1190 }
1191 n++
1192 }
1193
1194 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1195 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1196 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
1197 if err != nil {
1198 return nil, err
1199 }
1200 n++
1201 }
1202
1203 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1204 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
1205 if err != nil {
1206 return nil, err
1207 }
1208 n++
1209 }
1210
1211 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1212 ret[n].Id = oidExtensionSubjectKeyId
1213 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1214 if err != nil {
1215 return
1216 }
1217 n++
1218 }
1219
1220 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1221 ret[n].Id = oidExtensionAuthorityKeyId
1222 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1223 if err != nil {
1224 return
1225 }
1226 n++
1227 }
1228
1229 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1230 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1231 ret[n].Id = oidExtensionAuthorityInfoAccess
1232 var aiaValues []authorityInfoAccess
1233 for _, name := range template.OCSPServer {
1234 aiaValues = append(aiaValues, authorityInfoAccess{
1235 Method: oidAuthorityInfoAccessOcsp,
1236 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1237 })
1238 }
1239 for _, name := range template.IssuingCertificateURL {
1240 aiaValues = append(aiaValues, authorityInfoAccess{
1241 Method: oidAuthorityInfoAccessIssuers,
1242 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1243 })
1244 }
1245 ret[n].Value, err = asn1.Marshal(aiaValues)
1246 if err != nil {
1247 return
1248 }
1249 n++
1250 }
1251
1252 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1253 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1254 ret[n].Id = oidExtensionSubjectAltName
1255
1256
1257
1258 ret[n].Critical = subjectIsEmpty
1259 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1260 if err != nil {
1261 return
1262 }
1263 n++
1264 }
1265
1266 usePolicies := x509usepolicies.Value() != "0"
1267 if ((!usePolicies && len(template.PolicyIdentifiers) > 0) || (usePolicies && len(template.Policies) > 0)) &&
1268 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1269 ret[n], err = marshalCertificatePolicies(template.Policies, template.PolicyIdentifiers)
1270 if err != nil {
1271 return nil, err
1272 }
1273 n++
1274 }
1275
1276 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1277 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1278 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1279 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1280 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1281 ret[n].Id = oidExtensionNameConstraints
1282 ret[n].Critical = template.PermittedDNSDomainsCritical
1283
1284 ipAndMask := func(ipNet *net.IPNet) []byte {
1285 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1286 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1287 ipAndMask = append(ipAndMask, maskedIP...)
1288 ipAndMask = append(ipAndMask, ipNet.Mask...)
1289 return ipAndMask
1290 }
1291
1292 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1293 var b cryptobyte.Builder
1294
1295 for _, name := range dns {
1296 if err = isIA5String(name); err != nil {
1297 return nil, err
1298 }
1299
1300 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1301 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1302 b.AddBytes([]byte(name))
1303 })
1304 })
1305 }
1306
1307 for _, ipNet := range ips {
1308 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1309 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1310 b.AddBytes(ipAndMask(ipNet))
1311 })
1312 })
1313 }
1314
1315 for _, email := range emails {
1316 if err = isIA5String(email); err != nil {
1317 return nil, err
1318 }
1319
1320 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1321 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1322 b.AddBytes([]byte(email))
1323 })
1324 })
1325 }
1326
1327 for _, uriDomain := range uriDomains {
1328 if err = isIA5String(uriDomain); err != nil {
1329 return nil, err
1330 }
1331
1332 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1333 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1334 b.AddBytes([]byte(uriDomain))
1335 })
1336 })
1337 }
1338
1339 return b.Bytes()
1340 }
1341
1342 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1343 if err != nil {
1344 return nil, err
1345 }
1346
1347 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1348 if err != nil {
1349 return nil, err
1350 }
1351
1352 var b cryptobyte.Builder
1353 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1354 if len(permitted) > 0 {
1355 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1356 b.AddBytes(permitted)
1357 })
1358 }
1359
1360 if len(excluded) > 0 {
1361 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1362 b.AddBytes(excluded)
1363 })
1364 }
1365 })
1366
1367 ret[n].Value, err = b.Bytes()
1368 if err != nil {
1369 return nil, err
1370 }
1371 n++
1372 }
1373
1374 if len(template.CRLDistributionPoints) > 0 &&
1375 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1376 ret[n].Id = oidExtensionCRLDistributionPoints
1377
1378 var crlDp []distributionPoint
1379 for _, name := range template.CRLDistributionPoints {
1380 dp := distributionPoint{
1381 DistributionPoint: distributionPointName{
1382 FullName: []asn1.RawValue{
1383 {Tag: 6, Class: 2, Bytes: []byte(name)},
1384 },
1385 },
1386 }
1387 crlDp = append(crlDp, dp)
1388 }
1389
1390 ret[n].Value, err = asn1.Marshal(crlDp)
1391 if err != nil {
1392 return
1393 }
1394 n++
1395 }
1396
1397
1398
1399
1400
1401 return append(ret[:n], template.ExtraExtensions...), nil
1402 }
1403
1404 func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
1405 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
1406
1407 var a [2]byte
1408 a[0] = reverseBitsInAByte(byte(ku))
1409 a[1] = reverseBitsInAByte(byte(ku >> 8))
1410
1411 l := 1
1412 if a[1] != 0 {
1413 l = 2
1414 }
1415
1416 bitString := a[:l]
1417 var err error
1418 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1419 return ext, err
1420 }
1421
1422 func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
1423 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
1424
1425 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
1426 for i, u := range extUsages {
1427 if oid, ok := oidFromExtKeyUsage(u); ok {
1428 oids[i] = oid
1429 } else {
1430 return ext, errors.New("x509: unknown extended key usage")
1431 }
1432 }
1433
1434 copy(oids[len(extUsages):], unknownUsages)
1435
1436 var err error
1437 ext.Value, err = asn1.Marshal(oids)
1438 return ext, err
1439 }
1440
1441 func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
1442 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
1443
1444
1445
1446 if maxPathLen == 0 && !maxPathLenZero {
1447 maxPathLen = -1
1448 }
1449 var err error
1450 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
1451 return ext, err
1452 }
1453
1454 func marshalCertificatePolicies(policies []OID, policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
1455 ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
1456
1457 b := cryptobyte.NewBuilder(make([]byte, 0, 128))
1458 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1459 if x509usepolicies.Value() != "0" {
1460 x509usepolicies.IncNonDefault()
1461 for _, v := range policies {
1462 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1463 child.AddASN1(cryptobyte_asn1.OBJECT_IDENTIFIER, func(child *cryptobyte.Builder) {
1464 if len(v.der) == 0 {
1465 child.SetError(errors.New("invalid policy object identifier"))
1466 return
1467 }
1468 child.AddBytes(v.der)
1469 })
1470 })
1471 }
1472 } else {
1473 for _, v := range policyIdentifiers {
1474 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1475 child.AddASN1ObjectIdentifier(v)
1476 })
1477 }
1478 }
1479 })
1480
1481 var err error
1482 ext.Value, err = b.Bytes()
1483 return ext, err
1484 }
1485
1486 func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
1487 var ret []pkix.Extension
1488
1489 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1490 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1491 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1492 if err != nil {
1493 return nil, err
1494 }
1495
1496 ret = append(ret, pkix.Extension{
1497 Id: oidExtensionSubjectAltName,
1498 Value: sanBytes,
1499 })
1500 }
1501
1502 return append(ret, template.ExtraExtensions...), nil
1503 }
1504
1505 func subjectBytes(cert *Certificate) ([]byte, error) {
1506 if len(cert.RawSubject) > 0 {
1507 return cert.RawSubject, nil
1508 }
1509
1510 return asn1.Marshal(cert.Subject.ToRDNSequence())
1511 }
1512
1513
1514
1515
1516 func signingParamsForKey(key crypto.Signer, sigAlgo SignatureAlgorithm) (SignatureAlgorithm, pkix.AlgorithmIdentifier, error) {
1517 var ai pkix.AlgorithmIdentifier
1518 var pubType PublicKeyAlgorithm
1519 var defaultAlgo SignatureAlgorithm
1520
1521 switch pub := key.Public().(type) {
1522 case *rsa.PublicKey:
1523 pubType = RSA
1524 defaultAlgo = SHA256WithRSA
1525
1526 case *ecdsa.PublicKey:
1527 pubType = ECDSA
1528 switch pub.Curve {
1529 case elliptic.P224(), elliptic.P256():
1530 defaultAlgo = ECDSAWithSHA256
1531 case elliptic.P384():
1532 defaultAlgo = ECDSAWithSHA384
1533 case elliptic.P521():
1534 defaultAlgo = ECDSAWithSHA512
1535 default:
1536 return 0, ai, errors.New("x509: unsupported elliptic curve")
1537 }
1538
1539 case ed25519.PublicKey:
1540 pubType = Ed25519
1541 defaultAlgo = PureEd25519
1542
1543 default:
1544 return 0, ai, errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
1545 }
1546
1547 if sigAlgo == 0 {
1548 sigAlgo = defaultAlgo
1549 }
1550
1551 for _, details := range signatureAlgorithmDetails {
1552 if details.algo == sigAlgo {
1553 if details.pubKeyAlgo != pubType {
1554 return 0, ai, errors.New("x509: requested SignatureAlgorithm does not match private key type")
1555 }
1556 if details.hash == crypto.MD5 {
1557 return 0, ai, errors.New("x509: signing with MD5 is not supported")
1558 }
1559
1560 return sigAlgo, pkix.AlgorithmIdentifier{
1561 Algorithm: details.oid,
1562 Parameters: details.params,
1563 }, nil
1564 }
1565 }
1566
1567 return 0, ai, errors.New("x509: unknown SignatureAlgorithm")
1568 }
1569
1570 func signTBS(tbs []byte, key crypto.Signer, sigAlg SignatureAlgorithm, rand io.Reader) ([]byte, error) {
1571 signed := tbs
1572 hashFunc := sigAlg.hashFunc()
1573 if hashFunc != 0 {
1574 h := hashFunc.New()
1575 h.Write(signed)
1576 signed = h.Sum(nil)
1577 }
1578
1579 var signerOpts crypto.SignerOpts = hashFunc
1580 if sigAlg.isRSAPSS() {
1581 signerOpts = &rsa.PSSOptions{
1582 SaltLength: rsa.PSSSaltLengthEqualsHash,
1583 Hash: hashFunc,
1584 }
1585 }
1586
1587 signature, err := key.Sign(rand, signed, signerOpts)
1588 if err != nil {
1589 return nil, err
1590 }
1591
1592
1593 if err := checkSignature(sigAlg, tbs, signature, key.Public(), true); err != nil {
1594 return nil, fmt.Errorf("x509: signature returned by signer is invalid: %w", err)
1595 }
1596
1597 return signature, nil
1598 }
1599
1600
1601
1602 var emptyASN1Subject = []byte{0x30, 0}
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) {
1668 key, ok := priv.(crypto.Signer)
1669 if !ok {
1670 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1671 }
1672
1673 serialNumber := template.SerialNumber
1674 if serialNumber == nil {
1675
1676
1677
1678 serialBytes := make([]byte, 20)
1679 if _, err := io.ReadFull(rand, serialBytes); err != nil {
1680 return nil, err
1681 }
1682
1683
1684
1685
1686 serialBytes[0] &= 0b0111_1111
1687 serialNumber = new(big.Int).SetBytes(serialBytes)
1688 }
1689
1690
1691
1692
1693
1694
1695 if serialNumber.Sign() == -1 {
1696 return nil, errors.New("x509: serial number must be positive")
1697 }
1698
1699 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
1700 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
1701 }
1702
1703 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
1704 if err != nil {
1705 return nil, err
1706 }
1707
1708 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1709 if err != nil {
1710 return nil, err
1711 }
1712 if getPublicKeyAlgorithmFromOID(publicKeyAlgorithm.Algorithm) == UnknownPublicKeyAlgorithm {
1713 return nil, fmt.Errorf("x509: unsupported public key type: %T", pub)
1714 }
1715
1716 asn1Issuer, err := subjectBytes(parent)
1717 if err != nil {
1718 return nil, err
1719 }
1720
1721 asn1Subject, err := subjectBytes(template)
1722 if err != nil {
1723 return nil, err
1724 }
1725
1726 authorityKeyId := template.AuthorityKeyId
1727 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1728 authorityKeyId = parent.SubjectKeyId
1729 }
1730
1731 subjectKeyId := template.SubjectKeyId
1732 if len(subjectKeyId) == 0 && template.IsCA {
1733
1734
1735
1736
1737 h := sha1.Sum(publicKeyBytes)
1738 subjectKeyId = h[:]
1739 }
1740
1741
1742 type privateKey interface {
1743 Equal(crypto.PublicKey) bool
1744 }
1745 if privPub, ok := key.Public().(privateKey); !ok {
1746 return nil, errors.New("x509: internal error: supported public key does not implement Equal")
1747 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
1748 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
1749 }
1750
1751 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
1752 if err != nil {
1753 return nil, err
1754 }
1755
1756 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1757 c := tbsCertificate{
1758 Version: 2,
1759 SerialNumber: serialNumber,
1760 SignatureAlgorithm: algorithmIdentifier,
1761 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1762 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1763 Subject: asn1.RawValue{FullBytes: asn1Subject},
1764 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1765 Extensions: extensions,
1766 }
1767
1768 tbsCertContents, err := asn1.Marshal(c)
1769 if err != nil {
1770 return nil, err
1771 }
1772 c.Raw = tbsCertContents
1773
1774 signature, err := signTBS(tbsCertContents, key, signatureAlgorithm, rand)
1775 if err != nil {
1776 return nil, err
1777 }
1778
1779 return asn1.Marshal(certificate{
1780 TBSCertificate: c,
1781 SignatureAlgorithm: algorithmIdentifier,
1782 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1783 })
1784 }
1785
1786
1787
1788 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1789
1790
1791 var pemType = "X509 CRL"
1792
1793
1794
1795
1796
1797
1798
1799 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1800 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1801 block, _ := pem.Decode(crlBytes)
1802 if block != nil && block.Type == pemType {
1803 crlBytes = block.Bytes
1804 }
1805 }
1806 return ParseDERCRL(crlBytes)
1807 }
1808
1809
1810
1811
1812 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1813 certList := new(pkix.CertificateList)
1814 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
1815 return nil, err
1816 } else if len(rest) != 0 {
1817 return nil, errors.New("x509: trailing data after CRL")
1818 }
1819 return certList, nil
1820 }
1821
1822
1823
1824
1825
1826
1827 func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1828 key, ok := priv.(crypto.Signer)
1829 if !ok {
1830 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1831 }
1832
1833 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, 0)
1834 if err != nil {
1835 return nil, err
1836 }
1837
1838
1839 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
1840 for i, rc := range revokedCerts {
1841 rc.RevocationTime = rc.RevocationTime.UTC()
1842 revokedCertsUTC[i] = rc
1843 }
1844
1845 tbsCertList := pkix.TBSCertificateList{
1846 Version: 1,
1847 Signature: algorithmIdentifier,
1848 Issuer: c.Subject.ToRDNSequence(),
1849 ThisUpdate: now.UTC(),
1850 NextUpdate: expiry.UTC(),
1851 RevokedCertificates: revokedCertsUTC,
1852 }
1853
1854
1855 if len(c.SubjectKeyId) > 0 {
1856 var aki pkix.Extension
1857 aki.Id = oidExtensionAuthorityKeyId
1858 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
1859 if err != nil {
1860 return nil, err
1861 }
1862 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
1863 }
1864
1865 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1866 if err != nil {
1867 return nil, err
1868 }
1869 tbsCertList.Raw = tbsCertListContents
1870
1871 signature, err := signTBS(tbsCertListContents, key, signatureAlgorithm, rand)
1872 if err != nil {
1873 return nil, err
1874 }
1875
1876 return asn1.Marshal(pkix.CertificateList{
1877 TBSCertList: tbsCertList,
1878 SignatureAlgorithm: algorithmIdentifier,
1879 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1880 })
1881 }
1882
1883
1884 type CertificateRequest struct {
1885 Raw []byte
1886 RawTBSCertificateRequest []byte
1887 RawSubjectPublicKeyInfo []byte
1888 RawSubject []byte
1889
1890 Version int
1891 Signature []byte
1892 SignatureAlgorithm SignatureAlgorithm
1893
1894 PublicKeyAlgorithm PublicKeyAlgorithm
1895 PublicKey any
1896
1897 Subject pkix.Name
1898
1899
1900
1901
1902
1903
1904 Attributes []pkix.AttributeTypeAndValueSET
1905
1906
1907
1908
1909 Extensions []pkix.Extension
1910
1911
1912
1913
1914
1915
1916
1917
1918 ExtraExtensions []pkix.Extension
1919
1920
1921 DNSNames []string
1922 EmailAddresses []string
1923 IPAddresses []net.IP
1924 URIs []*url.URL
1925 }
1926
1927
1928
1929
1930 type tbsCertificateRequest struct {
1931 Raw asn1.RawContent
1932 Version int
1933 Subject asn1.RawValue
1934 PublicKey publicKeyInfo
1935 RawAttributes []asn1.RawValue `asn1:"tag:0"`
1936 }
1937
1938 type certificateRequest struct {
1939 Raw asn1.RawContent
1940 TBSCSR tbsCertificateRequest
1941 SignatureAlgorithm pkix.AlgorithmIdentifier
1942 SignatureValue asn1.BitString
1943 }
1944
1945
1946
1947 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
1948
1949
1950
1951 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
1952 var rawAttributes []asn1.RawValue
1953 b, err := asn1.Marshal(attributes)
1954 if err != nil {
1955 return nil, err
1956 }
1957 rest, err := asn1.Unmarshal(b, &rawAttributes)
1958 if err != nil {
1959 return nil, err
1960 }
1961 if len(rest) != 0 {
1962 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
1963 }
1964 return rawAttributes, nil
1965 }
1966
1967
1968 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
1969 var attributes []pkix.AttributeTypeAndValueSET
1970 for _, rawAttr := range rawAttributes {
1971 var attr pkix.AttributeTypeAndValueSET
1972 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
1973
1974
1975 if err == nil && len(rest) == 0 {
1976 attributes = append(attributes, attr)
1977 }
1978 }
1979 return attributes
1980 }
1981
1982
1983
1984 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
1985
1986 type pkcs10Attribute struct {
1987 Id asn1.ObjectIdentifier
1988 Values []asn1.RawValue `asn1:"set"`
1989 }
1990
1991 var ret []pkix.Extension
1992 requestedExts := make(map[string]bool)
1993 for _, rawAttr := range rawAttributes {
1994 var attr pkcs10Attribute
1995 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
1996
1997 continue
1998 }
1999
2000 if !attr.Id.Equal(oidExtensionRequest) {
2001 continue
2002 }
2003
2004 var extensions []pkix.Extension
2005 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2006 return nil, err
2007 }
2008 for _, ext := range extensions {
2009 oidStr := ext.Id.String()
2010 if requestedExts[oidStr] {
2011 return nil, errors.New("x509: certificate request contains duplicate requested extensions")
2012 }
2013 requestedExts[oidStr] = true
2014 }
2015 ret = append(ret, extensions...)
2016 }
2017
2018 return ret, nil
2019 }
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error) {
2041 key, ok := priv.(crypto.Signer)
2042 if !ok {
2043 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2044 }
2045
2046 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
2047 if err != nil {
2048 return nil, err
2049 }
2050
2051 var publicKeyBytes []byte
2052 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2053 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2054 if err != nil {
2055 return nil, err
2056 }
2057
2058 extensions, err := buildCSRExtensions(template)
2059 if err != nil {
2060 return nil, err
2061 }
2062
2063
2064 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2065 for _, attr := range template.Attributes {
2066 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2067 copy(values, attr.Value)
2068 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2069 Type: attr.Type,
2070 Value: values,
2071 })
2072 }
2073
2074 extensionsAppended := false
2075 if len(extensions) > 0 {
2076
2077 for _, atvSet := range attributes {
2078 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2079 continue
2080 }
2081
2082
2083
2084 specifiedExtensions := make(map[string]bool)
2085
2086 for _, atvs := range atvSet.Value {
2087 for _, atv := range atvs {
2088 specifiedExtensions[atv.Type.String()] = true
2089 }
2090 }
2091
2092 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2093 newValue = append(newValue, atvSet.Value[0]...)
2094
2095 for _, e := range extensions {
2096 if specifiedExtensions[e.Id.String()] {
2097
2098
2099 continue
2100 }
2101
2102 newValue = append(newValue, pkix.AttributeTypeAndValue{
2103
2104
2105 Type: e.Id,
2106 Value: e.Value,
2107 })
2108 }
2109
2110 atvSet.Value[0] = newValue
2111 extensionsAppended = true
2112 break
2113 }
2114 }
2115
2116 rawAttributes, err := newRawAttributes(attributes)
2117 if err != nil {
2118 return nil, err
2119 }
2120
2121
2122
2123 if len(extensions) > 0 && !extensionsAppended {
2124 attr := struct {
2125 Type asn1.ObjectIdentifier
2126 Value [][]pkix.Extension `asn1:"set"`
2127 }{
2128 Type: oidExtensionRequest,
2129 Value: [][]pkix.Extension{extensions},
2130 }
2131
2132 b, err := asn1.Marshal(attr)
2133 if err != nil {
2134 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2135 }
2136
2137 var rawValue asn1.RawValue
2138 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2139 return nil, err
2140 }
2141
2142 rawAttributes = append(rawAttributes, rawValue)
2143 }
2144
2145 asn1Subject := template.RawSubject
2146 if len(asn1Subject) == 0 {
2147 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2148 if err != nil {
2149 return nil, err
2150 }
2151 }
2152
2153 tbsCSR := tbsCertificateRequest{
2154 Version: 0,
2155 Subject: asn1.RawValue{FullBytes: asn1Subject},
2156 PublicKey: publicKeyInfo{
2157 Algorithm: publicKeyAlgorithm,
2158 PublicKey: asn1.BitString{
2159 Bytes: publicKeyBytes,
2160 BitLength: len(publicKeyBytes) * 8,
2161 },
2162 },
2163 RawAttributes: rawAttributes,
2164 }
2165
2166 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2167 if err != nil {
2168 return nil, err
2169 }
2170 tbsCSR.Raw = tbsCSRContents
2171
2172 signature, err := signTBS(tbsCSRContents, key, signatureAlgorithm, rand)
2173 if err != nil {
2174 return nil, err
2175 }
2176
2177 return asn1.Marshal(certificateRequest{
2178 TBSCSR: tbsCSR,
2179 SignatureAlgorithm: algorithmIdentifier,
2180 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2181 })
2182 }
2183
2184
2185
2186 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2187 var csr certificateRequest
2188
2189 rest, err := asn1.Unmarshal(asn1Data, &csr)
2190 if err != nil {
2191 return nil, err
2192 } else if len(rest) != 0 {
2193 return nil, asn1.SyntaxError{Msg: "trailing data"}
2194 }
2195
2196 return parseCertificateRequest(&csr)
2197 }
2198
2199 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2200 out := &CertificateRequest{
2201 Raw: in.Raw,
2202 RawTBSCertificateRequest: in.TBSCSR.Raw,
2203 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2204 RawSubject: in.TBSCSR.Subject.FullBytes,
2205
2206 Signature: in.SignatureValue.RightAlign(),
2207 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2208
2209 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2210
2211 Version: in.TBSCSR.Version,
2212 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2213 }
2214
2215 var err error
2216 if out.PublicKeyAlgorithm != UnknownPublicKeyAlgorithm {
2217 out.PublicKey, err = parsePublicKey(&in.TBSCSR.PublicKey)
2218 if err != nil {
2219 return nil, err
2220 }
2221 }
2222
2223 var subject pkix.RDNSequence
2224 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2225 return nil, err
2226 } else if len(rest) != 0 {
2227 return nil, errors.New("x509: trailing data after X.509 Subject")
2228 }
2229
2230 out.Subject.FillFromRDNSequence(&subject)
2231
2232 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2233 return nil, err
2234 }
2235
2236 for _, extension := range out.Extensions {
2237 switch {
2238 case extension.Id.Equal(oidExtensionSubjectAltName):
2239 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2240 if err != nil {
2241 return nil, err
2242 }
2243 }
2244 }
2245
2246 return out, nil
2247 }
2248
2249
2250 func (c *CertificateRequest) CheckSignature() error {
2251 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey, true)
2252 }
2253
2254
2255
2256 type RevocationListEntry struct {
2257
2258
2259 Raw []byte
2260
2261
2262
2263
2264 SerialNumber *big.Int
2265
2266
2267
2268 RevocationTime time.Time
2269
2270
2271
2272
2273
2274
2275
2276
2277 ReasonCode int
2278
2279
2280
2281
2282
2283 Extensions []pkix.Extension
2284
2285
2286
2287
2288 ExtraExtensions []pkix.Extension
2289 }
2290
2291
2292
2293 type RevocationList struct {
2294
2295
2296 Raw []byte
2297
2298
2299 RawTBSRevocationList []byte
2300
2301 RawIssuer []byte
2302
2303
2304 Issuer pkix.Name
2305
2306
2307
2308
2309 AuthorityKeyId []byte
2310
2311 Signature []byte
2312
2313
2314
2315 SignatureAlgorithm SignatureAlgorithm
2316
2317
2318
2319
2320
2321 RevokedCertificateEntries []RevocationListEntry
2322
2323
2324
2325
2326
2327
2328 RevokedCertificates []pkix.RevokedCertificate
2329
2330
2331
2332
2333
2334 Number *big.Int
2335
2336
2337
2338 ThisUpdate time.Time
2339
2340
2341
2342 NextUpdate time.Time
2343
2344
2345
2346 Extensions []pkix.Extension
2347
2348
2349
2350 ExtraExtensions []pkix.Extension
2351 }
2352
2353
2354
2355
2356
2357
2358
2359 type certificateList struct {
2360 TBSCertList tbsCertificateList
2361 SignatureAlgorithm pkix.AlgorithmIdentifier
2362 SignatureValue asn1.BitString
2363 }
2364
2365 type tbsCertificateList struct {
2366 Raw asn1.RawContent
2367 Version int `asn1:"optional,default:0"`
2368 Signature pkix.AlgorithmIdentifier
2369 Issuer asn1.RawValue
2370 ThisUpdate time.Time
2371 NextUpdate time.Time `asn1:"optional"`
2372 RevokedCertificates []pkix.RevokedCertificate `asn1:"optional"`
2373 Extensions []pkix.Extension `asn1:"tag:0,optional,explicit"`
2374 }
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2389 if template == nil {
2390 return nil, errors.New("x509: template can not be nil")
2391 }
2392 if issuer == nil {
2393 return nil, errors.New("x509: issuer can not be nil")
2394 }
2395 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2396 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2397 }
2398 if len(issuer.SubjectKeyId) == 0 {
2399 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2400 }
2401 if template.NextUpdate.Before(template.ThisUpdate) {
2402 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2403 }
2404 if template.Number == nil {
2405 return nil, errors.New("x509: template contains nil Number field")
2406 }
2407
2408 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(priv, template.SignatureAlgorithm)
2409 if err != nil {
2410 return nil, err
2411 }
2412
2413 var revokedCerts []pkix.RevokedCertificate
2414
2415
2416 if len(template.RevokedCertificates) > 0 && len(template.RevokedCertificateEntries) == 0 {
2417
2418 revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2419 for i, rc := range template.RevokedCertificates {
2420 rc.RevocationTime = rc.RevocationTime.UTC()
2421 revokedCerts[i] = rc
2422 }
2423 } else {
2424
2425
2426 revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificateEntries))
2427 for i, rce := range template.RevokedCertificateEntries {
2428 if rce.SerialNumber == nil {
2429 return nil, errors.New("x509: template contains entry with nil SerialNumber field")
2430 }
2431 if rce.RevocationTime.IsZero() {
2432 return nil, errors.New("x509: template contains entry with zero RevocationTime field")
2433 }
2434
2435 rc := pkix.RevokedCertificate{
2436 SerialNumber: rce.SerialNumber,
2437 RevocationTime: rce.RevocationTime.UTC(),
2438 }
2439
2440
2441
2442 exts := make([]pkix.Extension, 0, len(rce.ExtraExtensions))
2443 for _, ext := range rce.ExtraExtensions {
2444 if ext.Id.Equal(oidExtensionReasonCode) {
2445 return nil, errors.New("x509: template contains entry with ReasonCode ExtraExtension; use ReasonCode field instead")
2446 }
2447 exts = append(exts, ext)
2448 }
2449
2450
2451
2452 if rce.ReasonCode != 0 {
2453 reasonBytes, err := asn1.Marshal(asn1.Enumerated(rce.ReasonCode))
2454 if err != nil {
2455 return nil, err
2456 }
2457
2458 exts = append(exts, pkix.Extension{
2459 Id: oidExtensionReasonCode,
2460 Value: reasonBytes,
2461 })
2462 }
2463
2464 if len(exts) > 0 {
2465 rc.Extensions = exts
2466 }
2467 revokedCerts[i] = rc
2468 }
2469 }
2470
2471 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2472 if err != nil {
2473 return nil, err
2474 }
2475
2476 if numBytes := template.Number.Bytes(); len(numBytes) > 20 || (len(numBytes) == 20 && numBytes[0]&0x80 != 0) {
2477 return nil, errors.New("x509: CRL number exceeds 20 octets")
2478 }
2479 crlNum, err := asn1.Marshal(template.Number)
2480 if err != nil {
2481 return nil, err
2482 }
2483
2484
2485 issuerSubject, err := subjectBytes(issuer)
2486 if err != nil {
2487 return nil, err
2488 }
2489
2490 tbsCertList := tbsCertificateList{
2491 Version: 1,
2492 Signature: algorithmIdentifier,
2493 Issuer: asn1.RawValue{FullBytes: issuerSubject},
2494 ThisUpdate: template.ThisUpdate.UTC(),
2495 NextUpdate: template.NextUpdate.UTC(),
2496 Extensions: []pkix.Extension{
2497 {
2498 Id: oidExtensionAuthorityKeyId,
2499 Value: aki,
2500 },
2501 {
2502 Id: oidExtensionCRLNumber,
2503 Value: crlNum,
2504 },
2505 },
2506 }
2507 if len(revokedCerts) > 0 {
2508 tbsCertList.RevokedCertificates = revokedCerts
2509 }
2510
2511 if len(template.ExtraExtensions) > 0 {
2512 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2513 }
2514
2515 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2516 if err != nil {
2517 return nil, err
2518 }
2519
2520
2521
2522 tbsCertList.Raw = tbsCertListContents
2523
2524 signature, err := signTBS(tbsCertListContents, priv, signatureAlgorithm, rand)
2525 if err != nil {
2526 return nil, err
2527 }
2528
2529 return asn1.Marshal(certificateList{
2530 TBSCertList: tbsCertList,
2531 SignatureAlgorithm: algorithmIdentifier,
2532 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2533 })
2534 }
2535
2536
2537
2538 func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error {
2539 if parent.Version == 3 && !parent.BasicConstraintsValid ||
2540 parent.BasicConstraintsValid && !parent.IsCA {
2541 return ConstraintViolationError{}
2542 }
2543
2544 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCRLSign == 0 {
2545 return ConstraintViolationError{}
2546 }
2547
2548 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
2549 return ErrUnsupportedAlgorithm
2550 }
2551
2552 return parent.CheckSignature(rl.SignatureAlgorithm, rl.RawTBSRevocationList, rl.Signature)
2553 }
2554
View as plain text