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