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