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