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