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 PolicyIdentifiers []asn1.ObjectIdentifier
790
791
792
793 Policies []OID
794 }
795
796
797
798 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
799
800
801
802
803
804
805
806 type InsecureAlgorithmError SignatureAlgorithm
807
808 func (e InsecureAlgorithmError) Error() string {
809 var override string
810 if SignatureAlgorithm(e) == SHA1WithRSA || SignatureAlgorithm(e) == ECDSAWithSHA1 {
811 override = " (temporarily override with GODEBUG=x509sha1=1)"
812 }
813 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e)) + override
814 }
815
816
817
818
819 type ConstraintViolationError struct{}
820
821 func (ConstraintViolationError) Error() string {
822 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
823 }
824
825 func (c *Certificate) Equal(other *Certificate) bool {
826 if c == nil || other == nil {
827 return c == other
828 }
829 return bytes.Equal(c.Raw, other.Raw)
830 }
831
832 func (c *Certificate) hasSANExtension() bool {
833 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
834 }
835
836
837
838
839
840 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
841
842
843
844
845
846 if parent.Version == 3 && !parent.BasicConstraintsValid ||
847 parent.BasicConstraintsValid && !parent.IsCA {
848 return ConstraintViolationError{}
849 }
850
851 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
852 return ConstraintViolationError{}
853 }
854
855 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
856 return ErrUnsupportedAlgorithm
857 }
858
859 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature, parent.PublicKey, false)
860 }
861
862
863
864
865
866
867
868
869 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
870 return checkSignature(algo, signed, signature, c.PublicKey, true)
871 }
872
873 func (c *Certificate) hasNameConstraints() bool {
874 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
875 }
876
877 func (c *Certificate) getSANExtension() []byte {
878 for _, e := range c.Extensions {
879 if e.Id.Equal(oidExtensionSubjectAltName) {
880 return e.Value
881 }
882 }
883 return nil
884 }
885
886 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {
887 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
888 }
889
890 var x509sha1 = godebug.New("x509sha1")
891
892
893
894 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error) {
895 var hashType crypto.Hash
896 var pubKeyAlgo PublicKeyAlgorithm
897
898 for _, details := range signatureAlgorithmDetails {
899 if details.algo == algo {
900 hashType = details.hash
901 pubKeyAlgo = details.pubKeyAlgo
902 break
903 }
904 }
905
906 switch hashType {
907 case crypto.Hash(0):
908 if pubKeyAlgo != Ed25519 {
909 return ErrUnsupportedAlgorithm
910 }
911 case crypto.MD5:
912 return InsecureAlgorithmError(algo)
913 case crypto.SHA1:
914
915 if !allowSHA1 {
916 if x509sha1.Value() != "1" {
917 return InsecureAlgorithmError(algo)
918 }
919 x509sha1.IncNonDefault()
920 }
921 fallthrough
922 default:
923 if !hashType.Available() {
924 return ErrUnsupportedAlgorithm
925 }
926 h := hashType.New()
927 h.Write(signed)
928 signed = h.Sum(nil)
929 }
930
931 switch pub := publicKey.(type) {
932 case *rsa.PublicKey:
933 if pubKeyAlgo != RSA {
934 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
935 }
936 if algo.isRSAPSS() {
937 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
938 } else {
939 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
940 }
941 case *ecdsa.PublicKey:
942 if pubKeyAlgo != ECDSA {
943 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
944 }
945 if !ecdsa.VerifyASN1(pub, signed, signature) {
946 return errors.New("x509: ECDSA verification failure")
947 }
948 return
949 case ed25519.PublicKey:
950 if pubKeyAlgo != Ed25519 {
951 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
952 }
953 if !ed25519.Verify(pub, signed, signature) {
954 return errors.New("x509: Ed25519 verification failure")
955 }
956 return
957 }
958 return ErrUnsupportedAlgorithm
959 }
960
961
962
963
964 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
965 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
966 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
967 }
968
969 type UnhandledCriticalExtension struct{}
970
971 func (h UnhandledCriticalExtension) Error() string {
972 return "x509: unhandled critical extension"
973 }
974
975 type basicConstraints struct {
976 IsCA bool `asn1:"optional"`
977 MaxPathLen int `asn1:"optional,default:-1"`
978 }
979
980
981 type policyInformation struct {
982 Policy asn1.ObjectIdentifier
983
984 }
985
986 const (
987 nameTypeEmail = 1
988 nameTypeDNS = 2
989 nameTypeURI = 6
990 nameTypeIP = 7
991 )
992
993
994 type authorityInfoAccess struct {
995 Method asn1.ObjectIdentifier
996 Location asn1.RawValue
997 }
998
999
1000 type distributionPoint struct {
1001 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
1002 Reason asn1.BitString `asn1:"optional,tag:1"`
1003 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
1004 }
1005
1006 type distributionPointName struct {
1007 FullName []asn1.RawValue `asn1:"optional,tag:0"`
1008 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
1009 }
1010
1011 func reverseBitsInAByte(in byte) byte {
1012 b1 := in>>4 | in<<4
1013 b2 := b1>>2&0x33 | b1<<2&0xcc
1014 b3 := b2>>1&0x55 | b2<<1&0xaa
1015 return b3
1016 }
1017
1018
1019
1020
1021 func asn1BitLength(bitString []byte) int {
1022 bitLen := len(bitString) * 8
1023
1024 for i := range bitString {
1025 b := bitString[len(bitString)-i-1]
1026
1027 for bit := uint(0); bit < 8; bit++ {
1028 if (b>>bit)&1 == 1 {
1029 return bitLen
1030 }
1031 bitLen--
1032 }
1033 }
1034
1035 return 0
1036 }
1037
1038 var (
1039 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1040 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1041 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1042 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1043 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1044 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1045 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1046 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1047 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1048 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1049 oidExtensionCRLNumber = []int{2, 5, 29, 20}
1050 oidExtensionReasonCode = []int{2, 5, 29, 21}
1051 )
1052
1053 var (
1054 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1055 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1056 )
1057
1058
1059
1060 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1061 for _, e := range extensions {
1062 if e.Id.Equal(oid) {
1063 return true
1064 }
1065 }
1066 return false
1067 }
1068
1069
1070
1071 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1072 var rawValues []asn1.RawValue
1073 for _, name := range dnsNames {
1074 if err := isIA5String(name); err != nil {
1075 return nil, err
1076 }
1077 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1078 }
1079 for _, email := range emailAddresses {
1080 if err := isIA5String(email); err != nil {
1081 return nil, err
1082 }
1083 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1084 }
1085 for _, rawIP := range ipAddresses {
1086
1087 ip := rawIP.To4()
1088 if ip == nil {
1089 ip = rawIP
1090 }
1091 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1092 }
1093 for _, uri := range uris {
1094 uriStr := uri.String()
1095 if err := isIA5String(uriStr); err != nil {
1096 return nil, err
1097 }
1098 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1099 }
1100 return asn1.Marshal(rawValues)
1101 }
1102
1103 func isIA5String(s string) error {
1104 for _, r := range s {
1105
1106 if r > unicode.MaxASCII {
1107 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1108 }
1109 }
1110
1111 return nil
1112 }
1113
1114 var x509usepolicies = godebug.New("x509usepolicies")
1115
1116 func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1117 ret = make([]pkix.Extension, 10 )
1118 n := 0
1119
1120 if template.KeyUsage != 0 &&
1121 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1122 ret[n], err = marshalKeyUsage(template.KeyUsage)
1123 if err != nil {
1124 return nil, err
1125 }
1126 n++
1127 }
1128
1129 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1130 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1131 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
1132 if err != nil {
1133 return nil, err
1134 }
1135 n++
1136 }
1137
1138 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1139 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
1140 if err != nil {
1141 return nil, err
1142 }
1143 n++
1144 }
1145
1146 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1147 ret[n].Id = oidExtensionSubjectKeyId
1148 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1149 if err != nil {
1150 return
1151 }
1152 n++
1153 }
1154
1155 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1156 ret[n].Id = oidExtensionAuthorityKeyId
1157 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1158 if err != nil {
1159 return
1160 }
1161 n++
1162 }
1163
1164 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1165 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1166 ret[n].Id = oidExtensionAuthorityInfoAccess
1167 var aiaValues []authorityInfoAccess
1168 for _, name := range template.OCSPServer {
1169 aiaValues = append(aiaValues, authorityInfoAccess{
1170 Method: oidAuthorityInfoAccessOcsp,
1171 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1172 })
1173 }
1174 for _, name := range template.IssuingCertificateURL {
1175 aiaValues = append(aiaValues, authorityInfoAccess{
1176 Method: oidAuthorityInfoAccessIssuers,
1177 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1178 })
1179 }
1180 ret[n].Value, err = asn1.Marshal(aiaValues)
1181 if err != nil {
1182 return
1183 }
1184 n++
1185 }
1186
1187 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1188 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1189 ret[n].Id = oidExtensionSubjectAltName
1190
1191
1192
1193 ret[n].Critical = subjectIsEmpty
1194 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1195 if err != nil {
1196 return
1197 }
1198 n++
1199 }
1200
1201 usePolicies := x509usepolicies.Value() == "1"
1202 if ((!usePolicies && len(template.PolicyIdentifiers) > 0) || (usePolicies && len(template.Policies) > 0)) &&
1203 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1204 ret[n], err = marshalCertificatePolicies(template.Policies, template.PolicyIdentifiers)
1205 if err != nil {
1206 return nil, err
1207 }
1208 n++
1209 }
1210
1211 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1212 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1213 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1214 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1215 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1216 ret[n].Id = oidExtensionNameConstraints
1217 ret[n].Critical = template.PermittedDNSDomainsCritical
1218
1219 ipAndMask := func(ipNet *net.IPNet) []byte {
1220 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1221 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1222 ipAndMask = append(ipAndMask, maskedIP...)
1223 ipAndMask = append(ipAndMask, ipNet.Mask...)
1224 return ipAndMask
1225 }
1226
1227 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1228 var b cryptobyte.Builder
1229
1230 for _, name := range dns {
1231 if err = isIA5String(name); err != nil {
1232 return nil, err
1233 }
1234
1235 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1236 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1237 b.AddBytes([]byte(name))
1238 })
1239 })
1240 }
1241
1242 for _, ipNet := range ips {
1243 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1244 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1245 b.AddBytes(ipAndMask(ipNet))
1246 })
1247 })
1248 }
1249
1250 for _, email := range emails {
1251 if err = isIA5String(email); err != nil {
1252 return nil, err
1253 }
1254
1255 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1256 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1257 b.AddBytes([]byte(email))
1258 })
1259 })
1260 }
1261
1262 for _, uriDomain := range uriDomains {
1263 if err = isIA5String(uriDomain); err != nil {
1264 return nil, err
1265 }
1266
1267 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1268 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1269 b.AddBytes([]byte(uriDomain))
1270 })
1271 })
1272 }
1273
1274 return b.Bytes()
1275 }
1276
1277 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1278 if err != nil {
1279 return nil, err
1280 }
1281
1282 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1283 if err != nil {
1284 return nil, err
1285 }
1286
1287 var b cryptobyte.Builder
1288 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1289 if len(permitted) > 0 {
1290 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1291 b.AddBytes(permitted)
1292 })
1293 }
1294
1295 if len(excluded) > 0 {
1296 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1297 b.AddBytes(excluded)
1298 })
1299 }
1300 })
1301
1302 ret[n].Value, err = b.Bytes()
1303 if err != nil {
1304 return nil, err
1305 }
1306 n++
1307 }
1308
1309 if len(template.CRLDistributionPoints) > 0 &&
1310 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1311 ret[n].Id = oidExtensionCRLDistributionPoints
1312
1313 var crlDp []distributionPoint
1314 for _, name := range template.CRLDistributionPoints {
1315 dp := distributionPoint{
1316 DistributionPoint: distributionPointName{
1317 FullName: []asn1.RawValue{
1318 {Tag: 6, Class: 2, Bytes: []byte(name)},
1319 },
1320 },
1321 }
1322 crlDp = append(crlDp, dp)
1323 }
1324
1325 ret[n].Value, err = asn1.Marshal(crlDp)
1326 if err != nil {
1327 return
1328 }
1329 n++
1330 }
1331
1332
1333
1334
1335
1336 return append(ret[:n], template.ExtraExtensions...), nil
1337 }
1338
1339 func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
1340 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
1341
1342 var a [2]byte
1343 a[0] = reverseBitsInAByte(byte(ku))
1344 a[1] = reverseBitsInAByte(byte(ku >> 8))
1345
1346 l := 1
1347 if a[1] != 0 {
1348 l = 2
1349 }
1350
1351 bitString := a[:l]
1352 var err error
1353 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1354 return ext, err
1355 }
1356
1357 func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
1358 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
1359
1360 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
1361 for i, u := range extUsages {
1362 if oid, ok := oidFromExtKeyUsage(u); ok {
1363 oids[i] = oid
1364 } else {
1365 return ext, errors.New("x509: unknown extended key usage")
1366 }
1367 }
1368
1369 copy(oids[len(extUsages):], unknownUsages)
1370
1371 var err error
1372 ext.Value, err = asn1.Marshal(oids)
1373 return ext, err
1374 }
1375
1376 func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
1377 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
1378
1379
1380
1381 if maxPathLen == 0 && !maxPathLenZero {
1382 maxPathLen = -1
1383 }
1384 var err error
1385 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
1386 return ext, err
1387 }
1388
1389 func marshalCertificatePolicies(policies []OID, policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
1390 ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
1391
1392 b := cryptobyte.NewBuilder(make([]byte, 0, 128))
1393 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1394 if x509usepolicies.Value() == "1" {
1395 x509usepolicies.IncNonDefault()
1396 for _, v := range policies {
1397 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1398 child.AddASN1(cryptobyte_asn1.OBJECT_IDENTIFIER, func(child *cryptobyte.Builder) {
1399 if len(v.der) == 0 {
1400 child.SetError(errors.New("invalid policy object identifier"))
1401 return
1402 }
1403 child.AddBytes(v.der)
1404 })
1405 })
1406 }
1407 } else {
1408 for _, v := range policyIdentifiers {
1409 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1410 child.AddASN1ObjectIdentifier(v)
1411 })
1412 }
1413 }
1414 })
1415
1416 var err error
1417 ext.Value, err = b.Bytes()
1418 return ext, err
1419 }
1420
1421 func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
1422 var ret []pkix.Extension
1423
1424 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1425 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1426 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1427 if err != nil {
1428 return nil, err
1429 }
1430
1431 ret = append(ret, pkix.Extension{
1432 Id: oidExtensionSubjectAltName,
1433 Value: sanBytes,
1434 })
1435 }
1436
1437 return append(ret, template.ExtraExtensions...), nil
1438 }
1439
1440 func subjectBytes(cert *Certificate) ([]byte, error) {
1441 if len(cert.RawSubject) > 0 {
1442 return cert.RawSubject, nil
1443 }
1444
1445 return asn1.Marshal(cert.Subject.ToRDNSequence())
1446 }
1447
1448
1449
1450
1451 func signingParamsForKey(key crypto.Signer, sigAlgo SignatureAlgorithm) (SignatureAlgorithm, pkix.AlgorithmIdentifier, error) {
1452 var ai pkix.AlgorithmIdentifier
1453 var pubType PublicKeyAlgorithm
1454 var defaultAlgo SignatureAlgorithm
1455
1456 switch pub := key.Public().(type) {
1457 case *rsa.PublicKey:
1458 pubType = RSA
1459 defaultAlgo = SHA256WithRSA
1460
1461 case *ecdsa.PublicKey:
1462 pubType = ECDSA
1463 switch pub.Curve {
1464 case elliptic.P224(), elliptic.P256():
1465 defaultAlgo = ECDSAWithSHA256
1466 case elliptic.P384():
1467 defaultAlgo = ECDSAWithSHA384
1468 case elliptic.P521():
1469 defaultAlgo = ECDSAWithSHA512
1470 default:
1471 return 0, ai, errors.New("x509: unsupported elliptic curve")
1472 }
1473
1474 case ed25519.PublicKey:
1475 pubType = Ed25519
1476 defaultAlgo = PureEd25519
1477
1478 default:
1479 return 0, ai, errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
1480 }
1481
1482 if sigAlgo == 0 {
1483 sigAlgo = defaultAlgo
1484 }
1485
1486 for _, details := range signatureAlgorithmDetails {
1487 if details.algo == sigAlgo {
1488 if details.pubKeyAlgo != pubType {
1489 return 0, ai, errors.New("x509: requested SignatureAlgorithm does not match private key type")
1490 }
1491 if details.hash == crypto.MD5 {
1492 return 0, ai, errors.New("x509: signing with MD5 is not supported")
1493 }
1494
1495 return sigAlgo, pkix.AlgorithmIdentifier{
1496 Algorithm: details.oid,
1497 Parameters: details.params,
1498 }, nil
1499 }
1500 }
1501
1502 return 0, ai, errors.New("x509: unknown SignatureAlgorithm")
1503 }
1504
1505 func signTBS(tbs []byte, key crypto.Signer, sigAlg SignatureAlgorithm, rand io.Reader) ([]byte, error) {
1506 signed := tbs
1507 hashFunc := sigAlg.hashFunc()
1508 if hashFunc != 0 {
1509 h := hashFunc.New()
1510 h.Write(signed)
1511 signed = h.Sum(nil)
1512 }
1513
1514 var signerOpts crypto.SignerOpts = hashFunc
1515 if sigAlg.isRSAPSS() {
1516 signerOpts = &rsa.PSSOptions{
1517 SaltLength: rsa.PSSSaltLengthEqualsHash,
1518 Hash: hashFunc,
1519 }
1520 }
1521
1522 signature, err := key.Sign(rand, signed, signerOpts)
1523 if err != nil {
1524 return nil, err
1525 }
1526
1527
1528 if err := checkSignature(sigAlg, tbs, signature, key.Public(), true); err != nil {
1529 return nil, fmt.Errorf("x509: signature returned by signer is invalid: %w", err)
1530 }
1531
1532 return signature, nil
1533 }
1534
1535
1536
1537 var emptyASN1Subject = []byte{0x30, 0}
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) {
1600 key, ok := priv.(crypto.Signer)
1601 if !ok {
1602 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1603 }
1604
1605 if template.SerialNumber == nil {
1606 return nil, errors.New("x509: no SerialNumber given")
1607 }
1608
1609
1610
1611
1612
1613
1614 if template.SerialNumber.Sign() == -1 {
1615 return nil, errors.New("x509: serial number must be positive")
1616 }
1617
1618 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
1619 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
1620 }
1621
1622 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
1623 if err != nil {
1624 return nil, err
1625 }
1626
1627 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1628 if err != nil {
1629 return nil, err
1630 }
1631 if getPublicKeyAlgorithmFromOID(publicKeyAlgorithm.Algorithm) == UnknownPublicKeyAlgorithm {
1632 return nil, fmt.Errorf("x509: unsupported public key type: %T", pub)
1633 }
1634
1635 asn1Issuer, err := subjectBytes(parent)
1636 if err != nil {
1637 return nil, err
1638 }
1639
1640 asn1Subject, err := subjectBytes(template)
1641 if err != nil {
1642 return nil, err
1643 }
1644
1645 authorityKeyId := template.AuthorityKeyId
1646 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1647 authorityKeyId = parent.SubjectKeyId
1648 }
1649
1650 subjectKeyId := template.SubjectKeyId
1651 if len(subjectKeyId) == 0 && template.IsCA {
1652
1653
1654
1655
1656 h := sha1.Sum(publicKeyBytes)
1657 subjectKeyId = h[:]
1658 }
1659
1660
1661 type privateKey interface {
1662 Equal(crypto.PublicKey) bool
1663 }
1664 if privPub, ok := key.Public().(privateKey); !ok {
1665 return nil, errors.New("x509: internal error: supported public key does not implement Equal")
1666 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
1667 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
1668 }
1669
1670 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
1671 if err != nil {
1672 return nil, err
1673 }
1674
1675 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1676 c := tbsCertificate{
1677 Version: 2,
1678 SerialNumber: template.SerialNumber,
1679 SignatureAlgorithm: algorithmIdentifier,
1680 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1681 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1682 Subject: asn1.RawValue{FullBytes: asn1Subject},
1683 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1684 Extensions: extensions,
1685 }
1686
1687 tbsCertContents, err := asn1.Marshal(c)
1688 if err != nil {
1689 return nil, err
1690 }
1691 c.Raw = tbsCertContents
1692
1693 signature, err := signTBS(tbsCertContents, key, signatureAlgorithm, rand)
1694 if err != nil {
1695 return nil, err
1696 }
1697
1698 return asn1.Marshal(certificate{
1699 TBSCertificate: c,
1700 SignatureAlgorithm: algorithmIdentifier,
1701 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1702 })
1703 }
1704
1705
1706
1707 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1708
1709
1710 var pemType = "X509 CRL"
1711
1712
1713
1714
1715
1716
1717
1718 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1719 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1720 block, _ := pem.Decode(crlBytes)
1721 if block != nil && block.Type == pemType {
1722 crlBytes = block.Bytes
1723 }
1724 }
1725 return ParseDERCRL(crlBytes)
1726 }
1727
1728
1729
1730
1731 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1732 certList := new(pkix.CertificateList)
1733 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
1734 return nil, err
1735 } else if len(rest) != 0 {
1736 return nil, errors.New("x509: trailing data after CRL")
1737 }
1738 return certList, nil
1739 }
1740
1741
1742
1743
1744
1745
1746 func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1747 key, ok := priv.(crypto.Signer)
1748 if !ok {
1749 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1750 }
1751
1752 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, 0)
1753 if err != nil {
1754 return nil, err
1755 }
1756
1757
1758 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
1759 for i, rc := range revokedCerts {
1760 rc.RevocationTime = rc.RevocationTime.UTC()
1761 revokedCertsUTC[i] = rc
1762 }
1763
1764 tbsCertList := pkix.TBSCertificateList{
1765 Version: 1,
1766 Signature: algorithmIdentifier,
1767 Issuer: c.Subject.ToRDNSequence(),
1768 ThisUpdate: now.UTC(),
1769 NextUpdate: expiry.UTC(),
1770 RevokedCertificates: revokedCertsUTC,
1771 }
1772
1773
1774 if len(c.SubjectKeyId) > 0 {
1775 var aki pkix.Extension
1776 aki.Id = oidExtensionAuthorityKeyId
1777 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
1778 if err != nil {
1779 return nil, err
1780 }
1781 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
1782 }
1783
1784 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1785 if err != nil {
1786 return nil, err
1787 }
1788 tbsCertList.Raw = tbsCertListContents
1789
1790 signature, err := signTBS(tbsCertListContents, key, signatureAlgorithm, rand)
1791 if err != nil {
1792 return nil, err
1793 }
1794
1795 return asn1.Marshal(pkix.CertificateList{
1796 TBSCertList: tbsCertList,
1797 SignatureAlgorithm: algorithmIdentifier,
1798 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1799 })
1800 }
1801
1802
1803 type CertificateRequest struct {
1804 Raw []byte
1805 RawTBSCertificateRequest []byte
1806 RawSubjectPublicKeyInfo []byte
1807 RawSubject []byte
1808
1809 Version int
1810 Signature []byte
1811 SignatureAlgorithm SignatureAlgorithm
1812
1813 PublicKeyAlgorithm PublicKeyAlgorithm
1814 PublicKey any
1815
1816 Subject pkix.Name
1817
1818
1819
1820
1821
1822
1823 Attributes []pkix.AttributeTypeAndValueSET
1824
1825
1826
1827
1828 Extensions []pkix.Extension
1829
1830
1831
1832
1833
1834
1835
1836
1837 ExtraExtensions []pkix.Extension
1838
1839
1840 DNSNames []string
1841 EmailAddresses []string
1842 IPAddresses []net.IP
1843 URIs []*url.URL
1844 }
1845
1846
1847
1848
1849 type tbsCertificateRequest struct {
1850 Raw asn1.RawContent
1851 Version int
1852 Subject asn1.RawValue
1853 PublicKey publicKeyInfo
1854 RawAttributes []asn1.RawValue `asn1:"tag:0"`
1855 }
1856
1857 type certificateRequest struct {
1858 Raw asn1.RawContent
1859 TBSCSR tbsCertificateRequest
1860 SignatureAlgorithm pkix.AlgorithmIdentifier
1861 SignatureValue asn1.BitString
1862 }
1863
1864
1865
1866 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
1867
1868
1869
1870 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
1871 var rawAttributes []asn1.RawValue
1872 b, err := asn1.Marshal(attributes)
1873 if err != nil {
1874 return nil, err
1875 }
1876 rest, err := asn1.Unmarshal(b, &rawAttributes)
1877 if err != nil {
1878 return nil, err
1879 }
1880 if len(rest) != 0 {
1881 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
1882 }
1883 return rawAttributes, nil
1884 }
1885
1886
1887 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
1888 var attributes []pkix.AttributeTypeAndValueSET
1889 for _, rawAttr := range rawAttributes {
1890 var attr pkix.AttributeTypeAndValueSET
1891 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
1892
1893
1894 if err == nil && len(rest) == 0 {
1895 attributes = append(attributes, attr)
1896 }
1897 }
1898 return attributes
1899 }
1900
1901
1902
1903 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
1904
1905 type pkcs10Attribute struct {
1906 Id asn1.ObjectIdentifier
1907 Values []asn1.RawValue `asn1:"set"`
1908 }
1909
1910 var ret []pkix.Extension
1911 requestedExts := make(map[string]bool)
1912 for _, rawAttr := range rawAttributes {
1913 var attr pkcs10Attribute
1914 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
1915
1916 continue
1917 }
1918
1919 if !attr.Id.Equal(oidExtensionRequest) {
1920 continue
1921 }
1922
1923 var extensions []pkix.Extension
1924 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
1925 return nil, err
1926 }
1927 for _, ext := range extensions {
1928 oidStr := ext.Id.String()
1929 if requestedExts[oidStr] {
1930 return nil, errors.New("x509: certificate request contains duplicate requested extensions")
1931 }
1932 requestedExts[oidStr] = true
1933 }
1934 ret = append(ret, extensions...)
1935 }
1936
1937 return ret, nil
1938 }
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error) {
1960 key, ok := priv.(crypto.Signer)
1961 if !ok {
1962 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1963 }
1964
1965 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
1966 if err != nil {
1967 return nil, err
1968 }
1969
1970 var publicKeyBytes []byte
1971 var publicKeyAlgorithm pkix.AlgorithmIdentifier
1972 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
1973 if err != nil {
1974 return nil, err
1975 }
1976
1977 extensions, err := buildCSRExtensions(template)
1978 if err != nil {
1979 return nil, err
1980 }
1981
1982
1983 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
1984 for _, attr := range template.Attributes {
1985 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
1986 copy(values, attr.Value)
1987 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
1988 Type: attr.Type,
1989 Value: values,
1990 })
1991 }
1992
1993 extensionsAppended := false
1994 if len(extensions) > 0 {
1995
1996 for _, atvSet := range attributes {
1997 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
1998 continue
1999 }
2000
2001
2002
2003 specifiedExtensions := make(map[string]bool)
2004
2005 for _, atvs := range atvSet.Value {
2006 for _, atv := range atvs {
2007 specifiedExtensions[atv.Type.String()] = true
2008 }
2009 }
2010
2011 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2012 newValue = append(newValue, atvSet.Value[0]...)
2013
2014 for _, e := range extensions {
2015 if specifiedExtensions[e.Id.String()] {
2016
2017
2018 continue
2019 }
2020
2021 newValue = append(newValue, pkix.AttributeTypeAndValue{
2022
2023
2024 Type: e.Id,
2025 Value: e.Value,
2026 })
2027 }
2028
2029 atvSet.Value[0] = newValue
2030 extensionsAppended = true
2031 break
2032 }
2033 }
2034
2035 rawAttributes, err := newRawAttributes(attributes)
2036 if err != nil {
2037 return nil, err
2038 }
2039
2040
2041
2042 if len(extensions) > 0 && !extensionsAppended {
2043 attr := struct {
2044 Type asn1.ObjectIdentifier
2045 Value [][]pkix.Extension `asn1:"set"`
2046 }{
2047 Type: oidExtensionRequest,
2048 Value: [][]pkix.Extension{extensions},
2049 }
2050
2051 b, err := asn1.Marshal(attr)
2052 if err != nil {
2053 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2054 }
2055
2056 var rawValue asn1.RawValue
2057 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2058 return nil, err
2059 }
2060
2061 rawAttributes = append(rawAttributes, rawValue)
2062 }
2063
2064 asn1Subject := template.RawSubject
2065 if len(asn1Subject) == 0 {
2066 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2067 if err != nil {
2068 return nil, err
2069 }
2070 }
2071
2072 tbsCSR := tbsCertificateRequest{
2073 Version: 0,
2074 Subject: asn1.RawValue{FullBytes: asn1Subject},
2075 PublicKey: publicKeyInfo{
2076 Algorithm: publicKeyAlgorithm,
2077 PublicKey: asn1.BitString{
2078 Bytes: publicKeyBytes,
2079 BitLength: len(publicKeyBytes) * 8,
2080 },
2081 },
2082 RawAttributes: rawAttributes,
2083 }
2084
2085 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2086 if err != nil {
2087 return nil, err
2088 }
2089 tbsCSR.Raw = tbsCSRContents
2090
2091 signature, err := signTBS(tbsCSRContents, key, signatureAlgorithm, rand)
2092 if err != nil {
2093 return nil, err
2094 }
2095
2096 return asn1.Marshal(certificateRequest{
2097 TBSCSR: tbsCSR,
2098 SignatureAlgorithm: algorithmIdentifier,
2099 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2100 })
2101 }
2102
2103
2104
2105 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2106 var csr certificateRequest
2107
2108 rest, err := asn1.Unmarshal(asn1Data, &csr)
2109 if err != nil {
2110 return nil, err
2111 } else if len(rest) != 0 {
2112 return nil, asn1.SyntaxError{Msg: "trailing data"}
2113 }
2114
2115 return parseCertificateRequest(&csr)
2116 }
2117
2118 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2119 out := &CertificateRequest{
2120 Raw: in.Raw,
2121 RawTBSCertificateRequest: in.TBSCSR.Raw,
2122 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2123 RawSubject: in.TBSCSR.Subject.FullBytes,
2124
2125 Signature: in.SignatureValue.RightAlign(),
2126 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2127
2128 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2129
2130 Version: in.TBSCSR.Version,
2131 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2132 }
2133
2134 var err error
2135 if out.PublicKeyAlgorithm != UnknownPublicKeyAlgorithm {
2136 out.PublicKey, err = parsePublicKey(&in.TBSCSR.PublicKey)
2137 if err != nil {
2138 return nil, err
2139 }
2140 }
2141
2142 var subject pkix.RDNSequence
2143 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2144 return nil, err
2145 } else if len(rest) != 0 {
2146 return nil, errors.New("x509: trailing data after X.509 Subject")
2147 }
2148
2149 out.Subject.FillFromRDNSequence(&subject)
2150
2151 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2152 return nil, err
2153 }
2154
2155 for _, extension := range out.Extensions {
2156 switch {
2157 case extension.Id.Equal(oidExtensionSubjectAltName):
2158 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2159 if err != nil {
2160 return nil, err
2161 }
2162 }
2163 }
2164
2165 return out, nil
2166 }
2167
2168
2169 func (c *CertificateRequest) CheckSignature() error {
2170 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey, true)
2171 }
2172
2173
2174
2175 type RevocationListEntry struct {
2176
2177
2178 Raw []byte
2179
2180
2181
2182
2183 SerialNumber *big.Int
2184
2185
2186
2187 RevocationTime time.Time
2188
2189
2190
2191
2192
2193
2194
2195
2196 ReasonCode int
2197
2198
2199
2200
2201
2202 Extensions []pkix.Extension
2203
2204
2205
2206
2207 ExtraExtensions []pkix.Extension
2208 }
2209
2210
2211
2212 type RevocationList struct {
2213
2214
2215 Raw []byte
2216
2217
2218 RawTBSRevocationList []byte
2219
2220 RawIssuer []byte
2221
2222
2223 Issuer pkix.Name
2224
2225
2226
2227
2228 AuthorityKeyId []byte
2229
2230 Signature []byte
2231
2232
2233
2234 SignatureAlgorithm SignatureAlgorithm
2235
2236
2237
2238
2239
2240 RevokedCertificateEntries []RevocationListEntry
2241
2242
2243
2244
2245
2246
2247 RevokedCertificates []pkix.RevokedCertificate
2248
2249
2250
2251
2252
2253 Number *big.Int
2254
2255
2256
2257 ThisUpdate time.Time
2258
2259
2260
2261 NextUpdate time.Time
2262
2263
2264
2265 Extensions []pkix.Extension
2266
2267
2268
2269 ExtraExtensions []pkix.Extension
2270 }
2271
2272
2273
2274
2275
2276
2277
2278 type certificateList struct {
2279 TBSCertList tbsCertificateList
2280 SignatureAlgorithm pkix.AlgorithmIdentifier
2281 SignatureValue asn1.BitString
2282 }
2283
2284 type tbsCertificateList struct {
2285 Raw asn1.RawContent
2286 Version int `asn1:"optional,default:0"`
2287 Signature pkix.AlgorithmIdentifier
2288 Issuer asn1.RawValue
2289 ThisUpdate time.Time
2290 NextUpdate time.Time `asn1:"optional"`
2291 RevokedCertificates []pkix.RevokedCertificate `asn1:"optional"`
2292 Extensions []pkix.Extension `asn1:"tag:0,optional,explicit"`
2293 }
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2308 if template == nil {
2309 return nil, errors.New("x509: template can not be nil")
2310 }
2311 if issuer == nil {
2312 return nil, errors.New("x509: issuer can not be nil")
2313 }
2314 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2315 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2316 }
2317 if len(issuer.SubjectKeyId) == 0 {
2318 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2319 }
2320 if template.NextUpdate.Before(template.ThisUpdate) {
2321 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2322 }
2323 if template.Number == nil {
2324 return nil, errors.New("x509: template contains nil Number field")
2325 }
2326
2327 signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(priv, template.SignatureAlgorithm)
2328 if err != nil {
2329 return nil, err
2330 }
2331
2332 var revokedCerts []pkix.RevokedCertificate
2333
2334
2335 if len(template.RevokedCertificates) > 0 && len(template.RevokedCertificateEntries) == 0 {
2336
2337 revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2338 for i, rc := range template.RevokedCertificates {
2339 rc.RevocationTime = rc.RevocationTime.UTC()
2340 revokedCerts[i] = rc
2341 }
2342 } else {
2343
2344
2345 revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificateEntries))
2346 for i, rce := range template.RevokedCertificateEntries {
2347 if rce.SerialNumber == nil {
2348 return nil, errors.New("x509: template contains entry with nil SerialNumber field")
2349 }
2350 if rce.RevocationTime.IsZero() {
2351 return nil, errors.New("x509: template contains entry with zero RevocationTime field")
2352 }
2353
2354 rc := pkix.RevokedCertificate{
2355 SerialNumber: rce.SerialNumber,
2356 RevocationTime: rce.RevocationTime.UTC(),
2357 }
2358
2359
2360
2361 exts := make([]pkix.Extension, 0, len(rce.ExtraExtensions))
2362 for _, ext := range rce.ExtraExtensions {
2363 if ext.Id.Equal(oidExtensionReasonCode) {
2364 return nil, errors.New("x509: template contains entry with ReasonCode ExtraExtension; use ReasonCode field instead")
2365 }
2366 exts = append(exts, ext)
2367 }
2368
2369
2370
2371 if rce.ReasonCode != 0 {
2372 reasonBytes, err := asn1.Marshal(asn1.Enumerated(rce.ReasonCode))
2373 if err != nil {
2374 return nil, err
2375 }
2376
2377 exts = append(exts, pkix.Extension{
2378 Id: oidExtensionReasonCode,
2379 Value: reasonBytes,
2380 })
2381 }
2382
2383 if len(exts) > 0 {
2384 rc.Extensions = exts
2385 }
2386 revokedCerts[i] = rc
2387 }
2388 }
2389
2390 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2391 if err != nil {
2392 return nil, err
2393 }
2394
2395 if numBytes := template.Number.Bytes(); len(numBytes) > 20 || (len(numBytes) == 20 && numBytes[0]&0x80 != 0) {
2396 return nil, errors.New("x509: CRL number exceeds 20 octets")
2397 }
2398 crlNum, err := asn1.Marshal(template.Number)
2399 if err != nil {
2400 return nil, err
2401 }
2402
2403
2404 issuerSubject, err := subjectBytes(issuer)
2405 if err != nil {
2406 return nil, err
2407 }
2408
2409 tbsCertList := tbsCertificateList{
2410 Version: 1,
2411 Signature: algorithmIdentifier,
2412 Issuer: asn1.RawValue{FullBytes: issuerSubject},
2413 ThisUpdate: template.ThisUpdate.UTC(),
2414 NextUpdate: template.NextUpdate.UTC(),
2415 Extensions: []pkix.Extension{
2416 {
2417 Id: oidExtensionAuthorityKeyId,
2418 Value: aki,
2419 },
2420 {
2421 Id: oidExtensionCRLNumber,
2422 Value: crlNum,
2423 },
2424 },
2425 }
2426 if len(revokedCerts) > 0 {
2427 tbsCertList.RevokedCertificates = revokedCerts
2428 }
2429
2430 if len(template.ExtraExtensions) > 0 {
2431 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2432 }
2433
2434 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2435 if err != nil {
2436 return nil, err
2437 }
2438
2439
2440
2441 tbsCertList.Raw = tbsCertListContents
2442
2443 signature, err := signTBS(tbsCertListContents, priv, signatureAlgorithm, rand)
2444 if err != nil {
2445 return nil, err
2446 }
2447
2448 return asn1.Marshal(certificateList{
2449 TBSCertList: tbsCertList,
2450 SignatureAlgorithm: algorithmIdentifier,
2451 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2452 })
2453 }
2454
2455
2456
2457 func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error {
2458 if parent.Version == 3 && !parent.BasicConstraintsValid ||
2459 parent.BasicConstraintsValid && !parent.IsCA {
2460 return ConstraintViolationError{}
2461 }
2462
2463 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCRLSign == 0 {
2464 return ConstraintViolationError{}
2465 }
2466
2467 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
2468 return ErrUnsupportedAlgorithm
2469 }
2470
2471 return parent.CheckSignature(rl.SignatureAlgorithm, rl.RawTBSRevocationList, rl.Signature)
2472 }
2473
View as plain text