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