forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
1675 lines (1509 loc) · 51.4 KB
/
service.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
/*
Copyright 2015-2017 Gravitational, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Package service implements teleport running service, takes care
// of initialization, cleanup and shutdown procedures
package service
import (
"context"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/pprof"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"time"
"golang.org/x/crypto/ssh"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/auth/native"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/backend/boltbk"
"github.com/gravitational/teleport/lib/backend/dir"
"github.com/gravitational/teleport/lib/backend/dynamo"
"github.com/gravitational/teleport/lib/backend/etcdbk"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/events/dynamoevents"
"github.com/gravitational/teleport/lib/events/filesessions"
"github.com/gravitational/teleport/lib/events/s3sessions"
"github.com/gravitational/teleport/lib/limiter"
"github.com/gravitational/teleport/lib/multiplexer"
"github.com/gravitational/teleport/lib/reversetunnel"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/srv/regular"
"github.com/gravitational/teleport/lib/state"
"github.com/gravitational/teleport/lib/system"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/web"
"github.com/gravitational/trace"
"github.com/gravitational/roundtrip"
"github.com/jonboulle/clockwork"
"github.com/pborman/uuid"
"github.com/prometheus/client_golang/prometheus"
"github.com/sirupsen/logrus"
)
var log = logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentProcess,
})
const (
// AuthIdentityEvent is generated when the Auth Servers identity has been
// initialized in the backend.
AuthIdentityEvent = "AuthIdentity"
// ProxyIdentityEvent is generated by the supervisor when the proxy's
// identity has been registered with the Auth Server.
ProxyIdentityEvent = "ProxyIdentity"
// SSHIdentityEvent is generated when node's identity has been registered
// with the Auth Server.
SSHIdentityEvent = "SSHIdentity"
// DELETE IN: 2.6.0
// AuthSSHReady is generated when the Auth Server has initialized the
// HTTP-over-SSH endpoint and is ready to start accepting connections.
AuthSSHReady = "AuthSSHReady"
// AuthTLSReady is generated when the Auth Server has initialized the
// TLS Mutual Auth endpoint and is ready to start accepting connections.
AuthTLSReady = "AuthTLSReady"
// ProxyWebServerReady is generated when the proxy has initialized the web
// server and is ready to start accepting connections.
ProxyWebServerReady = "ProxyWebServerReady"
// ProxyReverseTunnelReady is generated when the proxy has initialized the
// reverse tunnel server and is ready to start accepting connections.
ProxyReverseTunnelReady = "ProxyReverseTunnelReady"
// ProxySSHReady is generated when the proxy has initialized a SSH server
// and is ready to start accepting connections.
ProxySSHReady = "ProxySSHReady"
// NodeReady is generated when the Teleport node has initialized a SSH server
// and is ready to start accepting SSH connections.
NodeSSHReady = "NodeReady"
// TeleportExitEvent is generated when the Teleport process begins closing
// all listening sockets and exiting.
TeleportExitEvent = "TeleportExit"
)
// RoleConfig is a configuration for a server role (either proxy or node)
type RoleConfig struct {
DataDir string
HostUUID string
HostName string
AuthServers []utils.NetAddr
Auth AuthConfig
Console io.Writer
}
// Connector has all resources process needs to connect
// to other parts of the cluster: client and identity
type Connector struct {
Identity *auth.Identity
Client *auth.Client
}
// TeleportProcess structure holds the state of the Teleport daemon, controlling
// execution and configuration of the teleport services: ssh, auth and proxy.
type TeleportProcess struct {
clockwork.Clock
sync.Mutex
Supervisor
Config *Config
// localAuth has local auth server listed in case if this process
// has started with auth server role enabled
localAuth *auth.AuthServer
// backend is the process' backend
backend backend.Backend
// auditLog is the initialized audit log
auditLog events.IAuditLog
// identities of this process (credentials to auth sever, basically)
Identities map[teleport.Role]*auth.Identity
// registeredListeners keeps track of all listeners created by the process
// used to pass listeners to child processes during live reload
registeredListeners []RegisteredListener
// importedDescriptors is a list of imported file descriptors
// passed by the parent process
importedDescriptors []FileDescriptor
}
// GetAuthServer returns the process' auth server
func (process *TeleportProcess) GetAuthServer() *auth.AuthServer {
return process.localAuth
}
// GetAuditLog returns the process' audit log
func (process *TeleportProcess) GetAuditLog() events.IAuditLog {
return process.auditLog
}
// GetBackend returns the process' backend
func (process *TeleportProcess) GetBackend() backend.Backend {
return process.backend
}
func (process *TeleportProcess) backendSupportsForks() bool {
switch process.backend.(type) {
case *boltbk.BoltBackend:
return false
default:
return true
}
}
func (process *TeleportProcess) findStaticIdentity(id auth.IdentityID) (*auth.Identity, error) {
for i := range process.Config.Identities {
identity := process.Config.Identities[i]
if identity.ID.Equals(id) {
return identity, nil
}
}
return nil, trace.NotFound("identity %v not found", &id)
}
// readIdentity reads identity from disk and resets the local state
func (process *TeleportProcess) readIdentity(role teleport.Role) (*auth.Identity, error) {
process.Lock()
defer process.Unlock()
id := auth.IdentityID{HostUUID: process.Config.HostUUID, Role: role}
identity, err := auth.ReadIdentity(process.Config.DataDir, id)
if err != nil {
return nil, trace.Wrap(err)
}
process.Identities[role] = identity
return identity, nil
}
// GetIdentity returns the process identity (credentials to the auth server) for a given
// teleport Role. A teleport process can have any combination of 3 roles: auth, node, proxy
// and they have their own identities
func (process *TeleportProcess) GetIdentity(role teleport.Role) (i *auth.Identity, err error) {
var found bool
process.Lock()
defer process.Unlock()
i, found = process.Identities[role]
if found {
return i, nil
}
id := auth.IdentityID{HostUUID: process.Config.HostUUID, Role: role}
i, err = auth.ReadIdentity(process.Config.DataDir, id)
if err != nil {
if trace.IsNotFound(err) {
// try to locate static identity provided in the file
i, err = process.findStaticIdentity(id)
if err != nil {
return nil, trace.Wrap(err)
}
log.Infof("Found static identity %v in the config file, writing to disk.", &id)
if err = auth.WriteIdentity(process.Config.DataDir, i); err != nil {
return nil, trace.Wrap(err)
}
} else {
return nil, trace.Wrap(err)
}
}
process.Identities[role] = i
return i, nil
}
// connectToAuthService attempts to login into the auth servers specified in the
// configuration. Returns 'true' if successful
func (process *TeleportProcess) connectToAuthService(role teleport.Role, additionalPrincipals []string) (*Connector, error) {
identity, err := process.GetIdentity(role)
if err != nil {
return nil, trace.Wrap(err)
}
tlsConfig, err := identity.TLSConfig()
if err != nil {
if !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
// connect using legacy SSH and get new set of TLS credentials
storage := utils.NewFileAddrStorage(
filepath.Join(process.Config.DataDir, "authservers.json"))
authUser := identity.Cert.ValidPrincipals[0]
log.Infof("Connecting to the cluster as %v to fetch TLS certificates.", authUser)
authClient, err := auth.NewTunClient(
string(role),
process.Config.AuthServers,
authUser,
[]ssh.AuthMethod{ssh.PublicKeys(identity.KeySigner)},
auth.TunClientStorage(storage),
auth.TunDisableRefresh(),
)
if err != nil {
return nil, trace.Wrap(err)
}
defer authClient.Close()
if err := auth.ReRegister(process.Config.DataDir, authClient, identity.ID, additionalPrincipals); err != nil {
return nil, trace.Wrap(err)
}
if identity, err = process.readIdentity(role); err != nil {
return nil, trace.Wrap(err)
}
tlsConfig, err = identity.TLSConfig()
if err != nil {
return nil, trace.Wrap(err)
}
log.WithFields(logrus.Fields{"host": identity.ID.HostUUID, "role": identity.ID.Role}).Infof("Received new TLS identity.")
}
log.Infof("Connecting to the cluster %v with TLS client certificate.", identity.ClusterName)
client, err := auth.NewTLSClient(process.Config.AuthServers, tlsConfig)
if err != nil {
return nil, trace.Wrap(err)
}
if len(additionalPrincipals) != 0 && !identity.HasPrincipals(additionalPrincipals) {
log.Infof("Identity %v needs principals %v, going to re-register.", identity.ID, additionalPrincipals)
if err := auth.ReRegister(process.Config.DataDir, client, identity.ID, additionalPrincipals); err != nil {
return nil, trace.Wrap(err)
}
if identity, err = process.readIdentity(role); err != nil {
return nil, trace.Wrap(err)
}
tlsConfig, err = identity.TLSConfig()
if err != nil {
return nil, trace.Wrap(err)
}
}
// success ? we're logged in!
return &Connector{Client: client, Identity: identity}, nil
}
// NewTeleport takes the daemon configuration, instantiates all required services
// and starts them under a supervisor, returning the supervisor object
func NewTeleport(cfg *Config) (*TeleportProcess, error) {
// before we do anything reset the SIGINT handler back to the default
system.ResetInterruptSignalHandler()
if err := validateConfig(cfg); err != nil {
return nil, trace.Wrap(err, "configuration error")
}
// create the data directory if it's missing
_, err := os.Stat(cfg.DataDir)
if os.IsNotExist(err) {
err := os.MkdirAll(cfg.DataDir, os.ModeDir|0700)
if err != nil {
return nil, trace.Wrap(err)
}
}
// create the pid file
if cfg.PIDFile != "" {
f, err := os.OpenFile(cfg.PIDFile, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
fmt.Fprintf(f, "%v", os.Getpid())
defer f.Close()
}
importedDescriptors, err := importFileDescriptors()
if err != nil {
return nil, trace.Wrap(err)
}
// if there's no host uuid initialized yet, try to read one from the
// one of the identities
cfg.HostUUID, err = utils.ReadHostUUID(cfg.DataDir)
if err != nil {
if !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
if len(cfg.Identities) != 0 {
cfg.HostUUID = cfg.Identities[0].ID.HostUUID
log.Infof("Taking host UUID from first identity: %v.", cfg.HostUUID)
} else {
cfg.HostUUID = uuid.New()
log.Infof("Generating new host UUID: %v.", cfg.HostUUID)
}
if err := utils.WriteHostUUID(cfg.DataDir, cfg.HostUUID); err != nil {
return nil, trace.Wrap(err)
}
}
// if user started auth and another service (without providing the auth address for
// that service, the address of the in-process auth will be used
if cfg.Auth.Enabled && len(cfg.AuthServers) == 0 {
cfg.AuthServers = []utils.NetAddr{cfg.Auth.SSHAddr}
}
// if user did not provide auth domain name, use this host's name
if cfg.Auth.Enabled && cfg.Auth.ClusterName == nil {
cfg.Auth.ClusterName, err = services.NewClusterName(services.ClusterNameSpecV2{
ClusterName: cfg.Hostname,
})
if err != nil {
return nil, trace.Wrap(err)
}
}
process := &TeleportProcess{
Clock: clockwork.NewRealClock(),
Supervisor: NewSupervisor(),
Config: cfg,
Identities: make(map[teleport.Role]*auth.Identity),
importedDescriptors: importedDescriptors,
}
serviceStarted := false
if !cfg.DiagnosticAddr.IsEmpty() {
if err := process.initDiagnosticService(); err != nil {
return nil, trace.Wrap(err)
}
} else {
warnOnErr(process.closeImportedDescriptors(teleport.ComponentDiagnostic))
}
// Create a process wide key generator that will be shared. This is so the
// key generator can pre-generate keys and share these across services.
if cfg.Keygen == nil {
cfg.Keygen = native.New()
}
if cfg.Auth.Enabled {
if err := process.initAuthService(); err != nil {
return nil, trace.Wrap(err)
}
serviceStarted = true
} else {
warnOnErr(process.closeImportedDescriptors(teleport.ComponentAuth))
}
if cfg.SSH.Enabled {
if err := process.initSSH(); err != nil {
return nil, err
}
serviceStarted = true
} else {
warnOnErr(process.closeImportedDescriptors(teleport.ComponentNode))
}
if cfg.Proxy.Enabled {
if err := process.initProxy(); err != nil {
return nil, err
}
serviceStarted = true
} else {
warnOnErr(process.closeImportedDescriptors(teleport.ComponentProxy))
}
if !serviceStarted {
return nil, trace.BadParameter("all services failed to start")
}
return process, nil
}
func (process *TeleportProcess) setLocalAuth(a *auth.AuthServer) {
process.Lock()
defer process.Unlock()
process.localAuth = a
}
func (process *TeleportProcess) getLocalAuth() *auth.AuthServer {
process.Lock()
defer process.Unlock()
return process.localAuth
}
// adminCreds returns admin UID and GID settings based on the OS
func adminCreds() (*int, *int, error) {
if runtime.GOOS != teleport.LinuxOS {
return nil, nil, nil
}
// if the user member of adm linux group,
// make audit log folder readable by admins
isAdmin, err := utils.IsGroupMember(teleport.LinuxAdminGID)
if err != nil {
return nil, nil, trace.Wrap(err)
}
if !isAdmin {
return nil, nil, nil
}
uid := os.Getuid()
gid := teleport.LinuxAdminGID
return &uid, &gid, nil
}
// initUploadHandler initializes upload handler based on the config settings,
// currently the only upload handler supported is S3
// the call can return trace.NotFOund if no upload handler is setup
func initUploadHandler(auditConfig services.AuditConfig) (events.UploadHandler, error) {
if auditConfig.AuditSessionsURI == "" {
return nil, trace.NotFound("no upload handler is setup")
}
uri, err := utils.ParseSessionsURI(auditConfig.AuditSessionsURI)
if err != nil {
return nil, trace.Wrap(err)
}
switch uri.Scheme {
case teleport.SchemeS3:
return s3sessions.NewHandler(s3sessions.Config{
Bucket: uri.Host,
Region: auditConfig.Region,
})
case teleport.SchemeFile:
return filesessions.NewHandler(filesessions.Config{
Directory: uri.Path,
})
default:
return nil, trace.BadParameter(
"unsupported scheme for audit_sesions_uri: %q, currently supported schemes are %q and %q",
uri.Scheme, teleport.SchemeS3)
}
}
// initExternalLog initializes external storage, if the storage is not
// setup, returns nil
func initExternalLog(auditConfig services.AuditConfig) (events.IAuditLog, error) {
if auditConfig.Type == "" {
if auditConfig.AuditTableName != "" {
return nil, trace.BadParameter("no storage type defined for table name %q in config %#v", auditConfig.AuditTableName, auditConfig)
}
return nil, trace.NotFound("no external log is defined")
}
if auditConfig.AuditTableName == "" {
return nil, trace.NotFound("no external log is defined")
}
if auditConfig.Type != dynamo.GetName() {
return nil, trace.BadParameter("unsupported events backend %q, the only supported backend is %q", auditConfig.Type, dynamo.GetName())
}
if !auditConfig.ShouldUploadSessions() {
return nil, trace.BadParameter("please specify audit_sessions_uri when using external audit backends")
}
return dynamoevents.New(dynamoevents.Config{
Tablename: auditConfig.AuditTableName,
Region: auditConfig.Region,
})
}
// initAuthService can be called to initialize auth server service
func (process *TeleportProcess) initAuthService() error {
var (
askedToExit = false
err error
)
cfg := process.Config
// Initialize the storage back-ends for keys, events and records
b, err := process.initAuthStorage()
if err != nil {
return trace.Wrap(err)
}
process.backend = b
// create the audit log, which will be consuming (and recording) all events
// and recording all sessions.
if cfg.Auth.NoAudit {
// this is for teleconsole
process.auditLog = events.NewDiscardAuditLog()
warningMessage := "Warning: Teleport audit and session recording have been " +
"turned off. This is dangerous, you will not be able to view audit events " +
"or save and playback recorded sessions."
log.Warn(warningMessage)
} else {
// check if session recording has been disabled. note, we will continue
// logging audit events, we just won't record sessions.
recordSessions := true
if cfg.Auth.ClusterConfig.GetSessionRecording() == services.RecordOff {
recordSessions = false
warningMessage := "Warning: Teleport session recording have been turned off. " +
"This is dangerous, you will not be able to save and playback sessions."
log.Warn(warningMessage)
}
auditConfig := cfg.Auth.ClusterConfig.GetAuditConfig()
uploadHandler, err := initUploadHandler(auditConfig)
if err != nil {
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
}
externalLog, err := initExternalLog(auditConfig)
if err != nil {
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
}
auditServiceConfig := events.AuditLogConfig{
DataDir: filepath.Join(cfg.DataDir, teleport.LogsDir),
RecordSessions: recordSessions,
ServerID: cfg.HostUUID,
UploadHandler: uploadHandler,
ExternalLog: externalLog,
}
auditServiceConfig.UID, auditServiceConfig.GID, err = adminCreds()
if err != nil {
return trace.Wrap(err)
}
process.auditLog, err = events.NewAuditLog(auditServiceConfig)
if err != nil {
return trace.Wrap(err)
}
}
// first, create the AuthServer
authServer, identity, err := auth.Init(auth.InitConfig{
Backend: b,
Authority: cfg.Keygen,
ClusterConfiguration: cfg.ClusterConfiguration,
ClusterConfig: cfg.Auth.ClusterConfig,
ClusterName: cfg.Auth.ClusterName,
AuthServiceName: cfg.Hostname,
DataDir: cfg.DataDir,
HostUUID: cfg.HostUUID,
NodeName: cfg.Hostname,
Authorities: cfg.Auth.Authorities,
ReverseTunnels: cfg.ReverseTunnels,
Trust: cfg.Trust,
Presence: cfg.Presence,
Provisioner: cfg.Provisioner,
Identity: cfg.Identity,
Access: cfg.Access,
StaticTokens: cfg.Auth.StaticTokens,
Roles: cfg.Auth.Roles,
AuthPreference: cfg.Auth.Preference,
OIDCConnectors: cfg.OIDCConnectors,
AuditLog: process.auditLog,
})
if err != nil {
return trace.Wrap(err)
}
process.setLocalAuth(authServer)
// second, create the API Server: it's actually a collection of API servers,
// each serving requests for a "role" which is assigned to every connected
// client based on their certificate (user, server, admin, etc)
sessionService, err := session.New(b)
if err != nil {
return trace.Wrap(err)
}
authorizer, err := auth.NewAuthorizer(authServer.Access, authServer.Identity, authServer.Trust)
if err != nil {
return trace.Wrap(err)
}
apiConf := &auth.APIConfig{
AuthServer: authServer,
SessionService: sessionService,
Authorizer: authorizer,
AuditLog: process.auditLog,
}
sshLimiter, err := limiter.NewLimiter(cfg.Auth.Limiter)
if err != nil {
return trace.Wrap(err)
}
// admin access point is a caching access point used for frequently
// accessed data by auth server, e.g. cert authorities, users and roles
adminAuthServer, err := auth.NewAdminAuthServer(authServer, sessionService, process.auditLog)
if err != nil {
return trace.Wrap(err)
}
adminAccessPoint, err := process.newLocalCache(adminAuthServer, []string{"auth"})
if err != nil {
return trace.Wrap(err)
}
log := logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentAuth,
})
// Register TLS endpoint of the auth service
tlsConfig, err := identity.TLSConfig()
if err != nil {
return trace.Wrap(err)
}
tlsServer, err := auth.NewTLSServer(auth.TLSServerConfig{
TLS: tlsConfig,
APIConfig: *apiConf,
LimiterConfig: cfg.Auth.Limiter,
AccessPoint: adminAccessPoint,
})
if err != nil {
return trace.Wrap(err)
}
// auth server listens on SSH and TLS, reusing the same socket
listener, err := process.importOrCreateListener(teleport.ComponentAuth, cfg.Auth.SSHAddr.Addr)
if err != nil {
log.Errorf("PID: %v Failed to bind to address %v: %v, exiting.", os.Getpid(), cfg.Auth.SSHAddr.Addr, err)
return trace.Wrap(err)
}
// clean up unused descriptors passed for proxy, but not used by it
warnOnErr(process.closeImportedDescriptors(teleport.ComponentAuth))
if cfg.Auth.EnableProxyProtocol {
log.Infof("Starting Auth service with PROXY protocol support.")
}
mux, err := multiplexer.New(multiplexer.Config{
EnableProxyProtocol: cfg.Auth.EnableProxyProtocol,
Listener: listener,
})
if err != nil {
listener.Close()
return trace.Wrap(err)
}
go mux.Serve()
// Register an SSH endpoint which is used to create an SSH tunnel to send HTTP
// requests to the Auth API
var authTunnel *auth.AuthTunnel
process.RegisterFunc("auth.ssh", func() error {
log.Infof("Auth SSH service is starting on %v", cfg.Auth.SSHAddr.Addr)
authTunnel, err = auth.NewTunnel(
cfg.Auth.SSHAddr,
identity.KeySigner,
apiConf,
auth.SetLimiter(sshLimiter),
)
if err != nil {
log.Errorf("Error: %v", err)
return trace.Wrap(err)
}
// since authTunnel.Serve is a blocking call, we emit this even right before
// the service has started
process.BroadcastEvent(Event{Name: AuthSSHReady, Payload: nil})
if err := authTunnel.Serve(mux.SSH()); err != nil {
if askedToExit {
log.Infof("Auth tunnel exited.")
return nil
}
log.Errorf("Error: %v", err)
return trace.Wrap(err)
}
return nil
})
process.RegisterFunc("auth.tls", func() error {
// since tlsServer.Serve is a blocking call, we emit this even right before
// the service has started
process.BroadcastEvent(Event{Name: AuthTLSReady, Payload: nil})
err := tlsServer.Serve(mux.TLS())
if err != nil && err != http.ErrServerClosed {
log.Warningf("TLS server exited with error: %v.", err)
}
return nil
})
process.RegisterFunc("auth.heartbeat.broadcast", func() error {
// Heart beat auth server presence, this is not the best place for this
// logic, consolidate it into auth package later
connector, err := process.connectToAuthService(teleport.RoleAdmin, nil)
if err != nil {
return trace.Wrap(err)
}
// External integrations rely on this event:
process.BroadcastEvent(Event{Name: AuthIdentityEvent, Payload: connector})
process.onExit("auth.broadcast", func(payload interface{}) {
connector.Client.Close()
})
return nil
})
closeContext, signalClose := context.WithCancel(context.TODO())
process.RegisterFunc("auth.heartbeat", func() error {
srv := services.ServerV2{
Kind: services.KindAuthServer,
Version: services.V2,
Metadata: services.Metadata{
Namespace: defaults.Namespace,
Name: process.Config.HostUUID,
},
Spec: services.ServerSpecV2{
Addr: cfg.Auth.SSHAddr.Addr,
Hostname: process.Config.Hostname,
},
}
host, port, err := net.SplitHostPort(srv.GetAddr())
// advertise-ip is explicitly set:
if process.Config.AdvertiseIP != nil {
if err != nil {
return trace.Wrap(err)
}
srv.SetAddr(fmt.Sprintf("%v:%v", process.Config.AdvertiseIP.String(), port))
} else {
// advertise-ip is not set, while the CA is listening on 0.0.0.0? lets try
// to guess the 'advertise ip' then:
if net.ParseIP(host).IsUnspecified() {
ip, err := utils.GuessHostIP()
if err != nil {
log.Warn(err)
} else {
srv.SetAddr(net.JoinHostPort(ip.String(), port))
}
}
log.Warnf("auth_service: advertise_ip is not set. guessing %v.", srv.GetAddr())
}
// immediately register, and then keep repeating in a loop:
ticker := time.NewTicker(defaults.ServerHeartbeatTTL / 2)
defer ticker.Stop()
announce:
for {
srv.SetTTL(process, defaults.ServerHeartbeatTTL)
err := authServer.UpsertAuthServer(&srv)
if err != nil {
log.Warningf("Failed to announce presence: %v.", err)
}
select {
case <-closeContext.Done():
break announce
case <-ticker.C:
}
}
log.Infof("Heartbeat to other auth servers exited.")
return nil
})
// execute this when process is asked to exit:
process.onExit("auth.shutdown", func(payload interface{}) {
// as a last resort, at least close listeners (e.g. panic)
if listener != nil {
defer listener.Close()
}
if mux != nil {
defer mux.Close()
}
signalClose()
if payload == nil {
log.Info("Shutting down immediately.")
warnOnErr(tlsServer.Close())
warnOnErr(authTunnel.Close())
} else {
log.Info("Shutting down gracefully.")
ctx := payloadContext(payload)
warnOnErr(tlsServer.Shutdown(ctx))
warnOnErr(authTunnel.Shutdown(ctx))
}
log.Info("Exited.")
})
return nil
}
func payloadContext(payload interface{}) context.Context {
ctx, ok := payload.(context.Context)
if ok {
return ctx
}
log.Errorf("expected context, got %T", payload)
return context.TODO()
}
// onExit allows individual services to register a callback function which will be
// called when Teleport Process is asked to exit. Usually services terminate themselves
// when the callback is called
func (process *TeleportProcess) onExit(serviceName string, callback func(interface{})) {
process.RegisterFunc(serviceName, func() error {
eventC := make(chan Event)
process.WaitForEvent(TeleportExitEvent, eventC, make(chan struct{}))
select {
case event := <-eventC:
callback(event.Payload)
}
return nil
})
}
// newLocalCache returns new local cache access point
func (process *TeleportProcess) newLocalCache(clt auth.ClientI, cacheName []string) (auth.AccessPoint, error) {
// if caching is disabled, return access point
if !process.Config.CachePolicy.Enabled {
return clt, nil
}
path := filepath.Join(append([]string{process.Config.DataDir, "cache"}, cacheName...)...)
if err := os.MkdirAll(path, teleport.SharedDirMode); err != nil {
return nil, trace.ConvertSystemError(err)
}
cacheBackend, err := dir.New(backend.Params{"path": path})
if err != nil {
return nil, trace.Wrap(err)
}
return state.NewCachingAuthClient(state.Config{
AccessPoint: clt,
Backend: cacheBackend,
NeverExpires: process.Config.CachePolicy.NeverExpires,
RecentCacheTTL: process.Config.CachePolicy.GetRecentTTL(),
CacheMaxTTL: process.Config.CachePolicy.TTL,
})
}
// initSSH initializes the "node" role, i.e. a simple SSH server connected to the auth server.
func (process *TeleportProcess) initSSH() error {
process.RegisterWithAuthServer(
process.Config.Token, teleport.RoleNode, SSHIdentityEvent, nil)
eventsC := make(chan Event)
process.WaitForEvent(SSHIdentityEvent, eventsC, make(chan struct{}))
var s *regular.Server
log := logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentNode,
})
process.RegisterFunc("ssh.node", func() error {
event := <-eventsC
log.Infof("Received event %q.", event.Name)
conn, ok := (event.Payload).(*Connector)
if !ok {
return trace.BadParameter("unsupported connector type: %T", event.Payload)
}
cfg := process.Config
limiter, err := limiter.NewLimiter(cfg.SSH.Limiter)
if err != nil {
return trace.Wrap(err)
}
authClient, err := process.newLocalCache(conn.Client, []string{"node"})
if err != nil {
return trace.Wrap(err)
}
// make sure the namespace exists
namespace := services.ProcessNamespace(cfg.SSH.Namespace)
_, err = authClient.GetNamespace(namespace)
if err != nil {
if trace.IsNotFound(err) {
return trace.NotFound(
"namespace %v is not found, ask your system administrator to create this namespace so you can register nodes there.", namespace)
}
return trace.Wrap(err)
}
listener, err := process.importOrCreateListener(teleport.ComponentNode, cfg.SSH.Addr.Addr)
if err != nil {
return trace.Wrap(err)
}
// clean up unused descriptors passed for proxy, but not used by it
warnOnErr(process.closeImportedDescriptors(teleport.ComponentNode))
s, err = regular.New(cfg.SSH.Addr,
cfg.Hostname,
[]ssh.Signer{conn.Identity.KeySigner},
authClient,
cfg.DataDir,
cfg.AdvertiseIP,
cfg.Proxy.PublicAddr,
regular.SetLimiter(limiter),
regular.SetShell(cfg.SSH.Shell),
regular.SetAuditLog(conn.Client),
regular.SetSessionServer(conn.Client),
regular.SetLabels(cfg.SSH.Labels, cfg.SSH.CmdLabels),
regular.SetNamespace(namespace),
regular.SetPermitUserEnvironment(cfg.SSH.PermitUserEnvironment),
regular.SetCiphers(cfg.Ciphers),
regular.SetKEXAlgorithms(cfg.KEXAlgorithms),
regular.SetMACAlgorithms(cfg.MACAlgorithms),
)
if err != nil {
return trace.Wrap(err)
}
// init uploader service for recording SSH node, if proxy is not
// enabled on this node, because proxy stars uploader service as well
if !cfg.Proxy.Enabled {
if err := process.initUploaderService(authClient, conn.Client); err != nil {
return trace.Wrap(err)
}
}
log.Infof("Service is starting on %v %v.", cfg.SSH.Addr.Addr, process.Config.CachePolicy)
go s.Serve(listener)
// broadcast that the node has started
process.BroadcastEvent(Event{Name: NodeSSHReady, Payload: nil})
// block and wait while the node is running
s.Wait()
log.Infof("Exited.")
return nil
})
// execute this when process is asked to exit:
process.onExit("ssh.shutdown", func(payload interface{}) {
if payload == nil {
log.Infof("Shutting down immediately.")
if s != nil {
warnOnErr(s.Close())
}
} else {
log.Infof("Shutting down gracefully.")
if s != nil {
warnOnErr(s.Shutdown(payloadContext(payload)))
}
}
log.Infof("Exited.")
})
return nil
}
// RegisterWithAuthServer uses one time provisioning token obtained earlier
// from the server to get a pair of SSH keys signed by Auth server host
// certificate authority
func (process *TeleportProcess) RegisterWithAuthServer(token string, role teleport.Role, eventName string, additionalPrincipals []string) {
cfg := process.Config
identityID := auth.IdentityID{Role: role, HostUUID: cfg.HostUUID, NodeName: cfg.Hostname}
// this means the server has not been initialized yet, we are starting
// the registering client that attempts to connect to the auth server
// and provision the keys
var authClient *auth.Client
process.RegisterFunc(fmt.Sprintf("register.%v", strings.ToLower(role.String())), func() error {
retryTime := defaults.ServerHeartbeatTTL / 3
for {