This repository has been archived by the owner on Feb 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
gortr.go
831 lines (725 loc) · 20.6 KB
/
gortr.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
package main
import (
"bytes"
"crypto/ecdsa"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"flag"
"fmt"
rtr "github.com/cloudflare/gortr/lib"
"github.com/cloudflare/gortr/prefixfile"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
log "github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
"io"
"io/ioutil"
"net"
"net/http"
"os"
"os/signal"
"runtime"
"strings"
"sync"
"syscall"
"time"
)
const (
ENV_SSH_PASSWORD = "GORTR_SSH_PASSWORD"
ENV_SSH_KEY = "GORTR_SSH_AUTHORIZEDKEYS"
METHOD_NONE = iota
METHOD_PASSWORD
METHOD_KEY
)
var (
version = ""
buildinfos = ""
AppVersion = "GoRTR " + version + " " + buildinfos
MetricsAddr = flag.String("metrics.addr", ":8080", "Metrics address")
MetricsPath = flag.String("metrics.path", "/metrics", "Metrics path")
ExportPath = flag.String("export.path", "/rpki.json", "Export path")
ExportSign = flag.String("export.sign", "", "Sign export with key")
RTRVersion = flag.Int("protocol", 1, "RTR protocol version")
SessionID = flag.Int("rtr.sessionid", -1, "Set session ID (if < 0: will be randomized)")
RefreshRTR = flag.Int("rtr.refresh", 3600, "Refresh interval")
RetryRTR = flag.Int("rtr.retry", 600, "Retry interval")
ExpireRTR = flag.Int("rtr.expire", 7200, "Expire interval")
Bind = flag.String("bind", ":8282", "Bind address")
BindTLS = flag.String("tls.bind", "", "Bind address for TLS")
TLSCert = flag.String("tls.cert", "", "Certificate path")
TLSKey = flag.String("tls.key", "", "Private key path")
BindSSH = flag.String("ssh.bind", "", "Bind address for SSH")
SSHKey = flag.String("ssh.key", "private.pem", "SSH host key")
SSHAuthEnablePassword = flag.Bool("ssh.method.password", false, "Enable password auth")
SSHAuthUser = flag.String("ssh.auth.user", "rpki", "SSH user")
SSHAuthPassword = flag.String("ssh.auth.password", "", fmt.Sprintf("SSH password (if blank, will use envvar %v)", ENV_SSH_PASSWORD))
SSHAuthEnableKey = flag.Bool("ssh.method.key", false, "Enable key auth")
SSHAuthKeysBypass = flag.Bool("ssh.auth.key.bypass", false, "Accept any SSH key")
SSHAuthKeysList = flag.String("ssh.auth.key.file", "", fmt.Sprintf("Authorized SSH key file (if blank, will use envvar %v", ENV_SSH_KEY))
TimeCheck = flag.Bool("checktime", true, "Check if file is still valid")
Verify = flag.Bool("verify", true, "Check signature using provided public key (disable by passing -verify=false)")
PublicKey = flag.String("verify.key", "cf.pub", "Public key path (PEM file)")
CacheBin = flag.String("cache", "https://rpki.cloudflare.com/rpki.json", "URL of the cached JSON data")
Etag = flag.Bool("etag", true, "Enable Etag header")
UserAgent = flag.String("useragent", fmt.Sprintf("Cloudflare-%v (+https://github.com/cloudflare/gortr)", AppVersion), "User-Agent header")
RefreshInterval = flag.Int("refresh", 600, "Refresh interval in seconds")
MaxConn = flag.Int("maxconn", 0, "Max simultaneous connections (0 to disable limit)")
SendNotifs = flag.Bool("notifications", true, "Send notifications to clients")
Slurm = flag.String("slurm", "", "Slurm configuration file (filters and assertions)")
SlurmRefresh = flag.Bool("slurm.refresh", true, "Refresh along the cache")
LogLevel = flag.String("loglevel", "info", "Log level")
Version = flag.Bool("version", false, "Print version")
NumberOfROAs = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "rpki_roas",
Help: "Number of ROAS.",
},
[]string{"ip_version", "filtered", "path"},
)
LastRefresh = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "rpki_refresh",
Help: "Last successfull request for the given URL.",
},
[]string{"path"},
)
LastChange = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "rpki_change",
Help: "Last change.",
},
[]string{"path"},
)
RefreshStatusCode = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "refresh_requests_total",
Help: "Total number of HTTP requests by status code",
},
[]string{"path", "code"},
)
ClientsMetric = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "rtr_clients",
Help: "Number of clients connected.",
},
[]string{"bind"},
)
PDUsRecv = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "rtr_pdus",
Help: "PDU received.",
},
[]string{"type"},
)
protoverToLib = map[int]uint8{
0: rtr.PROTOCOL_VERSION_0,
1: rtr.PROTOCOL_VERSION_1,
}
authToId = map[string]int{
"none": METHOD_NONE,
"password": METHOD_PASSWORD,
//"key": METHOD_KEY,
}
)
func initMetrics() {
prometheus.MustRegister(NumberOfROAs)
prometheus.MustRegister(LastChange)
prometheus.MustRegister(LastRefresh)
prometheus.MustRegister(RefreshStatusCode)
prometheus.MustRegister(ClientsMetric)
prometheus.MustRegister(PDUsRecv)
}
func metricHTTP() {
http.Handle(*MetricsPath, promhttp.Handler())
log.Fatal(http.ListenAndServe(*MetricsAddr, nil))
}
func (s *state) fetchFile(file string) ([]byte, error) {
var f io.Reader
var err error
if len(file) > 8 && (file[0:7] == "http://" || file[0:8] == "https://") {
// Copying base of DefaultTransport from https://golang.org/src/net/http/transport.go
// There is a proposal for a Clone of
tr := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
ProxyConnectHeader: map[string][]string{},
}
// Keep User-Agent in proxy request
tr.ProxyConnectHeader.Set("User-Agent", s.userAgent)
client := &http.Client{Transport: tr}
req, err := http.NewRequest("GET", file, nil)
req.Header.Set("User-Agent", s.userAgent)
req.Header.Set("Accept", "text/json")
etag, ok := s.etags[file]
if s.enableEtags && ok {
req.Header.Set("If-None-Match", etag)
}
proxyurl, err := http.ProxyFromEnvironment(req)
if err != nil {
return nil, err
}
proxyreq := http.ProxyURL(proxyurl)
tr.Proxy = proxyreq
if err != nil {
return nil, err
}
fhttp, err := client.Do(req)
if err != nil {
return nil, err
}
RefreshStatusCode.WithLabelValues(file, fmt.Sprintf("%d", fhttp.StatusCode)).Inc()
if fhttp.StatusCode == 304 {
LastRefresh.WithLabelValues(file).Set(float64(s.lastts.UnixNano() / 1e9))
return nil, HttpNotModified{
File: file,
}
} else if fhttp.StatusCode != 200 {
delete(s.etags, file)
return nil, fmt.Errorf("HTTP %s", fhttp.Status)
}
LastRefresh.WithLabelValues(file).Set(float64(s.lastts.UnixNano() / 1e9))
f = fhttp.Body
newEtag := fhttp.Header.Get("ETag")
if !s.enableEtags || newEtag == "" || newEtag != s.etags[file] {
s.etags[file] = newEtag
} else {
return nil, IdenticalEtag{
File: file,
Etag: newEtag,
}
}
} else {
f, err = os.Open(file)
if err != nil {
return nil, err
}
}
data, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
return data, nil
}
func checkFile(data []byte) ([]byte, error) {
hsum := sha256.Sum256(data)
return hsum[:], nil
}
func decodeJSON(data []byte) (*prefixfile.ROAList, error) {
buf := bytes.NewBuffer(data)
dec := json.NewDecoder(buf)
var roalistjson prefixfile.ROAList
err := dec.Decode(&roalistjson)
return &roalistjson, err
}
func processData(roalistjson []prefixfile.ROAJson) ([]rtr.ROA, int, int, int) {
filterDuplicates := make(map[string]bool)
roalist := make([]rtr.ROA, 0)
var count int
var countv4 int
var countv6 int
for _, v := range roalistjson {
prefix, err := v.GetPrefix2()
if err != nil {
log.Error(err)
continue
}
asn, err := v.GetASN2()
if err != nil {
log.Error(err)
continue
}
count++
if prefix.IP.To4() != nil {
countv4++
} else if prefix.IP.To16() != nil {
countv6++
}
key := fmt.Sprintf("%s,%d,%d", prefix, asn, v.Length)
_, exists := filterDuplicates[key]
if !exists {
filterDuplicates[key] = true
} else {
continue
}
roa := rtr.ROA{
Prefix: *prefix,
ASN: asn,
MaxLen: v.Length,
}
roalist = append(roalist, roa)
}
return roalist, count, countv4, countv6
}
type IdenticalFile struct {
File string
}
func (e IdenticalFile) Error() string {
return fmt.Sprintf("File %s is identical to the previous version", e.File)
}
type HttpNotModified struct {
File string
}
func (e HttpNotModified) Error() string {
return fmt.Sprintf("HTTP 304 Not modified for %s", e.File)
}
type IdenticalEtag struct {
File string
Etag string
}
func (e IdenticalEtag) Error() string {
return fmt.Sprintf("File %s is identical according to Etag: %s", e.File, e.Etag)
}
func (s *state) updateFile(file string) error {
log.Debugf("Refreshing cache from %s", file)
s.lastts = time.Now().UTC()
data, err := s.fetchFile(file)
if err != nil {
return err
}
hsum, _ := checkFile(data)
if s.lasthash != nil {
cres := bytes.Compare(s.lasthash, hsum)
if cres == 0 {
return IdenticalFile{File: file}
}
}
s.lastchange = time.Now().UTC()
s.lastdata = data
roalistjson, err := decodeJSON(s.lastdata)
if err != nil {
return err
}
if s.checktime {
validtime := time.Unix(int64(roalistjson.Metadata.Valid), 0).UTC()
if time.Now().UTC().After(validtime) {
return errors.New(fmt.Sprintf("File is expired: %v", validtime))
}
}
if s.verify {
log.Debugf("Verifying signature in %v", file)
if roalistjson.Metadata.SignatureDate == "" || roalistjson.Metadata.Signature == "" {
return errors.New("No signatures in file")
}
validdata, validdatatime, err := roalistjson.CheckFile(s.pubkey)
if err != nil {
return err
}
if !(validdata && (validdatatime || !s.checktime)) {
return errors.New("Invalid signatures")
}
log.Debugf("Signature verified")
}
roasjson := roalistjson.Data
if s.slurm != nil {
kept, removed := s.slurm.FilterOnROAs(roasjson)
asserted := s.slurm.AssertROAs()
log.Infof("Slurm filtering: %v kept, %v removed, %v asserted", len(kept), len(removed), len(asserted))
roasjson = append(kept, asserted...)
}
s.lockJson.Lock()
s.exported = prefixfile.ROAList{
Metadata: prefixfile.MetaData{
Counts: len(roasjson),
Generated: roalistjson.Metadata.Generated,
Valid: roalistjson.Metadata.Valid,
/*Signature: roalistjson.Metadata.Signature,
SignatureDate: roalistjson.Metadata.SignatureDate,*/
},
Data: roasjson,
}
if s.key != nil {
signdate, sign, err := s.exported.Sign(s.key)
if err != nil {
log.Error(err)
}
s.exported.Metadata.Signature = sign
s.exported.Metadata.SignatureDate = signdate
}
s.lockJson.Unlock()
roas, count, countv4, countv6 := processData(roasjson)
if err != nil {
return err
}
log.Infof("New update (%v uniques, %v total prefixes). %v bytes. Updating sha256 hash %x -> %x",
len(roas), count, len(s.lastconverted), s.lasthash, hsum)
s.lasthash = hsum
s.server.AddROAs(roas)
sessid, _ := s.server.GetSessionId(nil)
serial, _ := s.server.GetCurrentSerial(sessid)
log.Infof("Updated added, new serial %v", serial)
if s.sendNotifs {
log.Debugf("Sending notifications to clients")
s.server.NotifyClientsLatest()
}
if s.metricsEvent != nil {
var countv4_dup int
var countv6_dup int
for _, roa := range roas {
if roa.Prefix.IP.To4() != nil {
countv4_dup++
} else if roa.Prefix.IP.To16() != nil {
countv6_dup++
}
}
s.metricsEvent.UpdateMetrics(countv4, countv6, countv4_dup, countv6_dup, s.lastchange, s.lastts, file)
}
return nil
}
func (s *state) updateSlurm(file string) error {
log.Debugf("Refreshing slurm from %v", file)
data, err := s.fetchFile(file)
if err != nil {
return err
}
buf := bytes.NewBuffer(data)
slurm, err := prefixfile.DecodeJSONSlurm(buf)
if err != nil {
return err
}
s.slurm = slurm
return nil
}
func (s *state) routineUpdate(file string, interval int, slurmFile string) {
log.Debugf("Starting refresh routine (file: %v, interval: %vs, slurm: %v)", file, interval, slurmFile)
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGHUP)
for {
delay := time.NewTimer(time.Duration(interval) * time.Second)
select {
case <-delay.C:
case <-signals:
log.Debug("Received HUP signal")
}
delay.Stop()
if slurmFile != "" {
err := s.updateSlurm(slurmFile)
if err != nil {
switch err.(type) {
case HttpNotModified:
log.Info(err)
case IdenticalEtag:
log.Info(err)
default:
log.Errorf("Slurm: %v", err)
}
}
}
err := s.updateFile(file)
if err != nil {
switch err.(type) {
case HttpNotModified:
log.Info(err)
case IdenticalEtag:
log.Info(err)
case IdenticalFile:
log.Info(err)
default:
log.Errorf("Error updating: %v", err)
}
}
}
}
func (s *state) exporter(wr http.ResponseWriter, r *http.Request) {
s.lockJson.RLock()
toExport := s.exported
s.lockJson.RUnlock()
enc := json.NewEncoder(wr)
enc.Encode(toExport)
}
type state struct {
lastdata []byte
lastconverted []byte
lasthash []byte
lastchange time.Time
lastts time.Time
sendNotifs bool
userAgent string
etags map[string]string
enableEtags bool
server *rtr.Server
metricsEvent *metricsEvent
exported prefixfile.ROAList
lockJson *sync.RWMutex
key *ecdsa.PrivateKey
slurm *prefixfile.SlurmConfig
pubkey *ecdsa.PublicKey
verify bool
checktime bool
}
type metricsEvent struct {
}
func (m *metricsEvent) ClientConnected(c *rtr.Client) {
ClientsMetric.WithLabelValues(c.GetLocalAddress().String()).Inc()
}
func (m *metricsEvent) ClientDisconnected(c *rtr.Client) {
ClientsMetric.WithLabelValues(c.GetLocalAddress().String()).Dec()
}
func (m *metricsEvent) HandlePDU(c *rtr.Client, pdu rtr.PDU) {
PDUsRecv.WithLabelValues(
strings.ToLower(
strings.Replace(
rtr.TypeToString(
pdu.GetType()),
" ",
"_", -1))).Inc()
}
func (m *metricsEvent) UpdateMetrics(numIPv4 int, numIPv6 int, numIPv4filtered int, numIPv6filtered int, changed time.Time, refreshed time.Time, file string) {
NumberOfROAs.WithLabelValues("ipv4", "filtered", file).Set(float64(numIPv4filtered))
NumberOfROAs.WithLabelValues("ipv4", "unfiltered", file).Set(float64(numIPv4))
NumberOfROAs.WithLabelValues("ipv6", "filtered", file).Set(float64(numIPv6filtered))
NumberOfROAs.WithLabelValues("ipv6", "unfiltered", file).Set(float64(numIPv6))
LastChange.WithLabelValues(file).Set(float64(changed.UnixNano() / 1e9))
}
func ReadPublicKey(key []byte, isPem bool) (*ecdsa.PublicKey, error) {
if isPem {
block, _ := pem.Decode(key)
key = block.Bytes
}
k, err := x509.ParsePKIXPublicKey(key)
if err != nil {
return nil, err
}
kconv, ok := k.(*ecdsa.PublicKey)
if !ok {
return nil, errors.New("Not EDCSA public key")
}
return kconv, nil
}
func ReadKey(key []byte, isPem bool) (*ecdsa.PrivateKey, error) {
if isPem {
block, _ := pem.Decode(key)
key = block.Bytes
}
k, err := x509.ParseECPrivateKey(key)
if err != nil {
return nil, err
}
return k, nil
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
flag.Parse()
if *Version {
fmt.Println(AppVersion)
os.Exit(0)
}
lvl, _ := log.ParseLevel(*LogLevel)
log.SetLevel(lvl)
deh := &rtr.DefaultRTREventHandler{
Log: log.StandardLogger(),
}
sc := rtr.ServerConfiguration{
ProtocolVersion: protoverToLib[*RTRVersion],
SessId: *SessionID,
KeepDifference: 3,
Log: log.StandardLogger(),
RefreshInterval: uint32(*RefreshRTR),
RetryInterval: uint32(*RetryRTR),
ExpireInterval: uint32(*ExpireRTR),
}
var me *metricsEvent
var enableHTTP bool
if *MetricsAddr != "" {
initMetrics()
me = &metricsEvent{}
enableHTTP = true
}
server := rtr.NewServer(sc, me, deh)
deh.SetROAManager(server)
var pubkey *ecdsa.PublicKey
if *Verify {
pubkeyBytes, err := ioutil.ReadFile(*PublicKey)
if err != nil {
log.Fatal(err)
}
pubkey, err = ReadPublicKey(pubkeyBytes, true)
if err != nil {
log.Fatal(err)
}
}
s := state{
server: server,
metricsEvent: me,
sendNotifs: *SendNotifs,
pubkey: pubkey,
verify: *Verify,
checktime: *TimeCheck,
userAgent: *UserAgent,
etags: make(map[string]string),
enableEtags: *Etag,
lockJson: &sync.RWMutex{},
}
if *ExportSign != "" {
keyFile, err := os.Open(*ExportSign)
if err != nil {
log.Fatal(err)
}
keyBytes, err := ioutil.ReadAll(keyFile)
if err != nil {
log.Fatal(err)
}
keyFile.Close()
keyDec, err := ReadKey(keyBytes, true)
if err != nil {
log.Fatal(err)
}
s.key = keyDec
}
if enableHTTP {
if *ExportPath != "" {
http.HandleFunc(*ExportPath, s.exporter)
}
go metricHTTP()
}
if *Bind == "" && *BindTLS == "" && *BindSSH == "" {
log.Fatalf("Specify at least a bind address")
}
if *Bind != "" {
go func() {
sessid, _ := server.GetSessionId(nil)
log.Infof("GoRTR Server started (sessionID:%d, refresh:%d, retry:%d, expire:%d)", sessid, sc.RefreshInterval, sc.RetryInterval, sc.ExpireInterval)
err := server.Start(*Bind)
if err != nil {
log.Fatal(err)
}
}()
}
if *BindTLS != "" {
cert, err := tls.LoadX509KeyPair(*TLSCert, *TLSKey)
if err != nil {
log.Fatal(err)
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{cert},
}
go func() {
err := server.StartTLS(*BindTLS, &tlsConfig)
if err != nil {
log.Fatal(err)
}
}()
}
if *BindSSH != "" {
sshkey, err := ioutil.ReadFile(*SSHKey)
if err != nil {
log.Fatal(err)
}
private, err := ssh.ParsePrivateKey(sshkey)
if err != nil {
log.Fatal("Failed to parse private key: ", err)
}
sshConfig := ssh.ServerConfig{}
log.Infof("Enabling ssh with the following authentications: password=%v, key=%v", *SSHAuthEnablePassword, *SSHAuthEnableKey)
if *SSHAuthEnablePassword {
password := *SSHAuthPassword
if password == "" {
password = os.Getenv(ENV_SSH_PASSWORD)
}
sshConfig.PasswordCallback = func(conn ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
log.Infof("Connected (ssh-password): %v/%v", conn.User(), conn.RemoteAddr())
if conn.User() != *SSHAuthUser || !bytes.Equal(password, []byte(*SSHAuthPassword)) {
log.Warnf("Wrong user or password for %v/%v. Disconnecting.", conn.User(), conn.RemoteAddr())
return nil, errors.New("Wrong user or password")
}
return &ssh.Permissions{
CriticalOptions: make(map[string]string),
Extensions: make(map[string]string),
}, nil
}
}
if *SSHAuthEnableKey {
var sshClientKeysToDecode string
if *SSHAuthKeysList == "" {
sshClientKeysToDecode = os.Getenv(ENV_SSH_KEY)
} else {
sshClientKeysToDecodeBytes, err := ioutil.ReadFile(*SSHAuthKeysList)
if err != nil {
log.Fatal(err)
}
sshClientKeysToDecode = string(sshClientKeysToDecodeBytes)
}
sshClientKeys := strings.Split(sshClientKeysToDecode, "\n")
sshConfig.PublicKeyCallback = func(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
keyBase64 := base64.RawStdEncoding.EncodeToString(key.Marshal())
if !*SSHAuthKeysBypass {
var noKeys bool
for i, k := range sshClientKeys {
if k == "" {
continue
}
if strings.HasPrefix(fmt.Sprintf("%v %v", key.Type(), keyBase64), k) {
log.Infof("Connected (ssh-key): %v/%v with key %v %v (matched with line %v)",
conn.User(), conn.RemoteAddr(), key.Type(), keyBase64, i+1)
noKeys = true
break
}
}
if !noKeys {
log.Warnf("No key for %v/%v %v %v. Disconnecting.", conn.User(), conn.RemoteAddr(), key.Type(), keyBase64)
return nil, errors.New("Key not found")
}
} else {
log.Infof("Connected (ssh-key): %v/%v with key %v %v", conn.User(), conn.RemoteAddr(), key.Type(), keyBase64)
}
return &ssh.Permissions{
CriticalOptions: make(map[string]string),
Extensions: make(map[string]string),
}, nil
}
}
if !(*SSHAuthEnableKey || *SSHAuthEnablePassword) {
sshConfig.NoClientAuth = true
}
sshConfig.AddHostKey(private)
go func() {
err := server.StartSSH(*BindSSH, &sshConfig)
if err != nil {
log.Fatal(err)
}
}()
}
slurmFile := *Slurm
if slurmFile != "" {
err := s.updateSlurm(slurmFile)
if err != nil {
switch err.(type) {
case HttpNotModified:
log.Info(err)
case IdenticalEtag:
log.Info(err)
default:
log.Errorf("Slurm: %v", err)
}
}
if !*SlurmRefresh {
slurmFile = ""
}
}
err := s.updateFile(*CacheBin)
if err != nil {
switch err.(type) {
case HttpNotModified:
log.Info(err)
case IdenticalFile:
log.Info(err)
case IdenticalEtag:
log.Info(err)
default:
log.Errorf("Error updating: %v", err)
}
}
s.routineUpdate(*CacheBin, *RefreshInterval, slurmFile)
}