forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service.go
2122 lines (1930 loc) · 67.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"
"sync/atomic"
"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/client"
"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"
kubeproxy "github.com/gravitational/teleport/lib/kube/proxy"
"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"
// 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"
// ProxyAgentPoolReady is generated when the proxy has initialized the agent
// pool (pool of connections from a remote cluster to a main cluster) and is
// ready to start accepting connections.
ProxyAgentPoolReady = "ProxyAgentPoolReady"
// 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"
// TeleportReloadEvent is generated to trigger in-process teleport
// service reload - all servers and clients will be re-created
// in a graceful way.
TeleportReloadEvent = "TeleportReload"
// TeleportPhaseChangeEvent is generated to indidate that teleport
// CA rotation phase has been updated, used in tests
TeleportPhaseChangeEvent = "TeleportPhaseChange"
// TeleportReadyEvent is generated to signal that all teleport
// internal components have started successfully.
TeleportReadyEvent = "TeleportReady"
// ServiceExitedWithErrorEvent is emitted whenever a service
// has exited with an error, the payload includes the error
ServiceExitedWithErrorEvent = "ServiceExitedWithError"
)
// 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 {
// ClientIdentity is the identity to be used in internal cluster
// clients to the auth service.
ClientIdentity *auth.Identity
// ServerIdentity is the identity to be used in servers - serving SSH
// and x509 certificates to clients.
ServerIdentity *auth.Identity
// Client is authenticated client with credentials from ClientIdenity.
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
// connectors is a list of connected clients and their identities
connectors map[teleport.Role]*Connector
// 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
// forkedPIDs is a collection of a teleport processes forked
// during restart used to collect their status in case if the
// child process crashed.
forkedPIDs []int
// storage is a server local storage
storage *auth.ProcessStorage
// id is a process id - used to identify different processes
// during in-process reloads.
id string
// Entry is a process-local log entry.
*logrus.Entry
// keyPairs holds private/public key pairs used
// to get signed host certificates from auth server
keyPairs map[keyPairKey]KeyPair
// keyMutex is a mutex to serialize key generation
keyMutex sync.Mutex
}
type keyPairKey struct {
role teleport.Role
reason string
}
// processIndex is an internal process index
// to help differentiate between two different teleport processes
// during in-process reload.
var processID int32 = 0
func nextProcessID() int32 {
return atomic.AddInt32(&processID, 1)
}
// 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)
}
// getConnectors returns a copy of the identities registered for auth server
func (process *TeleportProcess) getConnectors() []*Connector {
process.Lock()
defer process.Unlock()
out := make([]*Connector, 0, len(process.connectors))
for role := range process.connectors {
out = append(out, process.connectors[role])
}
return out
}
// addConnector adds connector to registered connectors list,
// it will overwrite the connector for the same role
func (process *TeleportProcess) addConnector(connector *Connector) {
process.Lock()
defer process.Unlock()
process.connectors[connector.ClientIdentity.ID.Role] = connector
}
// 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
}
i, err = process.storage.ReadIdentity(auth.IdentityCurrent, role)
id := auth.IdentityID{
Role: role,
HostUUID: process.Config.HostUUID,
NodeName: process.Config.Hostname,
}
if err != nil {
if !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
if role == teleport.RoleAdmin {
// for admin identity use local auth server
// because admin identity is requested by auth server
// itself
principals, err := process.getAdditionalPrincipals(role)
if err != nil {
return nil, trace.Wrap(err)
}
i, err = auth.GenerateIdentity(process.localAuth, id, principals)
} else {
// try to locate static identity provided in the file
i, err = process.findStaticIdentity(id)
if err != nil {
return nil, trace.Wrap(err)
}
process.Infof("Found static identity %v in the config file, writing to disk.", &id)
if err = process.storage.WriteIdentity(auth.IdentityCurrent, *i); err != nil {
return nil, trace.Wrap(err)
}
}
}
process.Identities[role] = i
return i, nil
}
// Process is a interface for processes
type Process interface {
// Closer closes all resources used by the process
io.Closer
// Start starts the process in a non-blocking way
Start() error
// WaitForSignals waits for and handles system process signals.
WaitForSignals(context.Context) error
// ExportFileDescriptors exports service listeners
// file descriptors used by the process.
ExportFileDescriptors() ([]FileDescriptor, error)
// Shutdown starts graceful shutdown of the process,
// blocks until all resources are freed and go-routines are
// shut down.
Shutdown(context.Context)
// WaitForEvent waits for event to occur, sends event to the channel,
// this is a non-blocking function.
WaitForEvent(ctx context.Context, name string, eventC chan Event)
// WaitWithContext waits for the service to stop. This is a blocking
// function.
WaitWithContext(ctx context.Context)
}
// NewProcess is a function that creates new teleport from config
type NewProcess func(cfg *Config) (Process, error)
func newTeleportProcess(cfg *Config) (Process, error) {
return NewTeleport(cfg)
}
// Run starts teleport processes, waits for signals
// and handles internal process reloads.
func Run(ctx context.Context, cfg Config, newTeleport NewProcess) error {
if newTeleport == nil {
newTeleport = newTeleportProcess
}
copyCfg := cfg
srv, err := newTeleport(©Cfg)
if err != nil {
return trace.Wrap(err, "initialization failed")
}
if srv == nil {
return trace.BadParameter("process has returned nil server")
}
if err := srv.Start(); err != nil {
return trace.Wrap(err, "startup failed")
}
// Wait and reload until called exit.
for {
srv, err = waitAndReload(ctx, cfg, srv, newTeleport)
if err != nil {
// This error means that was a clean shutdown
// an no reload is necessary.
if err == ErrTeleportExited {
return nil
}
return trace.Wrap(err)
}
}
}
func waitAndReload(ctx context.Context, cfg Config, srv Process, newTeleport NewProcess) (Process, error) {
err := srv.WaitForSignals(ctx)
if err == nil {
return nil, ErrTeleportExited
}
if err != ErrTeleportReloading {
return nil, trace.Wrap(err)
}
log.Infof("Started in-process service reload.")
fileDescriptors, err := srv.ExportFileDescriptors()
if err != nil {
warnOnErr(srv.Close())
return nil, trace.Wrap(err)
}
newCfg := cfg
newCfg.FileDescriptors = fileDescriptors
newSrv, err := newTeleport(&newCfg)
if err != nil {
warnOnErr(srv.Close())
return nil, trace.Wrap(err, "failed to create a new service")
}
log.Infof("Created new process.")
if err := newSrv.Start(); err != nil {
warnOnErr(srv.Close())
return nil, trace.Wrap(err, "failed to start a new service")
}
// Wait for the new server to report that it has started
// before shutting down the old one.
startTimeoutCtx, startCancel := context.WithTimeout(ctx, signalPipeTimeout)
defer startCancel()
eventC := make(chan Event, 1)
newSrv.WaitForEvent(startTimeoutCtx, TeleportReadyEvent, eventC)
select {
case <-eventC:
log.Infof("New service has started successfully.")
case <-startTimeoutCtx.Done():
warnOnErr(newSrv.Close())
warnOnErr(srv.Close())
return nil, trace.BadParameter("the new service has failed to start")
}
shutdownTimeout := cfg.ShutdownTimeout
if shutdownTimeout == 0 {
// The default shutdown timeout is very generous to avoid disrupting
// longer running connections.
shutdownTimeout = defaults.DefaultIdleConnectionDuration
}
log.Infof("Shutting down the old service with timeout %v.", shutdownTimeout)
// After the new process has started, initiate the graceful shutdown of the old process
// new process could have generated connections to the new process's server
// so not all connections can be kept forever.
timeoutCtx, cancel := context.WithTimeout(ctx, shutdownTimeout)
defer cancel()
srv.Shutdown(timeoutCtx)
if timeoutCtx.Err() == context.DeadlineExceeded {
// The new serivce can start initiating connections to the old service
// keeping it from shutting down gracefully, or some external
// connections can keep hanging the old auth service and prevent
// the services from shutting down, so abort the graceful way
// after some time to keep going.
log.Infof("Some connections to the old service were aborted after timeout of %v.", shutdownTimeout)
// Make sure that all parts of the service have exited, this function
// can not allow execution to continue if the shutdown is not complete,
// otherwise subsequent Run executions will hold system resources in case
// if old versions of the service are not exiting completely.
timeoutCtx, cancel := context.WithTimeout(ctx, shutdownTimeout)
defer cancel()
srv.WaitWithContext(timeoutCtx)
if timeoutCtx.Err() == context.DeadlineExceeded {
return nil, trace.BadParameter("the old service has failed to exit.")
}
} else {
log.Infof("The old service was successfully shut down gracefully.")
}
return newSrv, 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)
}
}
if len(cfg.FileDescriptors) == 0 {
cfg.FileDescriptors, 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)
}
}
storage, err := auth.NewProcessStorage(filepath.Join(cfg.DataDir, teleport.ComponentProcess))
if err != nil {
return nil, trace.Wrap(err)
}
processID := fmt.Sprintf("%v", nextProcessID())
process := &TeleportProcess{
Clock: clockwork.NewRealClock(),
Supervisor: NewSupervisor(processID),
Config: cfg,
Identities: make(map[teleport.Role]*auth.Identity),
connectors: make(map[teleport.Role]*Connector),
importedDescriptors: cfg.FileDescriptors,
storage: storage,
id: processID,
keyPairs: make(map[keyPairKey]KeyPair),
}
process.Entry = logrus.WithFields(logrus.Fields{
trace.Component: teleport.Component(teleport.ComponentProcess, process.id),
})
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 {
precomputeCount := native.PrecomputedNum
// in case if not auth or proxy services are enabled,
// there is no need to precompute any SSH keys in the pool
if !cfg.Auth.Enabled && !cfg.Proxy.Enabled {
precomputeCount = 0
}
var err error
cfg.Keygen, err = native.New(native.PrecomputeKeys(precomputeCount))
if err != nil {
return nil, trace.Wrap(err)
}
}
// Produce global TeleportReadyEvent
// when all components have started
eventMapping := EventMapping{
Out: TeleportReadyEvent,
}
if cfg.Auth.Enabled {
eventMapping.In = append(eventMapping.In, AuthTLSReady)
}
if cfg.SSH.Enabled {
eventMapping.In = append(eventMapping.In, NodeSSHReady)
}
if cfg.Proxy.Enabled {
eventMapping.In = append(eventMapping.In, ProxySSHReady)
}
process.RegisterEventMapping(eventMapping)
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 {
eventMapping.In = append(eventMapping.In, ProxySSHReady)
if err := process.initProxy(); err != nil {
return nil, err
}
serviceStarted = true
} else {
warnOnErr(process.closeImportedDescriptors(teleport.ComponentProxy))
}
process.RegisterFunc("common.rotate", process.periodicSyncRotationState)
if !serviceStarted {
return nil, trace.BadParameter("all services failed to start")
}
// create the new pid file only after started successfully
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()
}
// notify parent process that this process has started
go process.notifyParent()
return process, nil
}
// notifyParent notifies parent process that this process has started
// by writing to in-memory pipe used by communication channel.
func (process *TeleportProcess) notifyParent() {
signalPipe, err := process.importSignalPipe()
if err != nil {
if !trace.IsNotFound(err) {
process.Warningf("Failed to import signal pipe")
}
process.Debugf("No signal pipe to import, must be first Teleport process.")
return
}
defer signalPipe.Close()
ctx, cancel := context.WithTimeout(process.ExitContext(), signalPipeTimeout)
defer cancel()
eventC := make(chan Event, 1)
process.WaitForEvent(ctx, TeleportReadyEvent, eventC)
select {
case <-eventC:
process.Infof("New service has started successfully.")
case <-ctx.Done():
process.Errorf("Timeout waiting for a forked process to start: %v. Initiating self-shutdown.", ctx.Err())
if err := process.Close(); err != nil {
process.Warningf("Failed to shutdown process: %v.", err)
}
return
}
if err := process.writeToSignalPipe(signalPipe, fmt.Sprintf("Process %v has started.", os.Getpid())); err != nil {
process.Warningf("Failed to write to signal pipe: %v", err)
// despite the failure, it's ok to proceed,
// it could mean that the parent process has crashed and the pipe
// is no longer valid.
}
}
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:
handler, err := s3sessions.NewHandler(s3sessions.Config{
Bucket: uri.Host,
Region: auditConfig.Region,
Path: uri.Path,
})
if err != nil {
return nil, trace.Wrap(err)
}
return handler, nil
case teleport.SchemeFile:
if err := os.MkdirAll(uri.Path, teleport.SharedDirMode); err != nil {
return nil, trace.ConvertSystemError(err)
}
handler, err := filesessions.NewHandler(filesessions.Config{
Directory: uri.Path,
})
if err != nil {
return nil, trace.Wrap(err)
}
return handler, nil
default:
return nil, trace.BadParameter(
"unsupported scheme for audit_sesions_uri: %q, currently supported schemes are %q and %q",
uri.Scheme, teleport.SchemeS3, teleport.SchemeFile)
}
}
// initExternalLog initializes external storage, if the storage is not
// setup, returns nil
func initExternalLog(auditConfig services.AuditConfig) (events.IAuditLog, error) {
if auditConfig.AuditTableName != "" {
log.Warningf("Please note that 'audit_table_name' is deprecated and will be removed in several releases. Use audit_events_uri: '%v://%v' instead.", dynamo.GetName(), auditConfig.AuditTableName)
if len(auditConfig.AuditEventsURI) != 0 {
return nil, trace.BadParameter("Detected configuration specifying 'audit_table_name' and 'audit_events_uri' at the same time. Please migrate your config to use 'audit_events_uri' only.")
}
auditConfig.AuditEventsURI = []string{fmt.Sprintf("%v://%v", dynamo.GetName(), auditConfig.AuditTableName)}
}
if len(auditConfig.AuditEventsURI) > 0 && !auditConfig.ShouldUploadSessions() {
return nil, trace.BadParameter("please specify audit_sessions_uri when using external audit backends")
}
var hasNonFileLog bool
var loggers []events.IAuditLog
for _, eventsURI := range auditConfig.AuditEventsURI {
uri, err := utils.ParseSessionsURI(eventsURI)
if err != nil {
return nil, trace.Wrap(err)
}
switch uri.Scheme {
case dynamo.GetName():
hasNonFileLog = true
logger, err := dynamoevents.New(dynamoevents.Config{
Tablename: uri.Host,
Region: auditConfig.Region,
})
if err != nil {
return nil, trace.Wrap(err)
}
loggers = append(loggers, logger)
case teleport.SchemeFile:
if err := os.MkdirAll(uri.Path, teleport.SharedDirMode); err != nil {
return nil, trace.ConvertSystemError(err)
}
logger, err := events.NewFileLog(events.FileLogConfig{
Dir: uri.Path,
})
if err != nil {
return nil, trace.Wrap(err)
}
loggers = append(loggers, logger)
default:
return nil, trace.BadParameter(
"unsupported scheme for audit_events_uri: %q, currently supported schemes are %q and %q",
uri.Scheme, dynamo.GetName(), teleport.SchemeFile)
}
}
// only file external loggers are prohibited (they are not supposed
// to be used on their own, only in combo with external loggers)
// they also don't implement certain features, so they are going
// to be inefficient
switch len(loggers) {
case 0:
return nil, trace.NotFound("no external log is defined")
case 1:
if !hasNonFileLog {
return nil, trace.BadParameter("file:// log can not be used on it's own, can be only used in combination with external session logs, e.g. dynamodb://")
}
return loggers[0], nil
default:
if !hasNonFileLog {
return nil, trace.BadParameter("file:// log can not be used on it's own, can be only used in combination with external session logs, e.g. dynamodb://")
}
return events.NewMultiLog(loggers...), nil
}
}
// initAuthService can be called to initialize auth server service
func (process *TeleportProcess) initAuthService() error {
var 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."
process.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."
process.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, 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,
CipherSuites: cfg.CipherSuites,
KubeconfigPath: cfg.Auth.KubeconfigPath,
})
if err != nil {
return trace.Wrap(err)
}
process.setLocalAuth(authServer)
connector, err := process.connectToAuthService(teleport.RoleAdmin)
if err != nil {
return trace.Wrap(err)
}
// 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,
}
// 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.Component(teleport.ComponentAuth, process.id),
})
// Register TLS endpoint of the auth service
tlsConfig, err := connector.ServerIdentity.TLSConfig(cfg.CipherSuites)
if err != nil {
return trace.Wrap(err)
}
tlsServer, err := auth.NewTLSServer(auth.TLSServerConfig{
TLS: tlsConfig,
APIConfig: *apiConf,
LimiterConfig: cfg.Auth.Limiter,
AccessPoint: adminAccessPoint,
Component: teleport.Component(teleport.ComponentAuth, process.id),
})
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,
ID: teleport.Component(process.id),
})
if err != nil {
listener.Close()
return trace.Wrap(err)
}
go mux.Serve()
process.RegisterCriticalFunc("auth.tls", func() error {
utils.Consolef(cfg.Console, teleport.ComponentAuth, "Auth service is starting on %v.", cfg.Auth.SSHAddr.Addr)
// 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