-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
x509.go
1467 lines (1276 loc) · 41 KB
/
x509.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
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
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package crypto
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"fmt"
"math/big"
"net"
"net/mail"
"net/url"
"strings"
"time"
"github.com/Laisky/errors/v2"
"github.com/Laisky/zap"
gutils "github.com/Laisky/go-utils/v4"
gcounter "github.com/Laisky/go-utils/v4/counter"
glog "github.com/Laisky/go-utils/v4/log"
)
// X509CertSerialNumberGenerator x509 certificate serial number generator
type X509CertSerialNumberGenerator interface {
SerialNum() int64
}
type x509CSROption struct {
err error
subject pkix.Name
dnsNames []string
emailAddresses []string
ipAddresses []net.IP
uris []*url.URL
// extensions,
extraExtensions []pkix.Extension
// attributes contains the CSR attributes that can parse as
// pkix.AttributeTypeAndValueSET.
//
// Deprecated: Use Extensions and ExtraExtensions instead for parsing and
// generating the requestedExtensions attribute.
attributes []pkix.AttributeTypeAndValueSET
// signatureAlgorithm specific signature algorithm manually
//
// default to auto choose algorithm depends on certificate's algorithm
signatureAlgorithm x509.SignatureAlgorithm
// publicKeyAlgorithm specific publick key algorithm manually
//
// default to auto choose algorithm depends on certificate's algorithm
// publicKeyAlgorithm x509.PublicKeyAlgorithm
}
// X509CSROption option to generate tls certificate
type X509CSROption func(*x509CSROption) error
// WithX509CSRExtension set extension
//
// Extensions contains raw X.509 extensions. When parsing certificates,
// this can be used to extract non-critical extensions that are not
// parsed by this package. When marshaling certificates, the Extensions
// field is ignored, see ExtraExtensions.
//
// Deprecated: this field is ignored by golang's built-in x509 library,
// use ExtraExtensions instead if you want to add custom extensions.
func WithX509CSRExtension(_ pkix.Extension) X509CSROption {
return func(o *x509CSROption) error {
// o.extensions = append(o.extensions, ext)
return nil
}
}
// WithX509CSRExtraExtension set extra extension
//
// ExtraExtensions contains extensions to be copied, raw, into any
// marshaled certificates. Values override any extensions that would
// otherwise be produced based on the other fields. The ExtraExtensions
// field is not populated when parsing certificates, see Extensions.
func WithX509CSRExtraExtension(ext pkix.Extension) X509CSROption {
return func(o *x509CSROption) error {
o.extraExtensions = append(o.extraExtensions, ext)
return nil
}
}
// WithX509CSRAttribute set attribute
//
// Deprecated: Use Extensions and ExtraExtensions instead for parsing and
// generating the requestedExtensions attribute.
func WithX509CSRAttribute(attr pkix.AttributeTypeAndValueSET) X509CSROption {
return func(o *x509CSROption) error {
o.attributes = append(o.attributes, attr)
return nil
}
}
// WithX509CSRSignatureAlgorithm set signature algorithm
func WithX509CSRSignatureAlgorithm(sigAlg x509.SignatureAlgorithm) X509CSROption {
return func(o *x509CSROption) error {
o.signatureAlgorithm = sigAlg
return nil
}
}
// WithX509CSRPublicKeyAlgorithm set signature algorithm
//
// Deprecated: this field is ignored by golang's built-in x509 library
func WithX509CSRPublicKeyAlgorithm(_ x509.PublicKeyAlgorithm) X509CSROption {
return func(o *x509CSROption) error {
// o.publicKeyAlgorithm = pubAlg
return nil
}
}
// WithX509CSRSubject set subject name
func WithX509CSRSubject(subject pkix.Name) X509CSROption {
return func(o *x509CSROption) error {
o.subject = subject
return nil
}
}
// WithX509CSRCommonName set common name
func WithX509CSRCommonName(commonName string) X509CSROption {
return func(o *x509CSROption) error {
o.subject.CommonName = commonName
return nil
}
}
// WithX509CSROrganization set organization
func WithX509CSROrganization(organization ...string) X509CSROption {
return func(o *x509CSROption) error {
o.subject.Organization = append(o.subject.Organization, organization...)
return nil
}
}
// WithX509CSROrganizationUnit set organization units
func WithX509CSROrganizationUnit(ou ...string) X509CSROption {
return func(o *x509CSROption) error {
o.subject.OrganizationalUnit = append(o.subject.OrganizationalUnit, ou...)
return nil
}
}
// WithX509CSRLocality set subject localities
func WithX509CSRLocality(l ...string) X509CSROption {
return func(o *x509CSROption) error {
o.subject.Locality = append(o.subject.Locality, l...)
return nil
}
}
// WithX509CSRCountry set subject countries
func WithX509CSRCountry(values ...string) X509CSROption {
return func(o *x509CSROption) error {
o.subject.Country = append(o.subject.Country, values...)
return nil
}
}
// WithX509CSRProvince set subject provinces
func WithX509CSRProvince(values ...string) X509CSROption {
return func(o *x509CSROption) error {
o.subject.Province = append(o.subject.Province, values...)
return nil
}
}
// WithX509CSRStreetAddrs set subjuect street addresses
func WithX509CSRStreetAddrs(addrs ...string) X509CSROption {
return func(o *x509CSROption) error {
o.subject.StreetAddress = append(o.subject.StreetAddress, addrs...)
return nil
}
}
// WithX509CSRPostalCode set subjuect postal codes
func WithX509CSRPostalCode(codes ...string) X509CSROption {
return func(o *x509CSROption) error {
o.subject.PostalCode = append(o.subject.PostalCode, codes...)
return nil
}
}
// WithX509CSRDNSNames set dns sans
func WithX509CSRDNSNames(dnsNames ...string) X509CSROption {
return func(o *x509CSROption) error {
o.dnsNames = append(o.dnsNames, dnsNames...)
return nil
}
}
// WithX509CSREmailAddrs set email sans
func WithX509CSREmailAddrs(emailAddresses ...string) X509CSROption {
return func(o *x509CSROption) error {
o.emailAddresses = append(o.emailAddresses, emailAddresses...)
return nil
}
}
// WithX509CSRIPAddrs set ip sans
func WithX509CSRIPAddrs(ipAddresses ...net.IP) X509CSROption {
return func(o *x509CSROption) error {
o.ipAddresses = append(o.ipAddresses, ipAddresses...)
return nil
}
}
// WithX509CSRURIs set uri sans
func WithX509CSRURIs(uris ...*url.URL) X509CSROption {
return func(o *x509CSROption) error {
o.uris = append(o.uris, uris...)
return nil
}
}
// WithX509CertSANS set certificate SANs
//
// refer to RFC-5280 4.2.1.6
//
// auto WithX509CSRSANS to ip/email/url/dns
func WithX509CSRSANS(sans ...string) X509CSROption {
return func(o *x509CSROption) error {
parsedSANs := parseSans(sans)
o.dnsNames = append(o.dnsNames, parsedSANs.DNSNames...)
o.emailAddresses = append(o.emailAddresses, parsedSANs.EmailAddresses...)
o.uris = append(o.uris, parsedSANs.URIs...)
o.ipAddresses = append(o.ipAddresses, parsedSANs.IPAddresses...)
return nil
}
}
func (o *x509CSROption) fillDefault() *x509CSROption {
return o
}
func (o *x509CSROption) applyOpts(opts ...X509CSROption) (*x509CSROption, error) {
if o.err != nil {
return nil, o.err
}
for _, f := range opts {
if err := f(o); err != nil {
return nil, err
}
}
return o, nil
}
// NewX509CSR new CSR
//
// # Arguments
//
// if prikey is not RSA private key, you must set SignatureAlgorithm by WithX509CertSignatureAlgorithm.
//
// Warning: CSR do not support set IsCA / KeyUsage / ExtKeyUsage,
// you should set these attributes in NewX509CertByCSR.
func NewX509CSR(prikey crypto.PrivateKey, opts ...X509CSROption) (csrDer []byte, err error) {
if err = validPrikey(prikey); err != nil {
return nil, err
}
opt, err := new(x509CSROption).applyOpts(opts...)
if err != nil {
return nil, errors.Wrap(err, "apply options")
}
csrTpl := &x509.CertificateRequest{
SignatureAlgorithm: opt.signatureAlgorithm,
Subject: opt.subject,
ExtraExtensions: opt.extraExtensions,
Attributes: opt.attributes,
EmailAddresses: opt.emailAddresses,
DNSNames: opt.dnsNames,
IPAddresses: opt.ipAddresses,
URIs: opt.uris,
// these are fields that are not used by CreateCertificateRequest
// PublicKeyAlgorithm: opt.publicKeyAlgorithm,
// Extensions: opt.extensions,
}
csrDer, err = x509.CreateCertificateRequest(rand.Reader, csrTpl, prikey)
if err != nil {
return nil, errors.Wrap(err, "create certificate")
}
return csrDer, nil
}
var (
internalCertSerialNumGenerator X509CertSerialNumberGenerator
)
func init() {
var err error
if internalCertSerialNumGenerator, err = NewDefaultX509CertSerialNumGenerator(); err != nil {
glog.Shared.Panic("new default cert serial number generator", zap.Error(err))
}
}
// DefaultX509CertSerialNumGenerator default cert serial number generator base on epoch time and random int
type DefaultX509CertSerialNumGenerator struct {
counter *gcounter.RotateCounter
}
// NewDefaultX509CertSerialNumGenerator new DefaultX509CertSerialNumGenerator
func NewDefaultX509CertSerialNumGenerator() (*DefaultX509CertSerialNumGenerator, error) {
serialCounter, err := gcounter.NewRotateCounter(10000)
if err != nil {
return nil, errors.Wrap(err, "new counter")
}
return &DefaultX509CertSerialNumGenerator{
counter: serialCounter,
}, nil
}
// SerialNum get randon serial number
func (g *DefaultX509CertSerialNumGenerator) SerialNum() int64 {
return time.Now().UnixMilli()*10000 + g.counter.Count()
}
// NewX509CertTemplate new tls template with common default values
// func NewX509CertTemplate(opts ...X509CertOption) (tpl *x509.Certificate, err error) {
// opt, err := new(x509V3CertOption).fillDefault().applyOpts(opts...)
// if err != nil {
// return nil, err
// }
// notAfter := opt.validFrom.Add(opt.validFor)
// tpl = &x509.Certificate{
// SignatureAlgorithm: opt.signatureAlgorithm,
// SerialNumber: opt.serialNumber,
// Subject: pkix.Name{
// CommonName: opt.commonName,
// Organization: opt.organization,
// OrganizationalUnit: opt.organizationUnit,
// Locality: opt.locality,
// Country: opt.country,
// Province: opt.province,
// StreetAddress: opt.streetAddrs,
// PostalCode: opt.PostalCode,
// },
// NotBefore: opt.validFrom,
// NotAfter: notAfter,
// KeyUsage: opt.keyUsage,
// ExtKeyUsage: opt.extKeyUsage,
// BasicConstraintsValid: true,
// IsCA: opt.isCA,
// PolicyIdentifiers: opt.policies,
// CRLDistributionPoints: opt.crls,
// OCSPServer: opt.ocsps,
// }
// sansTpl := parseSans(opt.sans)
// tpl.DNSNames = sansTpl.DNSNames
// tpl.EmailAddresses = sansTpl.EmailAddresses
// tpl.IPAddresses = sansTpl.IPAddresses
// tpl.URIs = sansTpl.URIs
// return tpl, nil
// }
type sansTemp struct {
DNSNames []string
EmailAddresses []string
IPAddresses []net.IP
URIs []*url.URL
}
func parseSans(sans []string) (tpl sansTemp) {
for i := range sans {
if ip := net.ParseIP(sans[i]); ip != nil {
tpl.IPAddresses = append(tpl.IPAddresses, ip)
} else if email, err := mail.ParseAddress(sans[i]); err == nil && email != nil {
tpl.EmailAddresses = append(tpl.EmailAddresses, email.Address)
} else if uri, err := url.ParseRequestURI(sans[i]); err == nil && uri != nil {
tpl.URIs = append(tpl.URIs, uri)
} else {
tpl.DNSNames = append(tpl.DNSNames, sans[i])
}
}
return tpl
}
type signCSROption struct {
notBefore time.Time
notAfter time.Time
isCA bool
keyUsage x509.KeyUsage
extKeyUsage []x509.ExtKeyUsage
serialNumber *big.Int
// policies certificate policies
//
// refer to RFC-5280 4.2.1.4
policies []asn1.ObjectIdentifier
// crls crl endpoints
crls []string
// ocsps ocsp servers
ocsps []string
signatureAlgo x509.SignatureAlgorithm
// pubkeyAlgo x509.PublicKeyAlgorithm
// extensions,
extraExtensions []pkix.Extension
// pubkey csr will specific csr's pubkey, not use ca's pubkey
pubkey crypto.PublicKey
serialNumGenerator X509CertSerialNumberGenerator
}
func (o *signCSROption) fillDefault(csr *x509.CertificateRequest) *signCSROption {
o.notBefore = time.Now().UTC()
o.notAfter = o.notBefore.Add(7 * 24 * time.Hour)
o.keyUsage |= x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature
o.serialNumGenerator = internalCertSerialNumGenerator
if csr != nil {
if o.signatureAlgo == x509.UnknownSignatureAlgorithm {
o.signatureAlgo = csr.SignatureAlgorithm
}
// if o.pubkeyAlgo == x509.UnknownPublicKeyAlgorithm {
// o.pubkeyAlgo = csr.PublicKeyAlgorithm
// }
// o.extensions = append(o.extensions, csr.Extensions...)
o.extraExtensions = append(o.extraExtensions, csr.ExtraExtensions...)
}
return o
}
func (o *signCSROption) applyOpts(opts ...SignCSROption) (*signCSROption, error) {
for _, f := range opts {
if err := f(o); err != nil {
return nil, err
}
}
switch {
case o.serialNumber == nil:
// generate serial number by internal generator if not set
o.serialNumber = big.NewInt(o.serialNumGenerator.SerialNum())
}
return o, nil
}
// SignCSROption options for create certificate from CRL
type SignCSROption func(*signCSROption) error
// WithX509SerialNumGenerator set serial number generator
func WithX509SerialNumGenerator(gen X509CertSerialNumberGenerator) SignCSROption {
return func(o *signCSROption) error {
o.serialNumGenerator = gen
return nil
}
}
// WithX509SignSignatureAlgorithm set signature algorithm
func WithX509SignSignatureAlgorithm(algo x509.SignatureAlgorithm) SignCSROption {
return func(o *signCSROption) error {
o.signatureAlgo = algo
return nil
}
}
// WithX509SignPublicKeyAlgorithm set public key algorithm
//
// Deprecated: this field is ignored by golang built-in x509 library
func WithX509SignPublicKeyAlgorithm(_ x509.PublicKeyAlgorithm) SignCSROption {
return func(o *signCSROption) error {
// o.pubkeyAlgo = algo
return nil
}
}
// WithX509SignCSRExtenstions set certificate extensions
//
// Extensions contains all requested extensions, in raw form. When parsing
// CSRs, this can be used to extract extensions that are not parsed by this
// package.
//
// Deprecated: this field is ignored by golang built-in x509 library,
// use WithX509SignCSRExtraExtenstions instead if you want to set extensions.
func WithX509SignCSRExtenstions(_ ...pkix.Extension) SignCSROption {
return func(o *signCSROption) error {
// o.extensions = append(o.extensions, exts...)
return nil
}
}
// WithX509SignCSRExtraExtenstions set certificate extra extensions
//
// ExtraExtensions contains extensions to be copied, raw, into any CSR
// marshaled by CreateCertificateRequest. Values override any extensions
// that would otherwise be produced based on the other fields but are
// overridden by any extensions specified in Attributes.
//
// The ExtraExtensions field is not populated by ParseCertificateRequest,
// see Extensions instead.
func WithX509SignCSRExtraExtenstions(exts ...pkix.Extension) SignCSROption {
return func(o *signCSROption) error {
o.extraExtensions = append(o.extraExtensions, exts...)
return nil
}
}
// WithX509SignCSRPolicies set certificate policies
func WithX509SignCSRPolicies(policies ...asn1.ObjectIdentifier) SignCSROption {
return func(o *signCSROption) error {
o.policies = append(o.policies, policies...)
return nil
}
}
// WithX509SignCSROCSPServers set ocsp servers
func WithX509SignCSROCSPServers(ocsp ...string) SignCSROption {
return func(o *signCSROption) error {
o.ocsps = append(o.ocsps, ocsp...)
return nil
}
}
// WithX509SignCSRSeriaNumber set certificate/CRL's serial number
//
// refer to RFC-5280 5.2.3 &
//
// # Args
//
// seriaNumber:
// - (optional): generate certificate
// - (required): generate CRL
func WithX509SignCSRSeriaNumber(serialNumber *big.Int) SignCSROption {
return func(o *signCSROption) error {
if serialNumber == nil {
return errors.Errorf("serial number shoule not be empty")
}
o.serialNumber = serialNumber
return nil
}
}
// WithX509SignCSRKeyUsage add key usage
func WithX509SignCSRKeyUsage(usage ...x509.KeyUsage) SignCSROption {
return func(o *signCSROption) error {
for i := range usage {
o.keyUsage |= usage[i]
}
return nil
}
}
// WithX509SignCSRCRLs add crl endpoints
func WithX509SignCSRCRLs(crlEndpoint ...string) SignCSROption {
return func(o *signCSROption) error {
o.crls = append(o.crls, crlEndpoint...)
return nil
}
}
// WithX509SignCSRExtKeyUsage add ext key usage
func WithX509SignCSRExtKeyUsage(usage ...x509.ExtKeyUsage) SignCSROption {
return func(o *signCSROption) error {
o.extKeyUsage = append(o.extKeyUsage, usage...)
return nil
}
}
// WithX509SignCSRValidFrom set valid from
//
// deprecated: use WithX509SignCSRNotBefore instead
func WithX509SignCSRValidFrom(validFrom time.Time) SignCSROption {
return func(o *signCSROption) error {
o.notBefore = validFrom
return nil
}
}
// WithX509SignCSRNotBefore set valid from
func WithX509SignCSRNotBefore(notBefore time.Time) SignCSROption {
return func(o *signCSROption) error {
o.notBefore = notBefore
return nil
}
}
// WithX509SignCSRValidFor set valid for duration
//
// deprecated: use WithX509SignCSRNotAfter instead
func WithX509SignCSRValidFor(validFor time.Duration) SignCSROption {
return func(o *signCSROption) error {
o.notAfter = o.notBefore.Add(validFor)
return nil
}
}
// WithX509SignCSRNotAfter set valid for duration
func WithX509SignCSRNotAfter(notAfter time.Time) SignCSROption {
return func(o *signCSROption) error {
o.notAfter = notAfter
return nil
}
}
// WithX509SignCSRIsCA set is ca
func WithX509SignCSRIsCA() SignCSROption {
return func(o *signCSROption) error {
o.isCA = true
o.keyUsage |= x509.KeyUsageCertSign | x509.KeyUsageCRLSign
return nil
}
}
// WithX509SignCSRIsCRLCA set is ca to sign CRL
func WithX509SignCSRIsCRLCA() SignCSROption {
return func(o *signCSROption) error {
o.isCA = true
o.keyUsage |= x509.KeyUsageCRLSign
return nil
}
}
// NewX509CertByCSR sign CSR to certificate
//
// Depends on RFC-5280 4.2.1.12, empty ext key usage is as same as any key usage.
// so do not set any default ext key usages.
//
// - https://github.com/golang/go/blob/1e9ff255a130200fcc4ec5e911d28181fce947d5/src/crypto/x509/verify.go#L1118
//
// but key usage is required in many cases:
//
// - https://github.com/golang/go/blob/e04be8b24c20816f3429a8193c324ea67892e61f/src/crypto/x509/x509.go#L2165
func NewX509CertByCSR(
ca *x509.Certificate,
prikey crypto.PrivateKey,
csrDer []byte,
opts ...SignCSROption) (certDer []byte, err error) {
if err = validPrikey(prikey); err != nil {
return nil, err
}
csr, err := Der2CSR(csrDer)
if err != nil {
return nil, errors.Wrap(err, "parse csr")
}
opt, err := new(signCSROption).fillDefault(csr).applyOpts(opts...)
if err != nil {
return nil, errors.Wrap(err, "apply options")
}
if !ca.IsCA || (ca.KeyUsage&x509.KeyUsageCertSign) == x509.KeyUsage(0) {
return nil, errors.Errorf("ca is invalid to sign cert")
}
certOpts := []X509CertOption{
WithX509Subject(csr.Subject),
WithX509CertParent(ca),
WithX509CertNotBefore(opt.notBefore),
WithX509CertNotAfter(opt.notAfter),
WithX509CertPolicies(opt.policies...),
WithX509CertCRLs(opt.crls...),
WithX509CertOCSPServers(opt.ocsps...),
WithX509CertKeyUsage(opt.keyUsage),
WithX509CertExtKeyUsage(opt.extKeyUsage...),
WithX509CertSeriaNumber(opt.serialNumber),
WithX509CertDNSNames(csr.DNSNames...),
WithX509CertEmailAddrs(csr.EmailAddresses...),
WithX509CertIPAddrs(csr.IPAddresses...),
WithX509CertURIs(csr.URIs...),
WithX509CertPubkey(csr.PublicKey),
WithX509CertSignatureAlgorithm(opt.signatureAlgo),
// WithX509CertPublicKeyAlgorithm(opt.pubkeyAlgo),
// WithX509CertExtentions(opt.extensions...),
WithX509CertExtraExtensions(opt.extraExtensions...),
}
if opt.isCA {
certOpts = append(certOpts, WithX509CertIsCA())
}
if opt.serialNumGenerator != nil {
certOpts = append(certOpts, WithX509CertSerialNumGenerator(opt.serialNumGenerator))
}
return NewX509Cert(prikey, certOpts...)
}
type x509V3CertOption struct {
parent *x509.Certificate
signCSROption
x509CSROption
}
func (o *x509V3CertOption) fillDefault() *x509V3CertOption {
o.signCSROption.fillDefault(nil)
o.x509CSROption.fillDefault()
return o
}
// X509CertOption option to generate tls certificate
type X509CertOption func(*x509V3CertOption) error
// WithX509CertExtentions set extensions
//
// Deprecated: this field is ignored in x509 v3 certificate,
// use WithX509CertExtraExtensions instead if you want to set extensions.
func WithX509CertExtentions(_ ...pkix.Extension) X509CertOption {
return func(o *x509V3CertOption) error {
// o.signCSROption.extensions = append(o.signCSROption.extensions, exts...)
return nil
}
}
// WithX509CertExtraExtensions set extra extensions
func WithX509CertExtraExtensions(exts ...pkix.Extension) X509CertOption {
return func(o *x509V3CertOption) error {
o.signCSROption.extraExtensions = append(o.signCSROption.extraExtensions, exts...)
return nil
}
}
// WithX509CertParent set issuer
func WithX509CertParent(parent *x509.Certificate) X509CertOption {
return func(o *x509V3CertOption) error {
o.parent = parent
return nil
}
}
// WithX509CertPolicies set certificate policies
func WithX509CertPolicies(policies ...asn1.ObjectIdentifier) X509CertOption {
return func(o *x509V3CertOption) error {
o.policies = append(o.policies, policies...)
return nil
}
}
// WithX509CertOCSPServers set ocsp servers
func WithX509CertOCSPServers(ocsp ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.ocsps = append(o.ocsps, ocsp...)
return nil
}
}
// WithX509CertSeriaNumber set certificate/CRL's serial number
//
// refer to RFC-5280 5.2.3 &
//
// # Args
//
// seriaNumber:
// - (optional): generate certificate
// - (required): generate CRL
func WithX509CertSeriaNumber(serialNumber *big.Int) X509CertOption {
return func(o *x509V3CertOption) error {
if serialNumber == nil {
return errors.Errorf("serial number shoule not be empty")
}
o.serialNumber = serialNumber
return nil
}
}
// WithX509CertSerialNumGenerator set serial number generator
func WithX509CertSerialNumGenerator(gen X509CertSerialNumberGenerator) X509CertOption {
return func(o *x509V3CertOption) error {
if gen == nil {
return errors.Errorf("serial number generator shoule not be empty")
}
o.serialNumGenerator = gen
return nil
}
}
// WithX509CertKeyUsage add key usage
func WithX509CertKeyUsage(usage ...x509.KeyUsage) X509CertOption {
return func(o *x509V3CertOption) error {
for i := range usage {
o.keyUsage |= usage[i]
}
return nil
}
}
// WithX509CertCRLs add crl endpoints
func WithX509CertCRLs(crlEndpoint ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.crls = append(o.crls, crlEndpoint...)
return nil
}
}
// WithX509CertExtKeyUsage add ext key usage
func WithX509CertExtKeyUsage(usage ...x509.ExtKeyUsage) X509CertOption {
return func(o *x509V3CertOption) error {
o.extKeyUsage = append(o.extKeyUsage, usage...)
return nil
}
}
// WithX509CertSignatureAlgorithm set signature algorithm
func WithX509CertSignatureAlgorithm(sigAlg x509.SignatureAlgorithm) X509CertOption {
return func(o *x509V3CertOption) error {
o.signatureAlgorithm = sigAlg
return nil
}
}
// WithX509CertPublicKeyAlgorithm set signature algorithm
//
// Deprecated: this field is ignored in x509 v3 certificate
func WithX509CertPublicKeyAlgorithm(_ x509.PublicKeyAlgorithm) X509CertOption {
return func(o *x509V3CertOption) error {
// o.publicKeyAlgorithm = pubkeyAlg
return nil
}
}
// WithX509Subject set subject name
func WithX509Subject(subject pkix.Name) X509CertOption {
return func(o *x509V3CertOption) error {
o.subject = subject
return nil
}
}
// WithX509CertCommonName set common name
func WithX509CertCommonName(commonName string) X509CertOption {
return func(o *x509V3CertOption) error {
o.subject.CommonName = commonName
return nil
}
}
// WithX509CertOrganization set organization
func WithX509CertOrganization(organization ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.subject.Organization = append(o.subject.Organization, organization...)
return nil
}
}
// WithX509CertOrganizationUnit set organization unit
func WithX509CertOrganizationUnit(ou ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.subject.OrganizationalUnit = append(o.subject.OrganizationalUnit, ou...)
return nil
}
}
// WithX509CertLocality set subject localities
func WithX509CertLocality(l ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.subject.Locality = append(o.subject.Locality, l...)
return nil
}
}
// WithX509CertCountry set subject countries
func WithX509CertCountry(values ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.subject.Country = append(o.subject.Country, values...)
return nil
}
}
// WithX509CertProvince set subject provinces
func WithX509CertProvince(values ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.subject.Province = append(o.subject.Province, values...)
return nil
}
}
// WithX509CertStreetAddrs set subjuect street addresses
func WithX509CertStreetAddrs(addrs ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.subject.StreetAddress = append(o.subject.StreetAddress, addrs...)
return nil
}
}
// WithX509CertPostalCode set subjuect postal codes
func WithX509CertPostalCode(codes ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.subject.PostalCode = append(o.subject.PostalCode, codes...)
return nil
}
}
// WithX509CertSANS set certificate SANs
//
// refer to RFC-5280 4.2.1.6
//
// auto parse to ip/email/url/dns
func WithX509CertSANS(sans ...string) X509CertOption {
return func(o *x509V3CertOption) error {
parsedSANs := parseSans(sans)
o.dnsNames = append(o.dnsNames, parsedSANs.DNSNames...)
o.emailAddresses = append(o.emailAddresses, parsedSANs.EmailAddresses...)
o.uris = append(o.uris, parsedSANs.URIs...)
o.ipAddresses = append(o.ipAddresses, parsedSANs.IPAddresses...)
return nil
}
}
// WithX509CertDNSNames set dns sans
func WithX509CertDNSNames(dnsNames ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.dnsNames = append(o.dnsNames, dnsNames...)
return nil
}
}
// WithX509CertEmailAddrs set email sans
func WithX509CertEmailAddrs(emailAddresses ...string) X509CertOption {
return func(o *x509V3CertOption) error {
o.emailAddresses = append(o.emailAddresses, emailAddresses...)
return nil
}
}
// WithX509CertIPAddrs set ip sans
func WithX509CertIPAddrs(ipAddresses ...net.IP) X509CertOption {
return func(o *x509V3CertOption) error {
o.ipAddresses = append(o.ipAddresses, ipAddresses...)
return nil
}
}
// WithX509CertURIs set uri sans
func WithX509CertURIs(uris ...*url.URL) X509CertOption {
return func(o *x509V3CertOption) error {
o.uris = append(o.uris, uris...)
return nil
}
}
// WithX509CertValidFrom set valid from
//
// deprecated: use WithX509CertNotBefore instead
func WithX509CertValidFrom(validFrom time.Time) X509CertOption {
return func(o *x509V3CertOption) error {
o.notBefore = validFrom
return nil
}
}
// WithX509CertNotBefore set not before
func WithX509CertNotBefore(notBefore time.Time) X509CertOption {
return func(o *x509V3CertOption) error {
o.notBefore = notBefore
return nil
}
}
// WithX509CertValidFor set valid for duration
//
// deprecated: use WithX509CertNotAfter instead
func WithX509CertValidFor(validFor time.Duration) X509CertOption {
return func(o *x509V3CertOption) error {
o.notAfter = o.notBefore.Add(validFor)
return nil
}
}
// WithX509CertNotAfter set not after
//
// default to 30 days later
func WithX509CertNotAfter(notAfter time.Time) X509CertOption {
return func(o *x509V3CertOption) error {
o.notAfter = notAfter
return nil
}