-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
windows_server.go
1329 lines (1198 loc) · 46 KB
/
windows_server.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 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 desktop
import (
"bytes"
"context"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/go-ldap/ldap/v3"
"github.com/jonboulle/clockwork"
"github.com/sirupsen/logrus"
"github.com/gravitational/trace"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client/proto"
apidefaults "github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/types"
"github.com/gravitational/teleport/api/types/events"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/defaults"
libevents "github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/events/filesessions"
"github.com/gravitational/teleport/lib/limiter"
"github.com/gravitational/teleport/lib/modules"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/srv"
"github.com/gravitational/teleport/lib/srv/desktop/rdp/rdpclient"
"github.com/gravitational/teleport/lib/srv/desktop/tdp"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
)
const (
// dnsDialTimeout is the timeout for dialing the LDAP server
// when resolving Windows Desktop hostnames
dnsDialTimeout = 5 * time.Second
// ldapDialTimeout is the timeout for dialing the LDAP server
// when making an initial connection
ldapDialTimeout = 5 * time.Second
// ldapRequestTimeout is the timeout for making LDAP requests.
// It is larger than the dial timeout because LDAP queries in large
// Active Directory environments may take longer to complete.
ldapRequestTimeout = 20 * time.Second
// windowsDesktopCertTTL is the TTL for Teleport-issued Windows Certificates.
// Certificates are requested on each connection attempt, so the TTL is
// deliberately set to a small value to give enough time to establish a
// single desktop session.
windowsDesktopCertTTL = 5 * time.Minute
// windowsDesktopServiceCertTTL is the TTL for certificates issued to the
// Windows Desktop Service in order to authenticate with the LDAP server.
// It is set longer than the Windows certificates for users because it is
// not used for interactive login and is only used when issuing certs for
// a restrictive service account.
windowsDesktopServiceCertTTL = 8 * time.Hour
// windowsDesktopServiceCertRetryInterval indicates how often to retry
// issuing an LDAP certificate if the operation fails.
windowsDesktopServiceCertRetryInterval = 10 * time.Minute
)
// WindowsService implements the RDP-based Windows desktop access service.
//
// This service accepts mTLS connections from the proxy, establishes RDP
// connections to Windows hosts and translates RDP into Teleport's desktop
// protocol.
type WindowsService struct {
cfg WindowsServiceConfig
middleware *auth.Middleware
lc *ldapClient
mu sync.Mutex // mu protects the fields that follow
ldapInitialized bool
ldapCertRenew *time.Timer
streamer libevents.Streamer
// lastDisoveryResults stores the results of the most recent LDAP search
// when desktop discovery is enabled.
// no synchronization is necessary because this is only read/written from
// the reconciler goroutine.
lastDiscoveryResults types.ResourcesWithLabels
// Windows hosts discovered via LDAP likely won't resolve with the
// default DNS resolver, so we need a custom resolver that will
// query the domain controller.
dnsResolver *net.Resolver
// clusterName is the cached local cluster name, to avoid calling
// cfg.AccessPoint.GetClusterName multiple times.
clusterName string
closeCtx context.Context
close func()
}
// WindowsServiceConfig contains all necessary configuration values for a
// WindowsService.
type WindowsServiceConfig struct {
// Log is the logging sink for the service.
Log logrus.FieldLogger
// Clock provides current time.
Clock clockwork.Clock
DataDir string
// Authorizer is used to authorize requests.
Authorizer auth.Authorizer
// LockWatcher is used to monitor for new locks.
LockWatcher *services.LockWatcher
// Emitter emits audit log events.
Emitter events.Emitter
// TLS is the TLS server configuration.
TLS *tls.Config
// AccessPoint is the Auth API client (with caching).
AccessPoint auth.WindowsDesktopAccessPoint
// AuthClient is the Auth API client (without caching).
AuthClient auth.ClientI
// ConnLimiter limits the number of active connections per client IP.
ConnLimiter *limiter.ConnectionsLimiter
// Heartbeat contains configuration for service heartbeats.
Heartbeat HeartbeatConfig
// HostLabelsFn gets labels that should be applied to a Windows host.
HostLabelsFn func(host string) map[string]string
// LDAPConfig contains parameters for connecting to an LDAP server.
LDAPConfig
// DiscoveryBaseDN is the base DN for searching for Windows Desktops.
// Desktop discovery is disabled if this field is empty.
DiscoveryBaseDN string
// DiscoveryLDAPFilters are additional LDAP filters for searching for
// Windows Desktops. If multiple filters are specified, they are ANDed
// together into a single search.
DiscoveryLDAPFilters []string
}
// LDAPConfig contains parameters for connecting to an LDAP server.
type LDAPConfig struct {
// Addr is the LDAP server address in the form host:port.
// Standard port is 636 for LDAPS.
Addr string
// Domain is an Active Directory domain name, like "example.com".
Domain string
// Username is an LDAP username, like "EXAMPLE\Administrator", where
// "EXAMPLE" is the NetBIOS version of Domain.
Username string
// InsecureSkipVerify decides whether whether we skip verifying with the LDAP server's CA when making the LDAPS connection.
InsecureSkipVerify bool
// CA is an optional CA cert to be used for verification if InsecureSkipVerify is set to false.
CA *x509.Certificate
}
func (cfg LDAPConfig) check() error {
if cfg.Addr == "" {
return trace.BadParameter("missing Addr in LDAPConfig")
}
if cfg.Domain == "" {
return trace.BadParameter("missing Domain in LDAPConfig")
}
if cfg.Username == "" {
return trace.BadParameter("missing Username in LDAPConfig")
}
return nil
}
func (cfg LDAPConfig) domainDN() string {
var sb strings.Builder
parts := strings.Split(cfg.Domain, ".")
for _, p := range parts {
if sb.Len() > 0 {
sb.WriteString(",")
}
sb.WriteString("DC=")
sb.WriteString(p)
}
return sb.String()
}
// HeartbeatConfig contains the configuration for service heartbeats.
type HeartbeatConfig struct {
// HostUUID is the UUID of the host that this service runs on. Used as the
// name of the created API object.
HostUUID string
// PublicAddr is the public address of this service.
PublicAddr string
// OnHeartbeat is called after each heartbeat attempt.
OnHeartbeat func(error)
// StaticHosts is an optional list of static Windows hosts to register.
StaticHosts []utils.NetAddr
}
func (cfg *WindowsServiceConfig) checkAndSetDiscoveryDefaults() error {
switch {
case cfg.DiscoveryBaseDN == types.Wildcard:
cfg.DiscoveryBaseDN = cfg.domainDN()
case len(cfg.DiscoveryBaseDN) > 0:
if _, err := ldap.ParseDN(cfg.DiscoveryBaseDN); err != nil {
return trace.BadParameter("WindowsServiceConfig contains an invalid base_dn: %v", err)
}
}
for _, filter := range cfg.DiscoveryLDAPFilters {
if _, err := ldap.CompileFilter(filter); err != nil {
return trace.BadParameter("WindowsServiceConfig contains an invalid LDAP filter %q: %v", filter, err)
}
}
return nil
}
func (cfg *WindowsServiceConfig) CheckAndSetDefaults() error {
if cfg.Log == nil {
cfg.Log = logrus.New().WithField(trace.Component, teleport.ComponentWindowsDesktop)
}
if cfg.Clock == nil {
cfg.Clock = clockwork.NewRealClock()
}
if cfg.Authorizer == nil {
return trace.BadParameter("WindowsServiceConfig is missing Authorizer")
}
if cfg.LockWatcher == nil {
return trace.BadParameter("WindowsServiceConfig is missing LockWatcher")
}
if cfg.Emitter == nil {
return trace.BadParameter("WindowsServiceConfig is missing Emitter")
}
if cfg.TLS == nil {
return trace.BadParameter("WindowsServiceConfig is missing TLS")
}
if cfg.AccessPoint == nil {
return trace.BadParameter("WindowsServiceConfig is missing AccessPoint")
}
if cfg.AuthClient == nil {
return trace.BadParameter("WindowsServiceConfig is missing AuthClient")
}
if cfg.ConnLimiter == nil {
return trace.BadParameter("WindowsServiceConfig is missing ConnLimiter")
}
if err := cfg.Heartbeat.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
if err := cfg.LDAPConfig.check(); err != nil {
return trace.Wrap(err)
}
if err := cfg.checkAndSetDiscoveryDefaults(); err != nil {
return trace.Wrap(err)
}
return nil
}
func (cfg *HeartbeatConfig) CheckAndSetDefaults() error {
if cfg.HostUUID == "" {
return trace.BadParameter("HeartbeatConfig is missing HostUUID")
}
if cfg.PublicAddr == "" {
return trace.BadParameter("HeartbeatConfig is missing PublicAddr")
}
if cfg.OnHeartbeat == nil {
return trace.BadParameter("HeartbeatConfig is missing OnHeartbeat")
}
return nil
}
// NewWindowsService initializes a new WindowsService.
//
// To start serving connections, call Serve.
// When done serving connections, call Close.
func NewWindowsService(cfg WindowsServiceConfig) (*WindowsService, error) {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
// It's possible to provide a CA certificate for the LDAP server
// and to skip TLS valdiation, though this may be an error, so try
// to warn the user.
// (You may need this configuration in order to use certificates to
// authenticate with LDAP when the LDAP server name is not correct
// in the certificate).
if cfg.LDAPConfig.CA != nil && cfg.LDAPConfig.InsecureSkipVerify {
cfg.Log.Warn("LDAP configuration specifies both der_ca_file and insecure_skip_verify." +
"TLS connections to the LDAP server will not be verified. If this is intentional, disregard this warning.")
}
clusterName, err := cfg.AccessPoint.GetClusterName()
if err != nil {
return nil, trace.Wrap(err, "fetching cluster name")
}
// Here we assume the LDAP server is an Active Directory Domain Controller,
// which means it should also be a DNS server that can resolve Windows hosts.
dnsServer, _, err := net.SplitHostPort(cfg.LDAPConfig.Addr)
if err != nil {
return nil, trace.Wrap(err)
}
dnsAddr := net.JoinHostPort(dnsServer, "53")
cfg.Log.Debugln("DNS lookups will be performed against", dnsAddr)
ctx, close := context.WithCancel(context.Background())
s := &WindowsService{
cfg: cfg,
middleware: &auth.Middleware{
AccessPoint: cfg.AccessPoint,
AcceptedUsage: []string{teleport.UsageWindowsDesktopOnly},
},
dnsResolver: &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
// Ignore the address provided, and always explicitly dial
// the domain controller.
d := net.Dialer{Timeout: dnsDialTimeout}
return d.DialContext(ctx, network, dnsAddr)
},
},
lc: &ldapClient{cfg: cfg.LDAPConfig},
clusterName: clusterName.GetClusterName(),
closeCtx: ctx,
close: close,
}
// initialize LDAP - if this fails it will automatically schedule a retry.
// we don't want to return an error in this case, because failure to start
// the service brings down the entire Teleport process
if err := s.initializeLDAP(); err != nil {
s.cfg.Log.WithError(err).Error("initializing LDAP client, will retry")
}
ok := false
defer func() {
if !ok {
s.Close()
}
}()
recConfig, err := s.cfg.AccessPoint.GetSessionRecordingConfig(s.closeCtx)
if err != nil {
return nil, trace.Wrap(err)
}
streamer, err := s.newStreamer(s.closeCtx, recConfig)
if err != nil {
return nil, trace.Wrap(err)
}
s.streamer = streamer
if err := s.startServiceHeartbeat(); err != nil {
return nil, trace.Wrap(err)
}
if err := s.startStaticHostHeartbeats(); err != nil {
return nil, trace.Wrap(err)
}
if len(s.cfg.DiscoveryBaseDN) > 0 {
if err := s.startDesktopDiscovery(); err != nil {
return nil, trace.Wrap(err)
}
} else if len(s.cfg.Heartbeat.StaticHosts) == 0 {
s.cfg.Log.Warnln("desktop discovery via LDAP is disabled, and no hosts are defined in the configuration; there will be no Windows desktops available to connect")
} else {
s.cfg.Log.Infoln("desktop discovery via LDAP is disabled, set 'base_dn' to enable")
}
ok = true
return s, nil
}
func (s *WindowsService) newStreamWriter(record bool, sessionID string) (libevents.StreamWriter, error) {
return libevents.NewAuditWriter(libevents.AuditWriterConfig{
Component: teleport.ComponentWindowsDesktop,
Namespace: apidefaults.Namespace,
Context: s.closeCtx,
Clock: s.cfg.Clock,
ClusterName: s.clusterName,
SessionID: session.ID(sessionID),
Streamer: s.streamer,
ServerID: s.cfg.Heartbeat.HostUUID,
RecordOutput: record,
})
}
// newStreamer creates a streamer (sync or async) based on the cluster configuration.
// Synchronous streamers send events directly to the auth server, and blocks if the server
// cannot keep up. Asynchronous streamers buffers the events to disk and uploads them later.
func (s *WindowsService) newStreamer(ctx context.Context, recConfig types.SessionRecordingConfig) (libevents.Streamer, error) {
if services.IsRecordSync(recConfig.GetMode()) {
s.cfg.Log.Debugf("using sync streamer (for mode %v)", recConfig.GetMode())
return s.cfg.AuthClient, nil
}
s.cfg.Log.Debugf("using async streamer (for mode %v)", recConfig.GetMode())
uploadDir := filepath.Join(s.cfg.DataDir, teleport.LogsDir, teleport.ComponentUpload,
libevents.StreamingLogsDir, apidefaults.Namespace)
// ensure upload dir exists
_, err := utils.StatDir(uploadDir)
if trace.IsNotFound(err) {
s.cfg.Log.Debugf("Creating upload dir %v.", uploadDir)
if err := os.MkdirAll(uploadDir, 0755); err != nil {
return nil, trace.Wrap(err)
}
} else if err != nil {
return nil, trace.Wrap(err)
}
fileStreamer, err := filesessions.NewStreamer(uploadDir)
if err != nil {
return nil, trace.Wrap(err)
}
return libevents.NewTeeStreamer(fileStreamer, s.cfg.Emitter), nil
}
func (s *WindowsService) tlsConfigForLDAP() (*tls.Config, error) {
// trim NETBIOS name from username
user := s.cfg.Username
if i := strings.LastIndex(s.cfg.Username, `\`); i != -1 {
user = user[i+1:]
}
certDER, keyDER, err := s.generateCredentials(s.closeCtx, user, s.cfg.Domain, windowsDesktopServiceCertTTL)
if err != nil {
return nil, trace.Wrap(err)
}
cert, err := x509.ParseCertificate(certDER)
if err != nil {
return nil, trace.Wrap(err, "parsing cert DER")
}
key, err := x509.ParsePKCS1PrivateKey(keyDER)
if err != nil {
return nil, trace.Wrap(err, "parsing key DER")
}
tc := &tls.Config{
Certificates: []tls.Certificate{
{
Certificate: [][]byte{cert.Raw},
PrivateKey: key,
},
},
InsecureSkipVerify: s.cfg.InsecureSkipVerify,
}
if s.cfg.CA != nil {
pool := x509.NewCertPool()
pool.AddCert(s.cfg.CA)
tc.RootCAs = pool
}
return tc, nil
}
// initializeLDAP requests a TLS certificate from the auth server to be used for
// authenticating with the LDAP server. If the certificate is obtained, and
// authentication with the LDAP server succeeds, it schedules a renewal to take
// place before the certificate expires. If we are unable to obtain a certificate
// and authenticate with the LDAP server, then the operation will be automatically
// retried.
func (s *WindowsService) initializeLDAP() error {
tc, err := s.tlsConfigForLDAP()
if trace.IsAccessDenied(err) && modules.GetModules().BuildType() == modules.BuildEnterprise {
s.cfg.Log.Warn("Could not generate certificate for LDAPS. Ensure that the auth server is licensed for desktop access.")
}
if err != nil {
s.mu.Lock()
s.ldapInitialized = false
// in the case where we're not licensed for desktop access, we retry less frequently,
// since this is likely not an intermittent error that will resolve itself quickly
s.scheduleNextLDAPCertRenewalLocked(windowsDesktopServiceCertRetryInterval * 3)
s.mu.Unlock()
return trace.Wrap(err)
}
conn, err := ldap.DialURL("ldaps://"+s.cfg.Addr,
ldap.DialWithTLSDialer(tc, &net.Dialer{Timeout: ldapDialTimeout}))
if err != nil {
s.mu.Lock()
s.ldapInitialized = false
s.scheduleNextLDAPCertRenewalLocked(windowsDesktopServiceCertRetryInterval)
s.mu.Unlock()
return trace.Wrap(err, "dial")
}
conn.SetTimeout(ldapRequestTimeout)
s.lc.setClient(conn)
// Note: admin still needs to import our CA into the Group Policy following
// https://docs.vmware.com/en/VMware-Horizon-7/7.13/horizon-installation/GUID-7966AE16-D98F-430E-A916-391E8EAAFE18.html
//
// We can find the group policy object via LDAP, but it only contains an
// SMB file path with the actual policy. See
// https://en.wikipedia.org/wiki/Group_Policy
//
// In theory, we could update the policy file(s) over SMB following
// https://docs.microsoft.com/en-us/previous-versions/windows/desktop/policy/registry-policy-file-format,
// but I'm leaving this for later.
//
if err := s.updateCA(s.closeCtx); err != nil {
return trace.Wrap(err)
}
s.mu.Lock()
s.ldapInitialized = true
s.scheduleNextLDAPCertRenewalLocked(windowsDesktopServiceCertTTL / 3)
s.mu.Unlock()
return nil
}
// scheduleNextLDAPCertRenewalLocked schedules a renewal of our LDAP credentials
// after some amount of time has elapsed. If an existing renewal is already
// scheduled, it is canceled and this new one takes its place.
//
// The lock on s.mu MUST be held.
func (s *WindowsService) scheduleNextLDAPCertRenewalLocked(after time.Duration) {
if s.ldapCertRenew != nil {
s.ldapCertRenew.Reset(after)
} else {
s.ldapCertRenew = time.AfterFunc(after, func() {
if err := s.initializeLDAP(); err != nil {
s.cfg.Log.WithError(err).Error("couldn't renew certificate for LDAP auth")
}
})
}
}
func (s *WindowsService) startServiceHeartbeat() error {
heartbeat, err := srv.NewHeartbeat(srv.HeartbeatConfig{
Context: s.closeCtx,
Component: teleport.ComponentWindowsDesktop,
Mode: srv.HeartbeatModeWindowsDesktopService,
Announcer: s.cfg.AccessPoint,
GetServerInfo: s.getServiceHeartbeatInfo,
KeepAlivePeriod: apidefaults.ServerKeepAliveTTL(),
AnnouncePeriod: apidefaults.ServerAnnounceTTL/2 + utils.RandomDuration(apidefaults.ServerAnnounceTTL/10),
CheckPeriod: defaults.HeartbeatCheckPeriod,
ServerTTL: apidefaults.ServerAnnounceTTL,
OnHeartbeat: s.cfg.Heartbeat.OnHeartbeat,
})
if err != nil {
return trace.Wrap(err)
}
go func() {
if err := heartbeat.Run(); err != nil {
s.cfg.Log.WithError(err).Error("Heartbeat ended with error")
}
}()
return nil
}
// startStaticHostHeartbeats spawns heartbeat routines for all static hosts in
// this service. We use heartbeats instead of registering once at startup to
// support expiration.
//
// When a WindowsService with a list of static hosts disappears, those hosts
// should eventually get cleaned up. But they should exist as long as the
// service itself is running.
func (s *WindowsService) startStaticHostHeartbeats() error {
for _, host := range s.cfg.Heartbeat.StaticHosts {
heartbeat, err := srv.NewHeartbeat(srv.HeartbeatConfig{
Context: s.closeCtx,
Component: teleport.ComponentWindowsDesktop,
Mode: srv.HeartbeatModeWindowsDesktop,
Announcer: s.cfg.AccessPoint,
GetServerInfo: s.staticHostHeartbeatInfo(host, s.cfg.HostLabelsFn),
KeepAlivePeriod: apidefaults.ServerKeepAliveTTL(),
AnnouncePeriod: apidefaults.ServerAnnounceTTL/2 + utils.RandomDuration(apidefaults.ServerAnnounceTTL/10),
CheckPeriod: defaults.HeartbeatCheckPeriod,
ServerTTL: apidefaults.ServerAnnounceTTL,
OnHeartbeat: s.cfg.Heartbeat.OnHeartbeat,
})
if err != nil {
return trace.Wrap(err)
}
go func() {
if err := heartbeat.Run(); err != nil {
s.cfg.Log.WithError(err).Error("Heartbeat ended with error")
}
}()
}
return nil
}
// Close instructs the server to stop accepting new connections and abort all
// established ones. Close does not wait for the connections to be finished.
func (s *WindowsService) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
if s.ldapCertRenew != nil {
s.ldapCertRenew.Stop()
}
s.close()
s.lc.close()
return nil
}
// Serve starts serving TLS connections for plainLis. plainLis should be a TCP
// listener and Serve will handle TLS internally.
func (s *WindowsService) Serve(plainLis net.Listener) error {
lis := tls.NewListener(plainLis, s.cfg.TLS)
defer lis.Close()
for {
select {
case <-s.closeCtx.Done():
return trace.Wrap(s.closeCtx.Err())
default:
}
conn, err := lis.Accept()
if err != nil {
if utils.IsOKNetworkError(err) || trace.IsConnectionProblem(err) {
return nil
}
return trace.Wrap(err)
}
proxyConn, ok := conn.(*tls.Conn)
if !ok {
return trace.ConnectionProblem(nil, "Got %T from TLS listener, expected *tls.Conn", conn)
}
go s.handleConnection(proxyConn)
}
}
func (s *WindowsService) ldapReady() bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.ldapInitialized
}
// handleConnection handles TLS connections from a Teleport proxy.
// It authenticates and authorizes the connection, and then begins
// translating the TDP messages from the proxy into native RDP.
func (s *WindowsService) handleConnection(proxyConn *tls.Conn) {
log := s.cfg.Log
tdpConn := tdp.NewConn(proxyConn)
defer tdpConn.Close()
// Inline function to enforce that we are centralizing TDP Error sending in this function.
sendTDPError := func(message string) {
if err := tdpConn.SendError(message); err != nil {
s.cfg.Log.Errorf("Failed to send TDP error message %v", err)
}
}
// don't handle connections until the LDAP initialization retry loop has succeeded
// (it would fail anyway, but this presents a better error to the user)
if !s.ldapReady() {
const msg = "This service cannot accept connections until LDAP initialization has completed."
log.Error(msg)
sendTDPError(msg)
return
}
// Check connection limits.
remoteAddr, _, err := net.SplitHostPort(proxyConn.RemoteAddr().String())
if err != nil {
log.WithError(err).Errorf("Could not parse client IP from %q", proxyConn.RemoteAddr().String())
sendTDPError("Internal error.")
return
}
log = log.WithField("client-ip", remoteAddr)
if err := s.cfg.ConnLimiter.AcquireConnection(remoteAddr); err != nil {
log.WithError(err).Warning("Connection limit exceeded, rejecting connection")
sendTDPError("Connection limit exceeded.")
return
}
defer s.cfg.ConnLimiter.ReleaseConnection(remoteAddr)
// Authenticate the client.
ctx, err := s.middleware.WrapContextWithUser(s.closeCtx, proxyConn)
if err != nil {
log.WithError(err).Warning("mTLS authentication failed for incoming connection")
sendTDPError("Connection authentication failed.")
return
}
log.Debug("Authenticated Windows desktop connection")
authContext, err := s.cfg.Authorizer.Authorize(ctx)
if err != nil {
log.WithError(err).Warning("authorization failed for Windows desktop connection")
sendTDPError("Connection authorization failed.")
return
}
// Fetch the target desktop info. Name of the desktop is passed via SNI.
desktopName := strings.TrimSuffix(proxyConn.ConnectionState().ServerName, SNISuffix)
log = log.WithField("desktop-name", desktopName)
desktops, err := s.cfg.AccessPoint.GetWindowsDesktops(ctx,
types.WindowsDesktopFilter{HostID: s.cfg.Heartbeat.HostUUID, Name: desktopName})
if err != nil {
log.WithError(err).Warning("Failed to fetch desktop by name")
sendTDPError("Teleport failed to find the requested desktop in its database.")
return
}
if len(desktops) == 0 {
log.Error("no windows desktops with HostID %s and Name %s", s.cfg.Heartbeat.HostUUID,
desktopName)
sendTDPError(fmt.Sprintf("Could not find desktop %v.", desktopName))
return
}
desktop := desktops[0]
log = log.WithField("desktop-addr", desktop.GetAddr())
log.Debug("Connecting to Windows desktop")
defer log.Debug("Windows desktop disconnected")
if err := s.connectRDP(ctx, log, tdpConn, desktop, authContext); err != nil {
log.Errorf("RDP connection failed: %v", err)
sendTDPError("RDP connection failed.")
return
}
}
func (s *WindowsService) connectRDP(ctx context.Context, log logrus.FieldLogger, tdpConn *tdp.Conn, desktop types.WindowsDesktop, authCtx *auth.Context) error {
identity := authCtx.Identity.GetIdentity()
netConfig, err := s.cfg.AccessPoint.GetClusterNetworkingConfig(ctx)
if err != nil {
return trace.Wrap(err)
}
authPref, err := s.cfg.AccessPoint.GetAuthPreference(ctx)
if err != nil {
return trace.Wrap(err)
}
sessionID := session.NewID()
// in order for the session to be recorded, the cluster's session recording mode must
// not be "off" and the user's roles must enable recording
recordSession := false
if authCtx.Checker.RecordDesktopSession() {
recConfig, err := s.cfg.AccessPoint.GetSessionRecordingConfig(ctx)
if err != nil {
return trace.Wrap(err)
}
recordSession = recConfig.GetMode() != types.RecordOff
} else {
log.Infof("desktop session %v will not be recorded, user %v's roles disable recording", string(sessionID), authCtx.User.GetName())
}
sw, err := s.newStreamWriter(recordSession, string(sessionID))
if err != nil {
return trace.Wrap(err)
}
// Closing the stream writer is needed to flush all recorded data
// and trigger the upload. Do it in a goroutine since depending on
// the session size it can take a while, and we don't want to block
// the client.
defer func() {
go func() {
if err := sw.Close(context.Background()); err != nil {
log.WithError(err).Errorf("closing stream writer for desktop session %v", sessionID.String())
}
}()
}()
var windowsUser string
authorize := func(login string) error {
windowsUser = login // capture attempted login user
mfaParams := services.AccessMFAParams{
Verified: identity.MFAVerified != "",
AlwaysRequired: authPref.GetRequireSessionMFA(),
}
return authCtx.Checker.CheckAccess(
desktop,
mfaParams,
services.NewWindowsLoginMatcher(login))
}
// Use a context that is canceled when we're done handling
// this connection. This ensures that the connection monitor
// will stop checking for idle activity when the connection
// is closed.
ctx, cancel := context.WithCancel(ctx)
defer cancel()
delay := timer()
tdpConn.OnSend = s.makeTDPSendHandler(ctx, sw, delay, &identity, string(sessionID), desktop.GetAddr())
tdpConn.OnRecv = s.makeTDPReceiveHandler(ctx, sw, delay, &identity, string(sessionID), desktop.GetAddr())
sessionStartTime := s.cfg.Clock.Now().UTC().Round(time.Millisecond)
rdpc, err := rdpclient.New(ctx, rdpclient.Config{
Log: log,
GenerateUserCert: func(ctx context.Context, username string, ttl time.Duration) (certDER, keyDER []byte, err error) {
return s.generateCredentials(ctx, username, desktop.GetDomain(), ttl)
},
CertTTL: windowsDesktopCertTTL,
Addr: desktop.GetAddr(),
Conn: tdpConn,
AuthorizeFn: authorize,
AllowClipboard: authCtx.Checker.DesktopClipboard(),
})
if err != nil {
s.onSessionStart(ctx, &identity, sessionStartTime, windowsUser, string(sessionID), desktop, err)
return trace.Wrap(err)
}
monitorCfg := srv.MonitorConfig{
Context: ctx,
Conn: tdpConn,
Clock: s.cfg.Clock,
ClientIdleTimeout: authCtx.Checker.AdjustClientIdleTimeout(netConfig.GetClientIdleTimeout()),
Entry: log,
Emitter: s.cfg.Emitter,
LockWatcher: s.cfg.LockWatcher,
LockingMode: authCtx.Checker.LockingMode(authPref.GetLockingMode()),
LockTargets: append(services.LockTargetsFromTLSIdentity(identity), types.LockTarget{WindowsDesktop: desktop.GetName()}),
Tracker: rdpc,
TeleportUser: identity.Username,
ServerID: s.cfg.Heartbeat.HostUUID,
}
shouldDisconnectExpiredCert := authCtx.Checker.AdjustDisconnectExpiredCert(authPref.GetDisconnectExpiredCert())
if shouldDisconnectExpiredCert && !identity.Expires.IsZero() {
monitorCfg.DisconnectExpiredCert = identity.Expires
}
if err := srv.StartMonitor(monitorCfg); err != nil {
// if we can't establish a connection monitor then we can't enforce RBAC.
// consider this a connection failure and return an error
// (in the happy path, rdpc remains open until Wait() completes)
rdpc.Close()
s.onSessionStart(ctx, &identity, sessionStartTime, windowsUser, string(sessionID), desktop, err)
return trace.Wrap(err)
}
s.onSessionStart(ctx, &identity, sessionStartTime, windowsUser, string(sessionID), desktop, nil)
err = rdpc.Wait()
s.onSessionEnd(ctx, &identity, sessionStartTime, recordSession, windowsUser, string(sessionID), desktop)
return trace.Wrap(err)
}
func (s *WindowsService) makeTDPSendHandler(ctx context.Context, emitter events.Emitter, delay func() int64,
id *tlsca.Identity, sessionID, desktopAddr string) func(m tdp.Message, b []byte) {
return func(m tdp.Message, b []byte) {
switch b[0] {
case byte(tdp.TypePNGFrame), byte(tdp.TypeError):
e := &events.DesktopRecording{
Metadata: events.Metadata{
Type: libevents.DesktopRecordingEvent,
Time: s.cfg.Clock.Now().UTC().Round(time.Millisecond),
},
Message: b,
DelayMilliseconds: delay(),
}
if e.Size() > libevents.MaxProtoMessageSizeBytes {
// Technically a PNG frame is unbounded and could be too big for a single protobuf.
// In practice though, Windows limits RDP bitmaps to 64x64 pixels, and we compress
// the PNGs before they get here, so most PNG frames are under 500 bytes. The largest
// ones are around 2000 bytes. Anything approaching the limit of a single protobuf
// is likely some sort of DoS attempt and not legitimate RDP traffic, so we don't log it.
s.cfg.Log.Warnf("refusing to record %d byte PNG frame, image too large", len(b))
} else if err := emitter.EmitAuditEvent(ctx, e); err != nil {
s.cfg.Log.WithError(err).Warning("could not emit desktop recording event")
}
case byte(tdp.TypeClipboardData):
if clip, ok := m.(tdp.ClipboardData); ok {
// the TDP send handler emits a clipboard receive event, because we
// received clipboard data from the remote desktop and are sending
// it on the TDP connection
s.onClipboardReceive(ctx, id, sessionID, desktopAddr, int32(len(clip)))
}
}
}
}
func (s *WindowsService) makeTDPReceiveHandler(ctx context.Context, emitter events.Emitter, delay func() int64,
id *tlsca.Identity, sessionID, desktopAddr string) func(m tdp.Message) {
return func(m tdp.Message) {
switch msg := m.(type) {
case tdp.ClientScreenSpec, tdp.MouseButton, tdp.MouseMove:
b, err := m.Encode()
if err != nil {
s.cfg.Log.WithError(err).Warning("could not emit desktop recording event")
}
e := &events.DesktopRecording{
Metadata: events.Metadata{
Type: libevents.DesktopRecordingEvent,
Time: s.cfg.Clock.Now().UTC().Round(time.Millisecond),
},
Message: b,
DelayMilliseconds: delay(),
}
if e.Size() > libevents.MaxProtoMessageSizeBytes {
// screen spec, mouse button, and mouse move are fixed size messages,
// so they cannot exceed the maximum size
s.cfg.Log.Warnf("refusing to record %d byte %T message", len(b), m)
} else if err := emitter.EmitAuditEvent(ctx, e); err != nil {
s.cfg.Log.WithError(err).Warning("could not emit desktop recording event")
}
case tdp.ClipboardData:
// the TDP receive handler emits a clipboard send event, because we
// received clipboard data from the user (over TDP) and are sending
// it to the remote desktop
s.onClipboardSend(ctx, id, sessionID, desktopAddr, int32(len(msg)))
}
}
}
func (s *WindowsService) getServiceHeartbeatInfo() (types.Resource, error) {
srv, err := types.NewWindowsDesktopServiceV3(
s.cfg.Heartbeat.HostUUID,
types.WindowsDesktopServiceSpecV3{
Addr: s.cfg.Heartbeat.PublicAddr,
TeleportVersion: teleport.Version,
})
if err != nil {
return nil, trace.Wrap(err)
}
srv.SetExpiry(s.cfg.Clock.Now().UTC().Add(apidefaults.ServerAnnounceTTL))
return srv, nil
}
// staticHostHeartbeatInfo generates the Windows Desktop resource
// for heartbeating statically defined hosts
func (s *WindowsService) staticHostHeartbeatInfo(netAddr utils.NetAddr,
getHostLabels func(string) map[string]string) func() (types.Resource, error) {
return func() (types.Resource, error) {
addr := netAddr.String()
name, err := s.nameForStaticHost(addr)
if err != nil {
return nil, trace.Wrap(err)
}
// for static hosts, we match against the host's addr,
// as the name is a randomly generated UUID
labels := getHostLabels(addr)
labels[types.OriginLabel] = types.OriginConfigFile
desktop, err := types.NewWindowsDesktopV3(
name,
labels,
types.WindowsDesktopSpecV3{
Addr: addr,
Domain: s.cfg.Domain,
HostID: s.cfg.Heartbeat.HostUUID,
})
if err != nil {
return nil, trace.Wrap(err)
}
desktop.SetExpiry(s.cfg.Clock.Now().UTC().Add(apidefaults.ServerAnnounceTTL))
return desktop, nil
}
}
// nameForStaticHost attempts to find the name of an existing Windows desktop
// with the same address. If no matching address is found, a new name is
// generated.
//
// The list of WindowsDesktop objects should be read from the local cache. It
// should be reasonably fast to do this scan on every heartbeat. However, with
// a very large number of desktops in the cluster, this may use up a lot of CPU
// time.
func (s *WindowsService) nameForStaticHost(addr string) (string, error) {
desktops, err := s.cfg.AccessPoint.GetWindowsDesktops(s.closeCtx,
types.WindowsDesktopFilter{})
if err != nil {
return "", trace.Wrap(err)
}
for _, d := range desktops {
if d.GetAddr() == addr {
return d.GetName(), nil
}
}