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