-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
1025 lines (907 loc) · 27.2 KB
/
auth.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 auth
import (
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/base32"
"encoding/base64"
"encoding/binary"
"encoding/json"
"encoding/pem"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strings"
"errors"
"fmt"
"math/big"
"time"
meshauth "github.com/costinm/hbone/auth"
)
// Support for ID and authn using certificates and workload identity.
//
// Private key, certificates and associated helpers.
// An IPv6 address is derived from the public key.
//
// Auth represents a workload identity and associated info.
// It can load existing certificates from the well known location, and can
// save certificates to the well known locations.
//
//
// When loading existing certificate it can extract namespace/trustdomain/sa.
type Auth struct {
// MeshAuth is minimal, simplified version of auth based only on platform certs.
meshauth.MeshAuth
// Public part of the Auth info
//ugate.DMNode
PublicKey []byte `json:"pub,omitempty"`
ID string `json:"id,omitempty"`
// Primary VIP, Created from the PublicKey key, will be included in the self-signed cert.
VIP6 net.IP
// Same as VIP6, but as uint64
VIP64 uint64
// Blob store - for loading/saving certs and keys. If nil, all is just in memory.
Config ConfStore
// base64URL encoding of the primary public key.
// Will be used in JWT header.
pub64 string
// Moved to base
// User name, based on service account or uid.
Name string
// Private key to use in both server and client authentication.
// ED22519: 32B
// EC256: DER
// RSA: DER
Priv []byte
// Explicit certificates (lego), key is hostname from file
//
CertMap map[string]*tls.Certificate
}
var certValidityPeriod = 100 * 365 * 24 * time.Hour
// Interface for very simple configuration and key loading.
// Can have a simple in-memory, fs implementation, as well
// as K8S, XDS or database backends.
//
// The name is hierachical, in case of K8S or Istio corresponds
// to the type, including namespace.
type ConfStore interface {
// Get a config blob by name
Get(name string) ([]byte, error)
// Save a config blob
Set(conf string, data []byte) error
// List the configs starting with a prefix, of a given type
List(name string, tp string) ([]string, error)
}
// SetVapid sets a new Vapid generator from EC256 public and private keys,
// in base64 uncompressed format.
func (v *Auth) SetVapid(publicKey64, privateKey64 string) {
publicUncomp, _ := base64.RawURLEncoding.DecodeString(publicKey64)
privateUncomp, _ := base64.RawURLEncoding.DecodeString(privateKey64)
x, y := elliptic.Unmarshal(elliptic.P256(), publicUncomp)
d := new(big.Int).SetBytes(privateUncomp)
pubkey := ecdsa.PublicKey{Curve: elliptic.P256(), X: x, Y: y}
pkey := ecdsa.PrivateKey{PublicKey: pubkey, D: d}
tlsCert, _, _ := v.generateSelfSigned("ec256", &pkey, "TODO")
// Required now
v.pub64 = publicKey64
v.PublicKey = publicUncomp
v.Priv = privateUncomp
v.PublicKey = elliptic.Marshal(elliptic.P256(), pkey.X, pkey.Y)
v.Priv = pkey.D.Bytes()
v.Cert = &tlsCert
}
//func (v *Auth) InitPrivate(kty string) {
//
//}
// NewAuth initializes the auth using environment, local files or the config store.
//
// If no private key is found, generate an EC256 key.
func NewAuth(cs ConfStore, name, domain string) *Auth {
if name == "" {
if os.Getenv("POD_NAME") != "" {
name = os.Getenv("POD_NAME") + "." + os.Getenv("POD_NAMESPACE")
} else {
name, _ = os.Hostname()
}
}
if domain == "" {
domain = os.Getenv("DOMAIN")
}
if domain == "" {
domain = "c1.webinf.info"
}
auth := &Auth{
Config: cs,
Name: name,
}
auth.TrustDomain = domain
auth.TrustedCertPool = x509.NewCertPool()
auth.initCert()
//if cs != nil {
// err := auth.loadCert()
// if err != nil {
// log.Println("Error loading cert: ", err)
// }
//}
//
//// For missing certs - generate new ones.
//auth.generateCert()
//auth.tlsCerts = append(auth.tlsCerts, *auth.EC256Cert)
c0 := auth.Cert
pk := c0.PrivateKey
var pubkey crypto.PublicKey
if priv, ok := pk.(*ecdsa.PrivateKey); ok {
auth.Priv = priv.D.Bytes()
auth.PublicKey = elliptic.Marshal(elliptic.P256(), priv.X, priv.Y) // starts with 0x04 == uncompressed curve
pubkey = priv.Public()
} else if priv, ok := pk.(*ed25519.PrivateKey); ok {
auth.Priv = *priv
edpub := meshauth.PublicKey(priv)
auth.PublicKey = edpub.(ed25519.PublicKey)
pubkey = edpub
} else if priv, ok := pk.(*rsa.PrivateKey); ok {
edpub := meshauth.PublicKey(priv)
auth.Priv = MarshalPrivateKey(priv)
auth.PublicKey = MarshalPublicKey(priv.Public())
pubkey = edpub
}
auth.VIP6 = Pub2VIP(auth.PublicKey)
auth.VIP64 = auth.NodeIDUInt(auth.PublicKey)
// Based on the primary EC256 key
auth.pub64 = base64.RawURLEncoding.EncodeToString(auth.PublicKey)
if auth.ID == "" {
auth.ID = IDFromPublicKey(pubkey)
}
auth.CertMap = auth.GetCerts()
return auth
}
func NewMeshAuth() *Auth {
a := &Auth{}
a.TrustedCertPool = x509.NewCertPool()
return a
}
func (a *Auth) leaf() *x509.Certificate {
if a.Cert == nil {
return nil
}
if a.Cert.Leaf == nil {
a.Cert.Leaf, _ = x509.ParseCertificate(a.Cert.Certificate[0])
}
return a.Cert.Leaf
}
// Host2ID concerts a Host/:authority or path parameter hostname to a node ID.
//
func (auth *Auth) Host2ID(host string) string {
col := strings.Index(host, ".")
if col > 0 {
host = host[0:col]
} else {
col = strings.Index(host, ":")
if col > 0 {
host = host[0:col]
}
}
return strings.ToUpper(host)
}
//func (kr *Auth) NewCertificate(ctx context.Context) error {
// if kr.CSRSigner == nil {
// return nil
// }
// // TODO: decode WorkloadCertificateConfig, use EC256 or RSA
// privPEM, csr, err := kr.NewCSR("rsa", kr.TrustDomain, "spiffe://"+kr.TrustDomain+"/ns/"+kr.Namespace+"/sa/"+kr.Name)
// if err != nil {
// return err
// }
// chain, err := kr.CSRSigner.CSRSign(ctx, csr, 24*3600)
// if err != nil {
// return err
// }
// certChain := strings.Join(chain, "\n")
//
// kp, err := tls.X509KeyPair([]byte(certChain), privPEM)
// kr.Cert = &kp
// kr.privPEM = privPEM
// kr.certPEM = []byte(certChain)
//
// if err == nil && len(kp.Certificate) > 0 {
// kp.Leaf, _ = x509.ParseCertificate(kp.Certificate[0])
//
// if !kp.Leaf.NotAfter.Before(time.Now()) {
// r, _ := x509.ParseCertificate(kp.Certificate[len(kp.Certificate)-1])
// log.Println("New Cert", "expires", kp.Leaf.NotAfter, "signer", r.Subject)
// }
// }
// return err
//}
const (
WorkloadCertDir = "/var/run/secrets/workload-spiffe-credentials"
// Different from typical Istio and CertManager key.pem - we can check both
privateKey = "private_key.pem"
// Also different, we'll check all. CertManager uses cert.pem
cert = "certificates.pem"
// This is derived from CA certs plus all TrustAnchors.
// In GKE, it is expected that Citadel roots will be configure using TrustConfig - so they are visible
// to all workloads including TD proxyless GRPC.
//
// Outside of GKE, this is loaded from the mesh.env - the mesh gate is responsible to keep it up to date.
WorkloadRootCAs = "ca_certificates.pem"
)
// SaveCerts will create certificate files as expected by gRPC and Istio, similar with the auto-created files.
//func (a *Auth) SaveCerts(outDir string) error {
// if outDir == "" {
// outDir = WorkloadCertDir
// }
// err := os.MkdirAll(outDir, 0755)
// // TODO: merge other roots as needed - this is Istio XDS server root.
// rootFile := filepath.Join(outDir, WorkloadRootCAs)
// if err != nil {
// return err
// }
//
// roots := ""
// err = ioutil.WriteFile(rootFile, []byte(roots), 0644)
// if err != nil {
// return err
// }
//
// keyFile := filepath.Join(outDir, privateKey)
// chainFile := filepath.Join(outDir, cert)
// os.MkdirAll(outDir, 0755)
// err = ioutil.WriteFile(keyFile, a.privPEM, 0660)
// if err != nil {
// return err
// }
// err = ioutil.WriteFile(chainFile, []byte(a.certPEM), 0660)
// if err != nil {
// return err
// }
// if os.Getuid() == 0 {
// os.Chown(outDir, 1337, 1337)
// os.Chown(keyFile, 1337, 1337)
// os.Chown(chainFile, 1337, 1337)
// }
//
// return nil
//}
// Get all known certificates from local files. This is used to support
// lego certificates and istio.
//
// "istio" is a special name, set if istio certs are found
//
func (auth *Auth) GetCerts() map[string]*tls.Certificate {
certMap := map[string]*tls.Certificate{}
if _, err := os.Stat("./etc/certs/key.pem"); !os.IsNotExist(err) {
crt, err := tls.LoadX509KeyPair("./etc/certs/cert-chain.pem", "./etc/certs/key.pem")
if err != nil {
log.Println("Failed to load system istio certs", err)
} else {
certMap["istio"] = &crt
if crt.Leaf != nil {
log.Println("Loaded istio cert ", crt.Leaf.URIs)
}
}
}
legoBase := os.Getenv("HOME") + "/.lego/certificates"
files, err := ioutil.ReadDir(legoBase)
if err == nil {
for _, ff := range files {
s := ff.Name()
if strings.HasSuffix(s, ".key") {
s = s[0 : len(s)-4]
base := legoBase + "/" + s
cert, err := tls.LoadX509KeyPair(base+".crt",
base+".key")
if err != nil {
log.Println("ACME: Failed to load ", s, err)
} else {
certMap[s] = &cert
log.Println("ACME: Loaded cert for ", s)
}
}
}
}
return certMap
}
// Sign - requires ECDSA primary key
func (auth *Auth) Sign(data []byte, sig []byte) {
hasher := crypto.SHA256.New()
hasher.Write(data) //[0:64]) // only public key, for debug
hash := hasher.Sum(nil)
c0 := auth.Cert
if ec, ok := c0.PrivateKey.(*ecdsa.PrivateKey); ok {
r, s, _ := ecdsa.Sign(rand.Reader, ec, hash)
copy(sig, r.Bytes())
copy(sig[32:], s.Bytes())
} else if ed, ok := c0.PrivateKey.(ed25519.PrivateKey); ok {
sig1, _ := ed.Sign(rand.Reader, hash, nil)
copy(sig, sig1)
}
}
func Verify(data []byte, pub []byte, sig []byte) error {
hasher := crypto.SHA256.New()
hasher.Write(data) //[0:64]) // only public key, for debug
hash := hasher.Sum(nil)
if len(pub) == 64 {
// Expects 0x4 prefix - we don't send the 4.
//x, y := elliptic.Unmarshal(curve, pub)
x := new(big.Int).SetBytes(pub[0:32])
y := new(big.Int).SetBytes(pub[32:64])
if !elliptic.P256().IsOnCurve(x, y) {
return errors.New("invalid public key")
}
pubKey := &ecdsa.PublicKey{Curve: elliptic.P256(), X: x, Y: y}
r := big.NewInt(0).SetBytes(sig[0:32])
s := big.NewInt(0).SetBytes(sig[32:64])
match := ecdsa.Verify(pubKey, hash, r, s)
if match {
return nil
} else {
return errors.New("failed to validate signature ")
}
} else if len(pub) == 32 {
edp := ed25519.PublicKey(pub)
if ed25519.Verify(edp, hash, sig) {
return nil
} else {
return errors.New("failed to validate signature")
}
}
return errors.New("unknown public key")
}
// Generate a config to be used in a HTTP client, using the primary identity and cert.
func (auth *Auth) GenerateTLSConfigClient() *tls.Config {
// see transport.go in http onceSetNextProtoDefaults
return &tls.Config{
// VerifyPeerCertificate used instead
InsecureSkipVerify: true,
Certificates: []tls.Certificate{*auth.Cert},
// not set on client !! Setting it also disables Auth !
//NextProtos: nextProtosH2,
}
}
// WIP: Attempt to get a signed certificate, using Istio protocol.
//func (auth *Auth) GetSignedCert(url string) error {
// if _, err := os.Stat("./etc/certs/key.pem"); !os.IsNotExist(err) {
// crt, err := tls.LoadX509KeyPair("./etc/certs/cert-chain.pem", "./etc/certs/key.pem")
// if err != nil {
// log.Println("Failed to load system istio certs", err)
// } else {
// //auth.RSACert = &crt
// auth.TlsCerts = append(auth.TlsCerts, crt)
// if crt.Leaf != nil {
// log.Println("Loaded istio cert ", crt.Leaf.URIs)
// }
// }
// }
//
// // Get token
// // Serialize the proto (raw varint)
// // Call the grpc ( raw, avoid dep), with token and mTLS
// // Save it as 'primary' cert.
//
// return nil
//}
var useED = false
// initCert will load a cert from env, and if not found create a new self-signed cert.
func (auth *Auth) initCert() {
auth.loadAuthCfg()
if auth.Cert != nil {
return // got a cert
}
var keyPEM, certPEM []byte
var tlsCert tls.Certificate
if useED {
_, edpk, _ := ed25519.GenerateKey(rand.Reader)
auth.ID = IDFromPublicKey(meshauth.PublicKey(edpk))
tlsCert, keyPEM, certPEM = auth.generateSelfSigned("ed25519", edpk, auth.Name+"."+auth.TrustDomain)
auth.Cert = &tlsCert
} else {
privk, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
auth.ID = IDFromPublicKey(meshauth.PublicKey(privk))
tlsCert, keyPEM, certPEM = auth.generateSelfSigned("ec256", privk, auth.Name+"."+auth.TrustDomain)
auth.Cert = &tlsCert
}
auth.SaveKubeconfig("kube.json", keyPEM, certPEM)
}
// SaveKubeconfig will save the current keys and config as a kube config file.
func (auth *Auth) SaveKubeconfig(name string, keyPEM []byte, certPEM []byte) {
kc := &KubeConfig{
ApiVersion: "v1",
Kind: "Config",
CurrentContext: "default",
Contexts: []KubeNamedContext{
{Name: "default",
Context: Context{
Cluster: "default",
User: auth.ID,
}},
},
Users: []KubeNamedUser{
{Name: auth.ID,
User: KubeUser{
ClientKeyData: keyPEM,
ClientCertificateData: certPEM,
},
},
},
Clusters: []KubeNamedCluster{},
}
kcb, _ := json.Marshal(kc)
if auth.Config != nil {
auth.Config.Set("kube.json", kcb)
}
}
// loadAuthCfg will attempt to find this node secrets in the store.
// Will try:
// - ./kube.json
// - ./secret/[NAME].[DOMAIN]
func (auth *Auth) loadAuthCfg() {
if auth.Config == nil {
return
}
rsaKey, _ := auth.Config.Get("key.pem")
rsaCert, _ := auth.Config.Get("cert-chain.pem")
// TODO: multiple roots
rootCert, _ := auth.Config.Get("root-cert.pem")
if rsaKey != nil && rsaCert != nil {
tlsCert, err := tls.X509KeyPair(rsaCert, rsaKey)
if err != nil {
log.Println("Invalid Istio cert ", err)
} else {
auth.Cert = &tlsCert
if rootCert != nil {
rootCAs, err := x509.ParseCertificates(rootCert)
if err == nil {
for _, c := range rootCAs {
auth.TrustedCertPool.AddCert(c)
}
} else {
log.Println("Failed to load roots ", err)
}
}
for n, c := range tlsCert.Certificate {
cert, err := x509.ParseCertificate(c)
if err != nil {
log.Println("Invalid Istio cert ", err)
continue
}
if n == 0 && len(cert.URIs) > 0 {
log.Println("ID ", cert.URIs[0], cert.Issuer,
cert.NotAfter)
// TODO: get cert fingerprint as well
//log.Println("Cert: ", cert)
// TODO: extract domain, ns, name
} else {
// org and name are set
log.Println("Cert: ", cert.Subject.Organization, cert.NotAfter)
}
}
return
}
}
// Single file - more convenient for upload
// Java supports PKCS12 ( p12, pfx)
kcfg, _ := auth.Config.Get("kube.json")
if kcfg == nil {
kcfg, _ = auth.Config.Get("secret/" + auth.Name + "." + auth.TrustDomain)
}
if kcfg == nil {
return
}
kube := &KubeConfig{}
err := json.Unmarshal(kcfg, kube)
if err != nil {
log.Println("Invalid kube config ", err)
return
}
if len(kube.Users) == 0 {
return
}
keyPEM := kube.Users[0].User.ClientKeyData
certPEM := kube.Users[0].User.ClientCertificateData
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
log.Println("Error loading cert")
return
}
// expect a single user
// TODO: default context or context env
//auth.TlsCerts = []tls.Certificate{tlsCert}
auth.Cert = &tlsCert
}
// Load the primary cert - expects a PEM key file
//
// Rejected formats:
// - PKCS12 (p12, pfx) - supported by Java. Too complex.
// - individual files - hard to manage
// -
func (auth *Auth) loadCert() error {
//keyPEM, _ := auth.Config.Get("ec256-key.pem")
//certPEM, _ := auth.Config.Get("ec256-cert.pem")
//if keyPEM != nil && certPEM != nil {
// tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
// if err != nil {
// return err
// }
// auth.EC256Cert = &tlsCert
//}
//edKey, _ := auth.Config.Get("ed25519-key.pem")
//edCert, _ := auth.Config.Get("ed25519-cert.pem")
//if edKey != nil && edCert != nil {
// tlsCert, err := tls.X509KeyPair(edCert, edKey)
// if err != nil {
// return err
// }
// auth.ED25519Cert = &tlsCert
//}
return nil
}
// generateCert will generate the keys and populate the PublicKey/Priv fields.
// Will set privateKey, Priv, PublicKey
// PublicKey, Priv should be saved
func (auth *Auth) generateCert() {
//var keyPEM []byte
//var certPEM []byte
//var tlsCert tls.Certificate
// The ID is currently based on the EC256 key. Will be included in cert
//if auth.EC256Cert != nil {
// auth.ID = IDFromPublicKey(PublicKey(auth.EC256Cert.PrivateKey))
//
//} else {
// privk, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
// auth.ID = IDFromPublicKey(PublicKey(privk))
// tlsCert, keyPEM, certPEM = auth.generateSelfSigned("ec256", privk, auth.Name+"."+auth.Domain)
// auth.EC256Cert = &tlsCert
//}
//if auth.ED25519Cert == nil {
// _, edpk, _ := ed25519.GenerateKey(rand.Reader)
// tlsCert, _, _ := auth.generateSelfSigned("ed25519", edpk, auth.Name+"."+auth.Domain)
// auth.ED25519Cert = &tlsCert
//}
//
//if auth.RSACert == nil {
// priv, _ := rsa.GenerateKey(rand.Reader, 2048)
// tlsCert, _, _ := auth.generateSelfSigned("rsa", priv, auth.Name+"."+auth.Domain)
// auth.RSACert = &tlsCert
//}
}
var (
MESH_NETWORK = []byte{0xFD, 0x00, 0x00, 0x00, 0x00, 0x00, 0, 0x00}
)
func (auth *Auth) NodeID() []byte {
return auth.VIP6[8:]
}
// Convert a public key to a VIP. This is the primary ID of the nodes.
// Primary format is the 64-byte EC256 public key.
//
// For RSA, the ASN.1 format of the byte[] is used.
// For ED, the 32-byte raw encoding.
func Pub2VIP(pub []byte) net.IP {
if pub == nil {
return nil
}
ip6 := make([]byte, 16)
copy(ip6, MESH_NETWORK)
binary.BigEndian.PutUint64(ip6[8:], Pub2ID(pub))
return net.IP(ip6)
}
func (auth *Auth) NodeIDUInt(pub []byte) uint64 {
return Pub2ID(pub)
}
var enc = base32.StdEncoding.WithPadding(base32.NoPadding)
// IDFromPublicKey returns a node ID based on the
// public key of the node - 52 bytes base32.
func IDFromPublicKey(key crypto.PublicKey) string {
m := MarshalPublicKey(key)
if len(m) > 32 {
sha256 := sha256.New()
sha256.Write(m)
m = sha256.Sum([]byte{}) // 302
}
return enc.EncodeToString(m)
}
func IDFromPublicKeyBytes(m []byte) string {
if len(m) > 32 {
sha256 := sha256.New()
sha256.Write(m)
m = sha256.Sum([]byte{}) // 302
}
return enc.EncodeToString(m)
}
func IDFromCert(c []*x509.Certificate) string {
if c == nil || len(c) == 0 {
return ""
}
key := c[0].PublicKey
m := MarshalPublicKey(key)
if len(m) > 32 {
sha256 := sha256.New()
sha256.Write(m)
m = sha256.Sum([]byte{}) // 302
}
return enc.EncodeToString(m)
}
// Generate a 8-byte identifier from a public key
func Pub2ID(pub []byte) uint64 {
if len(pub) > 65 {
sha256 := sha1.New()
sha256.Write(pub)
keysha := sha256.Sum([]byte{}) // 302
return binary.BigEndian.Uint64(keysha[len(keysha)-8:])
} else {
// For EC256 and ED - for now just the last bytes
return binary.BigEndian.Uint64(pub[len(pub)-8:])
}
}
func RawToCertChain(rawCerts [][]byte) ([]*x509.Certificate, error) {
chain := make([]*x509.Certificate, len(rawCerts))
for i := 0; i < len(rawCerts); i++ {
cert, err := x509.ParseCertificate(rawCerts[i])
if err != nil {
return nil, err
}
chain[i] = cert
}
return chain, nil
}
// PubKeyFromCertChain verifies the certificate chain and extract the remote's public key.
func PubKeyFromCertChain(chain []*x509.Certificate) (crypto.PublicKey, error) {
if chain == nil || len(chain) == 0 {
}
cert := chain[0]
// Self-signed certificate
if len(chain) == 1 {
pool := x509.NewCertPool()
pool.AddCert(cert)
if _, err := cert.Verify(x509.VerifyOptions{Roots: pool}); err != nil {
// If we return an x509 error here, it will be sent on the wire.
// Wrap the error to avoid that.
return nil, fmt.Errorf("certificate verification failed: %s", err)
}
} else {
//
pool := x509.NewCertPool()
pool.AddCert(chain[len(chain)-1])
if _, err := cert.Verify(x509.VerifyOptions{Roots: pool}); err != nil {
// If we return an x509 error here, it will be sent on the wire.
// Wrap the error to avoid that.
return nil, fmt.Errorf("chain certificate verification failed: %s", err)
}
}
// IPFS uses a key embedded in a custom extension, and verifies the public key of the cert is signed
// with the node public key
// This transport is instead based on standard certs/TLS
key := cert.PublicKey
if ec, ok := key.(*ecdsa.PublicKey); ok {
return ec, nil
}
if rsak, ok := key.(*rsa.PublicKey); ok {
return rsak, nil
}
if ed, ok := key.(ed25519.PublicKey); ok {
return ed, nil
}
return nil, errors.New("unknown public key")
}
// Return the self identity. Currently it's using the VIP6 format - may change.
// This is used in Message 'From' and in ReqContext.
func (a *Auth) Self() string {
return a.VIP6.String()
}
func (auth *Auth) genCSR(prefix string, org string, priv crypto.PrivateKey, sans ...string) []byte {
// Will be based on the JWT
template := &x509.CertificateRequest{}
csrBytes, _ := x509.CreateCertificateRequest(rand.Reader, template, priv)
encodeMsg := "CERTIFICATE REQUEST"
csrPem := pem.EncodeToMemory(&pem.Block{Type: encodeMsg, Bytes: csrBytes})
return csrPem
}
func (auth *Auth) SignCSR(csrBytes []byte, org string, sans ...string) ([]byte, error) {
// Will be based on the JWT
// Istio uses PEM
block, _ := pem.Decode(csrBytes)
if block == nil {
return nil, fmt.Errorf("certificate signing request is not properly encoded")
}
csr, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse X.509 certificate signing request")
}
certDER := auth.signCertDER(csr.PublicKey, auth.Cert.PrivateKey, sans...)
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
return certPEM, nil
}
func (auth *Auth) signCertDER(pub crypto.PublicKey, caPrivate crypto.PrivateKey, sans ...string) []byte {
var notBefore time.Time
notBefore = time.Now().Add(-1 * time.Hour)
notAfter := notBefore.Add(365 * 24 * time.Hour)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, _ := rand.Int(rand.Reader, serialNumberLimit)
template := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
CommonName: sans[0],
Organization: []string{auth.TrustDomain},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
BasicConstraintsValid: true,
DNSNames: sans,
//IPAddresses: []net.IP{auth.VIP6},
}
// IPFS:
//certKeyPub, err := x509.MarshalPKIXPublicKey(certKey.Public())
//signature, err := sk.Sign(append([]byte(certificatePrefix), certKeyPub...))
//value, err := asn1.Marshal(signedKey{
// PubKey: keyBytes,
// Signature: signature,
//})
certDER, err := x509.CreateCertificate(rand.Reader, &template, &template, pub, caPrivate)
if err != nil {
panic(err)
}
return certDER
}
// Generate and save the primary self-signed Certificate
func (auth *Auth) generateSelfSigned(prefix string, priv crypto.PrivateKey, sans ...string) (tls.Certificate, []byte, []byte) {
return auth.SignCert(priv, priv, sans...)
}
func (auth *Auth) SignCert(priv crypto.PrivateKey, ca crypto.PrivateKey, sans ...string) (tls.Certificate, []byte, []byte) {
pub := meshauth.PublicKey(priv)
certDER := auth.signCertDER(pub, ca, sans...)
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certDER})
ecb, _ := x509.MarshalPKCS8PrivateKey(priv)
keyPEM := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: ecb})
tlsCert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
log.Println("Error generating cert ", err)
}
return tlsCert, keyPEM, certPEM
}
func MarshalPublicKey(key crypto.PublicKey) []byte {
if k, ok := key.(ed25519.PublicKey); ok {
return []byte(k)
}
if k, ok := key.(*ecdsa.PublicKey); ok {
return elliptic.Marshal(elliptic.P256(), k.X, k.Y)
// starts with 0x04 == uncompressed curve
}
if k, ok := key.(*rsa.PublicKey); ok {
bk := x509.MarshalPKCS1PublicKey(k)
return bk
}
if k, ok := key.([]byte); ok {
if len(k) == 64 || len(k) == 32 {
return k
}
}
return nil
}
func MarshalPrivateKey(key crypto.PrivateKey) []byte {
if k, ok := key.(*rsa.PrivateKey); ok {
bk := x509.MarshalPKCS1PrivateKey(k)
return bk
}
return nil
}
// Convert a PublicKey to a marshalled format - in the raw format.
// - 32 byte ED25519
// - 65 bytes EC256 ( 0x04 prefix )
// - DER RSA key (PKCS1)
func PublicKeyBytesRaw(key crypto.PublicKey) []byte {
if ec, ok := key.(*ecdsa.PublicKey); ok {
// starts with 0x04 == uncompressed curve
pubbytes := elliptic.Marshal(ec.Curve, ec.X, ec.Y)
return pubbytes
}
if rsak, ok := key.(*rsa.PublicKey); ok {
pubbytes := x509.MarshalPKCS1PublicKey(rsak)
return pubbytes
}
if ed, ok := key.(ed25519.PublicKey); ok {
return []byte(ed)
}
return nil
}
var (
oidExtensionSubjectAltName = []int{2, 5, 29, 17}
)
const (
nameTypeEmail = 1
nameTypeDNS = 2
nameTypeURI = 6
nameTypeIP = 7
)
func getSANExtension(c *x509.Certificate) []byte {
for _, e := range c.Extensions {
if e.Id.Equal(oidExtensionSubjectAltName) {
return e.Value
}
}
return nil
}
// http-related auth
func GetPeerCertBytes(r *http.Request) []byte {
if r.TLS != nil {
if len(r.TLS.PeerCertificates) > 0 {
pke, ok := r.TLS.PeerCertificates[0].PublicKey.(*ecdsa.PublicKey)
if ok {
return elliptic.Marshal(elliptic.P256(), pke.X, pke.Y)
}
rsap, ok := r.TLS.PeerCertificates[0].PublicKey.(*rsa.PublicKey)
if ok {
return x509.MarshalPKCS1PublicKey(rsap)
}
}
}
return nil
}
func GetResponseCertBytes(r *http.Response) []byte {
if r.TLS != nil {
if len(r.TLS.PeerCertificates) > 0 {
pke, ok := r.TLS.PeerCertificates[0].PublicKey.(*ecdsa.PublicKey)
if ok {
return elliptic.Marshal(elliptic.P256(), pke.X, pke.Y)
}
rsap, ok := r.TLS.PeerCertificates[0].PublicKey.(*rsa.PublicKey)
if ok {
return x509.MarshalPKCS1PublicKey(rsap)
}
}
}
return nil
}
func GetSAN(c *x509.Certificate) ([]string, error) {
extension := getSANExtension(c)
dns := []string{}
// RFC 5280, 4.2.1.6
// SubjectAltName ::= GeneralNames
//
// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
//
// GeneralName ::= CHOICE {
// otherName [0] OtherName,
// rfc822Name [1] IA5String,
// dNSName [2] IA5String,
// x400Address [3] ORAddress,
// directoryName [4] Name,
// ediPartyName [5] EDIPartyName,
// uniformResourceIdentifier [6] IA5String,
// iPAddress [7] OCTET STRING,
// registeredID [8] OBJECT IDENTIFIER }