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