-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
service.go
6010 lines (5389 loc) · 206 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-2021 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/rand"
"crypto/tls"
"crypto/x509"
"encoding/hex"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/http/pprof"
"os"
"path/filepath"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/google/uuid"
"github.com/gravitational/roundtrip"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/crypto/acme"
"golang.org/x/crypto/acme/autocert"
"golang.org/x/crypto/ssh"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/keepalive"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client"
"github.com/gravitational/teleport/api/client/proto"
"github.com/gravitational/teleport/api/constants"
apidefaults "github.com/gravitational/teleport/api/defaults"
kubeproto "github.com/gravitational/teleport/api/gen/proto/go/teleport/kube/v1"
transportpb "github.com/gravitational/teleport/api/gen/proto/go/teleport/transport/v1"
"github.com/gravitational/teleport/api/types"
apievents "github.com/gravitational/teleport/api/types/events"
apiutils "github.com/gravitational/teleport/api/utils"
"github.com/gravitational/teleport/api/utils/aws"
"github.com/gravitational/teleport/api/utils/grpc/interceptors"
"github.com/gravitational/teleport/api/utils/retryutils"
"github.com/gravitational/teleport/lib"
"github.com/gravitational/teleport/lib/agentless"
"github.com/gravitational/teleport/lib/ai"
"github.com/gravitational/teleport/lib/ai/embedding"
"github.com/gravitational/teleport/lib/auditd"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/auth/keygen"
"github.com/gravitational/teleport/lib/auth/native"
"github.com/gravitational/teleport/lib/authz"
"github.com/gravitational/teleport/lib/backend"
"github.com/gravitational/teleport/lib/backend/dynamo"
"github.com/gravitational/teleport/lib/backend/etcdbk"
"github.com/gravitational/teleport/lib/backend/firestore"
"github.com/gravitational/teleport/lib/backend/kubernetes"
"github.com/gravitational/teleport/lib/backend/lite"
"github.com/gravitational/teleport/lib/backend/memory"
"github.com/gravitational/teleport/lib/backend/pgbk"
"github.com/gravitational/teleport/lib/bpf"
"github.com/gravitational/teleport/lib/cache"
"github.com/gravitational/teleport/lib/cloud"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/events/athena"
"github.com/gravitational/teleport/lib/events/azsessions"
"github.com/gravitational/teleport/lib/events/dynamoevents"
"github.com/gravitational/teleport/lib/events/filesessions"
"github.com/gravitational/teleport/lib/events/firestoreevents"
"github.com/gravitational/teleport/lib/events/gcssessions"
"github.com/gravitational/teleport/lib/events/pgevents"
"github.com/gravitational/teleport/lib/events/s3sessions"
"github.com/gravitational/teleport/lib/httplib"
"github.com/gravitational/teleport/lib/inventory"
"github.com/gravitational/teleport/lib/joinserver"
kubegrpc "github.com/gravitational/teleport/lib/kube/grpc"
kubeproxy "github.com/gravitational/teleport/lib/kube/proxy"
"github.com/gravitational/teleport/lib/labels"
"github.com/gravitational/teleport/lib/limiter"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/multiplexer"
"github.com/gravitational/teleport/lib/observability/tracing"
"github.com/gravitational/teleport/lib/openssh"
"github.com/gravitational/teleport/lib/plugin"
"github.com/gravitational/teleport/lib/proxy"
"github.com/gravitational/teleport/lib/proxy/clusterdial"
"github.com/gravitational/teleport/lib/proxy/peer"
restricted "github.com/gravitational/teleport/lib/restrictedsession"
"github.com/gravitational/teleport/lib/reversetunnel"
"github.com/gravitational/teleport/lib/reversetunnelclient"
"github.com/gravitational/teleport/lib/service/servicecfg"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/services/local"
"github.com/gravitational/teleport/lib/srv"
"github.com/gravitational/teleport/lib/srv/alpnproxy"
alpnproxyauth "github.com/gravitational/teleport/lib/srv/alpnproxy/auth"
alpncommon "github.com/gravitational/teleport/lib/srv/alpnproxy/common"
"github.com/gravitational/teleport/lib/srv/app"
"github.com/gravitational/teleport/lib/srv/db"
"github.com/gravitational/teleport/lib/srv/desktop"
"github.com/gravitational/teleport/lib/srv/ingress"
"github.com/gravitational/teleport/lib/srv/regular"
"github.com/gravitational/teleport/lib/srv/transport/transportv1"
"github.com/gravitational/teleport/lib/system"
usagereporter "github.com/gravitational/teleport/lib/usagereporter/teleport"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/cert"
uw "github.com/gravitational/teleport/lib/versioncontrol/upgradewindow"
"github.com/gravitational/teleport/lib/web"
)
const (
// AuthIdentityEvent is generated when the Auth Servers identity has been
// initialized in the backend.
AuthIdentityEvent = "AuthIdentity"
// InstanceIdentityEvent is generated by the supervisor when the instance-level
// identity has been registered with the Auth server.
InstanceIdentityEvent = "InstanceIdentity"
// 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"
// KubeIdentityEvent is generated by the supervisor when the kubernetes
// service's identity has been registered with the Auth Server.
KubeIdentityEvent = "KubeIdentity"
// AppsIdentityEvent is generated when the identity of the application proxy
// service has been registered with the Auth Server.
AppsIdentityEvent = "AppsIdentity"
// DatabasesIdentityEvent is generated when the identity of the database
// proxy service has been registered with the auth server.
DatabasesIdentityEvent = "DatabasesIdentity"
// WindowsDesktopIdentityEvent is generated by the supervisor when the
// windows desktop service's identity has been registered with the Auth
// Server.
WindowsDesktopIdentityEvent = "WindowsDesktopIdentity"
// DiscoveryIdentityEvent is generated when the identity of the
DiscoveryIdentityEvent = "DiscoveryIdentityEvent"
// 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"
// DebugAppReady is generated when the debugging application has been started
// and is ready to serve requests.
DebugAppReady = "DebugAppReady"
// ProxyAgentPoolReady is generated when the proxy has initialized the
// remote cluster watcher (to spawn reverse tunnels) 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"
// NodeSSHReady is generated when the Teleport node has initialized a SSH server
// and is ready to start accepting SSH connections.
NodeSSHReady = "NodeReady"
// KubernetesReady is generated when the kubernetes service has been initialized.
KubernetesReady = "KubernetesReady"
// AppsReady is generated when the Teleport app proxy service is ready to
// start accepting connections.
AppsReady = "AppsReady"
// DatabasesReady is generated when the Teleport database proxy service
// is ready to start accepting connections.
DatabasesReady = "DatabasesReady"
// MetricsReady is generated when the Teleport metrics service is ready to
// start accepting connections.
MetricsReady = "MetricsReady"
// WindowsDesktopReady is generated when the Teleport windows desktop
// service is ready to start accepting connections.
WindowsDesktopReady = "WindowsDesktopReady"
// TracingReady is generated when the Teleport tracing service is ready to
// start exporting spans.
TracingReady = "TracingReady"
// InstanceReady is generated when the teleport instance control handle has
// been set up.
InstanceReady = "InstanceReady"
// DiscoveryReady is generated when the Teleport discovery service
// is ready to start accepting connections.
DiscoveryReady = "DiscoveryReady"
// 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"
// TeleportDegradedEvent is emitted whenever a service is operating in a
// degraded manner.
TeleportDegradedEvent = "TeleportDegraded"
// TeleportOKEvent is emitted whenever a service is operating normally.
TeleportOKEvent = "TeleportOKEvent"
)
const (
// embeddingInitialDelay is the time to wait before the first embedding
// routine is started.
embeddingInitialDelay = 10 * time.Second
// embeddingPeriod is the time between two embedding routines.
// A seventh jitter is applied on the period.
embeddingPeriod = 20 * time.Minute
)
// 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 ClientIdentity.
Client *auth.Client
// ReusedClient, if true, indicates that the client reference is owned by
// a different connector and should not be closed.
ReusedClient bool
}
// TunnelProxyResolver if non-nil, indicates that the client is connected to the Auth Server
// through the reverse SSH tunnel proxy
func (c *Connector) TunnelProxyResolver() reversetunnelclient.Resolver {
if c.Client == nil || c.Client.Dialer() == nil {
return nil
}
switch dialer := c.Client.Dialer().(type) {
case *reversetunnelclient.TunnelAuthDialer:
return dialer.Resolver
default:
return nil
}
}
// UseTunnel indicates if the client is connected directly to the Auth Server
// (false) or through the proxy (true).
func (c *Connector) UseTunnel() bool {
return c.TunnelProxyResolver() != nil
}
// Close closes resources associated with connector
func (c *Connector) Close() error {
if c.Client != nil && !c.ReusedClient {
return c.Client.Close()
}
return nil
}
// TeleportProcess structure holds the state of the Teleport daemon, controlling
// execution and configuration of the teleport services: ssh, auth and proxy.
type TeleportProcess struct {
Clock clockwork.Clock
sync.Mutex
Supervisor
Config *servicecfg.Config
// PluginsRegistry handles plugin registrations with Teleport services
PluginRegistry plugin.Registry
// localAuth has local auth server listed in case if this process
// has started with auth server role enabled
localAuth *auth.Server
// backend is the process' backend
backend backend.Backend
// auditLog is the initialized audit log
auditLog events.AuditLogSessionStreamer
// inventorySetupDelay lets us inject a one-time delay in the makeInventoryControlStream
// method that helps reduce log spam in the event of slow instance cert acquisition.
inventorySetupDelay sync.Once
// inventoryHandle is the downstream inventory control handle for this instance.
inventoryHandle inventory.DownstreamHandle
// instanceConnector contains the instance-level connector. this is created asynchronously
// and may not exist for some time if cert migrations are necessary.
instanceConnector *Connector
// instanceConnectorReady is closed when the isntance client becomes available.
instanceConnectorReady chan struct{}
// instanceConnectorReadyOnce protects instanceConnectorReady from double-close.
instanceConnectorReadyOnce sync.Once
// instanceRoles is the collection of enabled service roles (excludes things like "admin"
// and "instance" which aren't true user-facing services). The values in this mapping are
// the names of the associated identity events for these roles.
instanceRoles map[types.SystemRole]string
// identities of this process (credentials to auth sever, basically)
Identities map[types.SystemRole]*auth.Identity
// connectors is a list of connected clients and their identities
connectors map[types.SystemRole]*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 []servicecfg.FileDescriptor
// listenersClosed is a flag that indicates that the process should not open
// new listeners (for instance, because we're shutting down and we've already
// closed all the listeners)
listenersClosed bool
// 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
// log is a process-local log entry.
log logrus.FieldLogger
// 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
// reporter is used to report some in memory stats
reporter *backend.Reporter
// clusterFeatures contain flags for supported and unsupported features.
clusterFeatures proto.Features
// authSubjectiveAddr is the peer address of this process as seen by the auth
// server during the most recent ping (may be empty).
authSubjectiveAddr string
// cloudLabels is a set of labels imported from a cloud provider and shared between
// services.
cloudLabels labels.Importer
// TracingProvider is the provider to be used for exporting traces. In the event
// that tracing is disabled this will be a no-op provider that drops all spans.
TracingProvider *tracing.Provider
// SSHD is used to execute commands to update or validate OpenSSH config.
SSHD openssh.SSHD
}
type keyPairKey struct {
role types.SystemRole
reason string
}
// processIndex is an internal process index
// to help differentiate between two different teleport processes
// during in-process reload.
var processID int32
func nextProcessID() int32 {
return atomic.AddInt32(&processID, 1)
}
// GetAuthServer returns the process' auth server
func (process *TeleportProcess) GetAuthServer() *auth.Server {
return process.localAuth
}
// GetAuditLog returns the process' audit log
func (process *TeleportProcess) GetAuditLog() events.AuditLogSessionStreamer {
return process.auditLog
}
// GetBackend returns the process' backend
func (process *TeleportProcess) GetBackend() backend.Backend {
return process.backend
}
// OnHeartbeat generates the default OnHeartbeat callback for the specified component.
func (process *TeleportProcess) OnHeartbeat(component string) func(err error) {
return func(err error) {
if err != nil {
process.BroadcastEvent(Event{Name: TeleportDegradedEvent, Payload: component})
} else {
process.BroadcastEvent(Event{Name: TeleportOKEvent, Payload: component})
}
}
}
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
}
// getInstanceRoles returns the list of enabled service roles. this differs from simply
// checking the roles of the existing connectors in two key ways. First, pseudo-services
// like "admin" or "instance" are not included. Secondly, instance roles are recorded synchronously
// at the time the associated component's init function runs, as opposed to connectors which are
// initialized asynchronously in the background.
func (process *TeleportProcess) getInstanceRoles() []types.SystemRole {
process.Lock()
defer process.Unlock()
out := make([]types.SystemRole, 0, len(process.instanceRoles))
for role := range process.instanceRoles {
out = append(out, role)
}
return out
}
// SetExpectedInstanceRole marks a given instance role as active, storing the name of its associated
// identity event.
func (process *TeleportProcess) SetExpectedInstanceRole(role types.SystemRole, eventName string) {
process.Lock()
defer process.Unlock()
process.instanceRoles[role] = eventName
}
func (process *TeleportProcess) instanceRoleExpected(role types.SystemRole) bool {
process.Lock()
defer process.Unlock()
_, ok := process.instanceRoles[role]
return ok
}
// 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
}
// WaitForConnector is a utility function to wait for an identity event and cast
// the resulting payload as a *Connector. Returns (nil, nil) when the
// ExitContext is done, so error checking should happen on the connector rather
// than the error:
//
// conn, err := process.WaitForConnector("FooIdentity", log)
// if conn == nil {
// return trace.Wrap(err)
// }
func (process *TeleportProcess) WaitForConnector(identityEvent string, log logrus.FieldLogger) (*Connector, error) {
event, err := process.WaitForEvent(process.ExitContext(), identityEvent)
if err != nil {
if log != nil {
log.Debugf("Process is exiting.")
}
return nil, nil
}
if log != nil {
log.Debugf("Received event %q.", event.Name)
}
conn, ok := (event.Payload).(*Connector)
if !ok {
return nil, trace.BadParameter("unsupported connector type: %T", event.Payload)
}
return conn, nil
}
// GetID returns the process ID.
func (process *TeleportProcess) GetID() string {
return process.id
}
func (process *TeleportProcess) setClusterFeatures(features *proto.Features) {
process.Lock()
defer process.Unlock()
if features != nil {
process.clusterFeatures = *features
}
}
func (process *TeleportProcess) getClusterFeatures() proto.Features {
process.Lock()
defer process.Unlock()
return process.clusterFeatures
}
// setAuthSubjectiveAddr records the peer address that the auth server observed
// for this process during the most recent ping.
func (process *TeleportProcess) setAuthSubjectiveAddr(ip string) {
process.Lock()
defer process.Unlock()
if ip != "" {
process.authSubjectiveAddr = ip
}
}
// getAuthSubjectiveAddr accesses the peer address reported by the auth server
// during the most recent ping. May be empty.
func (process *TeleportProcess) getAuthSubjectiveAddr() string {
process.Lock()
defer process.Unlock()
return process.authSubjectiveAddr
}
// 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 types.SystemRole) (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 == types.RoleAdmin {
// for admin identity use local auth server
// because admin identity is requested by auth server
// itself
principals, dnsNames, err := process.getAdditionalPrincipals(role)
if err != nil {
return nil, trace.Wrap(err)
}
i, err = auth.GenerateIdentity(process.localAuth, id, principals, dnsNames)
if err != nil {
return nil, trace.Wrap(err)
}
} else {
// try to locate static identity provided in the file
i, err = process.findStaticIdentity(id)
if err != nil {
return nil, trace.Wrap(err)
}
process.log.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() ([]servicecfg.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 one event with the specified name (returns the
// latest such event if at least one has been broadcasted already, ignoring
// the context). Returns an error if the context is canceled before an event
// is received.
WaitForEvent(ctx context.Context, name string) (Event, error)
// 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 *servicecfg.Config) (Process, error)
func newTeleportProcess(cfg *servicecfg.Config) (Process, error) {
return NewTeleport(cfg)
}
// Run starts teleport processes, waits for signals
// and handles internal process reloads.
func Run(ctx context.Context, cfg servicecfg.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
// and no reload is necessary.
if err == ErrTeleportExited {
return nil
}
return trace.Wrap(err)
}
}
}
func waitAndReload(ctx context.Context, cfg servicecfg.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)
}
cfg.Log.Infof("Started in-process service reload.")
fileDescriptors, err := srv.ExportFileDescriptors()
if err != nil {
warnOnErr(srv.Close(), cfg.Log)
return nil, trace.Wrap(err)
}
newCfg := cfg
newCfg.FileDescriptors = fileDescriptors
newSrv, err := newTeleport(&newCfg)
if err != nil {
warnOnErr(srv.Close(), cfg.Log)
return nil, trace.Wrap(err, "failed to create a new service")
}
cfg.Log.Infof("Created new process.")
if err := newSrv.Start(); err != nil {
warnOnErr(srv.Close(), cfg.Log)
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()
if _, err := newSrv.WaitForEvent(startTimeoutCtx, TeleportReadyEvent); err != nil {
warnOnErr(newSrv.Close(), cfg.Log)
warnOnErr(srv.Close(), cfg.Log)
return nil, trace.BadParameter("the new service has failed to start")
}
cfg.Log.Infof("New service has started successfully.")
shutdownTimeout := cfg.ShutdownTimeout
if shutdownTimeout == 0 {
// The default shutdown timeout is very generous to avoid disrupting
// longer running connections.
shutdownTimeout = defaults.DefaultGracefulShutdownTimeout
}
cfg.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(services.ProcessReloadContext(timeoutCtx))
if timeoutCtx.Err() == context.DeadlineExceeded {
// The new service 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.
cfg.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 {
cfg.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 *servicecfg.Config) (*TeleportProcess, error) {
var err error
// auth and proxy benefit from precomputing keys since they can experience spikes in key
// generation due to web session creation and recorded session creation respectively.
// for all other agents precomputing keys consumes excess resources.
if cfg.Auth.Enabled || cfg.Proxy.Enabled {
native.PrecomputeKeys()
}
// Before we do anything reset the SIGINT handler back to the default.
system.ResetInterruptSignalHandler()
// Validate the config before accessing it.
if err := servicecfg.ValidateConfig(cfg); err != nil {
return nil, trace.Wrap(err, "configuration error")
}
processID := fmt.Sprintf("%v", nextProcessID())
cfg.Log = utils.WrapLogger(cfg.Log.WithFields(logrus.Fields{
trace.Component: teleport.Component(teleport.ComponentProcess, processID),
"pid": fmt.Sprintf("%v.%v", os.Getpid(), processID),
}))
// If FIPS mode was requested make sure binary is build against BoringCrypto.
if cfg.FIPS {
if !modules.GetModules().IsBoringBinary() {
return nil, trace.BadParameter("binary not compiled against BoringCrypto, check " +
"that Enterprise FIPS release was downloaded from " +
"a Teleport account https://teleport.sh")
}
}
switch cfg.Auth.Preference.GetRequireMFAType() {
case types.RequireMFAType_SESSION_AND_HARDWARE_KEY, types.RequireMFAType_HARDWARE_KEY_TOUCH:
if modules.GetModules().BuildType() != modules.BuildEnterprise {
return nil, trace.AccessDenied("Hardware Key support is only available with an enterprise license")
}
}
// create the data directory if it's missing
_, err = os.Stat(cfg.DataDir)
if os.IsNotExist(err) {
err := os.MkdirAll(cfg.DataDir, os.ModeDir|0o700)
if err != nil {
if errors.Is(err, fs.ErrPermission) {
cfg.Log.Errorf("Teleport does not have permission to write to: %v. Ensure that you are running as a user with appropriate permissions.", cfg.DataDir)
}
return nil, trace.ConvertSystemError(err)
}
}
if len(cfg.FileDescriptors) == 0 {
cfg.FileDescriptors, err = importFileDescriptors(cfg.Log)
if err != nil {
return nil, trace.Wrap(err)
}
}
supervisor := NewSupervisor(processID, cfg.Log)
storage, err := auth.NewProcessStorage(supervisor.ExitContext(), filepath.Join(cfg.DataDir, teleport.ComponentProcess))
if err != nil {
return nil, trace.Wrap(err)
}
var kubeBackend kubernetesBackend
// If running in a Kubernetes Pod we must init the backend storage for `host_uuid` storage/retrieval.
if kubernetes.InKubeCluster() {
kubeBackend, err = kubernetes.New()
if err != nil {
return nil, trace.Wrap(err)
}
}
// Load `host_uuid` from different storages. If this process is running in a Kubernetes Cluster,
// readOrGenerateHostID will try to read the `host_uuid` from the Kubernetes Secret. If the
// key is empty or if not running in a Kubernetes Cluster, it will read the
// `host_uuid` from local data directory.
// If no host id is available, it will generate a new host id and persist it to available storages.
if err := readOrGenerateHostID(supervisor.ExitContext(), cfg, kubeBackend); err != nil {
return nil, trace.Wrap(err)
}
_, err = uuid.Parse(cfg.HostUUID)
if err != nil && !aws.IsEC2NodeID(cfg.HostUUID) {
cfg.Log.Warnf("Host UUID %q is not a true UUID (not eligible for UUID-based proxying)", cfg.HostUUID)
}
if cfg.Clock == nil {
cfg.Clock = clockwork.NewRealClock()
}
if cfg.PluginRegistry == nil {
cfg.PluginRegistry = plugin.NewRegistry()
}
var cloudLabels labels.Importer
// Check if we're on a cloud instance, and if we should override the node's hostname.
imClient := cfg.InstanceMetadataClient
if imClient == nil {
imClient, err = cloud.DiscoverInstanceMetadata(supervisor.ExitContext())
if err != nil && !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
}
if imClient != nil && imClient.GetType() != types.InstanceMetadataTypeDisabled {
cloudHostname, err := imClient.GetHostname(supervisor.ExitContext())
if err == nil {
cloudHostname = strings.ReplaceAll(cloudHostname, " ", "_")
if utils.IsValidHostname(cloudHostname) {
cfg.Log.Infof("Found %q tag in cloud instance. Using %q as hostname.", types.CloudHostnameTag, cloudHostname)
cfg.Hostname = cloudHostname
// cloudHostname exists but is not a valid hostname.
} else if cloudHostname != "" {
cfg.Log.Infof("Found %q tag in cloud instance, but %q is not a valid hostname.", types.CloudHostnameTag, cloudHostname)
}
} else if !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
cloudLabels, err = labels.NewCloudImporter(supervisor.ExitContext(), &labels.CloudConfig{
Client: imClient,
Clock: cfg.Clock,
})
if err != nil {
return nil, trace.Wrap(err)
}
}
if cloudLabels != nil {
cloudLabels.Start(supervisor.ExitContext())
}
// 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.NewClusterNameWithRandomID(types.ClusterNameSpecV2{
ClusterName: cfg.Hostname,
})
if err != nil {
return nil, trace.Wrap(err)
}
}
process := &TeleportProcess{
PluginRegistry: cfg.PluginRegistry,
Clock: cfg.Clock,
Supervisor: supervisor,
Config: cfg,
instanceConnectorReady: make(chan struct{}),
instanceRoles: make(map[types.SystemRole]string),
Identities: make(map[types.SystemRole]*auth.Identity),
connectors: make(map[types.SystemRole]*Connector),
importedDescriptors: cfg.FileDescriptors,
storage: storage,
id: processID,
log: cfg.Log,
keyPairs: make(map[keyPairKey]KeyPair),
cloudLabels: cloudLabels,
TracingProvider: tracing.NoopProvider(),
}
process.registerExpectedServices(cfg)
process.log = cfg.Log.WithFields(logrus.Fields{
trace.Component: teleport.Component(teleport.ComponentProcess, process.id),
})
// 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 process.Config.Auth.Enabled && len(process.Config.AuthServerAddresses()) == 0 {
process.Config.SetAuthServerAddress(process.Config.Auth.ListenAddr)
}
if len(process.Config.AuthServerAddresses()) != 0 && process.Config.AuthServerAddresses()[0].Port(0) == 0 {
// port appears undefined, attempt early listener creation so that we can get the real port
listener, err := process.importOrCreateListener(ListenerAuth, process.Config.Auth.ListenAddr.Addr)
if err == nil {
process.Config.SetAuthServerAddress(utils.FromAddr(listener.Addr()))
}
}
upgraderKind := os.Getenv("TELEPORT_EXT_UPGRADER")
// note: we must create the inventory handle *after* registerExpectedServices because that function determines
// the list of services (instance roles) to be included in the heartbeat.
process.inventoryHandle = inventory.NewDownstreamHandle(process.makeInventoryControlStreamWhenReady, proto.UpstreamInventoryHello{
ServerID: cfg.HostUUID,
Version: teleport.Version,
Services: process.getInstanceRoles(),
Hostname: cfg.Hostname,
ExternalUpgrader: upgraderKind,
})
process.inventoryHandle.RegisterPingHandler(func(sender inventory.DownstreamSender, ping proto.DownstreamInventoryPing) {
process.log.Infof("Handling incoming inventory ping (id=%d).", ping.ID)
err := sender.Send(process.ExitContext(), proto.UpstreamInventoryPong{
ID: ping.ID,
})
if err != nil {
process.log.Warnf("Failed to respond to inventory ping (id=%d): %v", ping.ID, err)
}
})
// if an external upgrader is defined, we need to set up an appropriate upgrade window exporter.
if upgraderKind != "" {
if process.Config.Auth.Enabled || process.Config.Proxy.Enabled {
process.log.Warnf("Use of external upgraders on control-plane instances is not recommended.")
}
driver, err := uw.NewDriver(upgraderKind)
if err != nil {
return nil, trace.Wrap(err)
}
exporter, err := uw.NewExporter(uw.ExporterConfig[inventory.DownstreamSender]{