forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiserver.go
2703 lines (2342 loc) · 87.3 KB
/
apiserver.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 web implements web proxy handler that provides
// web interface to view and connect to teleport nodes
package web
import (
"compress/gzip"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"html/template"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/api/client/proto"
"github.com/gravitational/teleport/api/client/webclient"
"github.com/gravitational/teleport/api/constants"
apidefaults "github.com/gravitational/teleport/api/defaults"
"github.com/gravitational/teleport/api/types"
apievents "github.com/gravitational/teleport/api/types/events"
apisshutils "github.com/gravitational/teleport/api/utils/sshutils"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/auth/u2f"
wanlib "github.com/gravitational/teleport/lib/auth/webauthn"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/httplib"
"github.com/gravitational/teleport/lib/httplib/csrf"
"github.com/gravitational/teleport/lib/jwt"
"github.com/gravitational/teleport/lib/plugin"
"github.com/gravitational/teleport/lib/reversetunnel"
"github.com/gravitational/teleport/lib/secret"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/web/app"
"github.com/gravitational/teleport/lib/web/ui"
"github.com/gravitational/roundtrip"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/julienschmidt/httprouter"
lemma_secret "github.com/mailgun/lemma/secret"
"github.com/sirupsen/logrus"
"golang.org/x/crypto/ssh"
)
const (
// ssoLoginConsoleErr is a generic error message to hide revealing sso login failure msgs.
ssoLoginConsoleErr = "Failed to login. Please check Teleport's log for more details."
metaRedirectHTML = `
<!DOCTYPE html>
<html lang="en">
<head>
<title>Teleport Redirection Service</title>
<meta http-equiv="cache-control" content="no-cache"/>
<meta http-equiv="refresh" content="0;URL='{{.}}'" />
</head>
<body></body>
</html>
`
)
var metaRedirectTemplate = template.Must(template.New("meta-redirect").Parse(metaRedirectHTML))
// Handler is HTTP web proxy handler
type Handler struct {
log logrus.FieldLogger
sync.Mutex
httprouter.Router
cfg Config
auth *sessionCache
sessionStreamPollPeriod time.Duration
clock clockwork.Clock
// sshPort specifies the SSH proxy port extracted
// from configuration
sshPort string
// ClusterFeatures contain flags for supported and unsupported features.
ClusterFeatures proto.Features
}
// HandlerOption is a functional argument - an option that can be passed
// to NewHandler function
type HandlerOption func(h *Handler) error
// SetSessionStreamPollPeriod sets polling period for session streams
func SetSessionStreamPollPeriod(period time.Duration) HandlerOption {
return func(h *Handler) error {
if period < 0 {
return trace.BadParameter("period should be non zero")
}
h.sessionStreamPollPeriod = period
return nil
}
}
// SetClock sets the clock on a handler
func SetClock(clock clockwork.Clock) HandlerOption {
return func(h *Handler) error {
h.clock = clock
return nil
}
}
type proxySettingsGetter interface {
GetProxySettings(ctx context.Context) (*webclient.ProxySettings, error)
}
// Config represents web handler configuration parameters
type Config struct {
// PluginRegistry handles plugin registration
PluginRegistry plugin.Registry
// Proxy is a reverse tunnel proxy that handles connections
// to local cluster or remote clusters using unified interface
Proxy reversetunnel.Tunnel
// AuthServers is a list of auth servers this proxy talks to
AuthServers utils.NetAddr
// DomainName is a domain name served by web handler
DomainName string
// ProxyClient is a client that authenticated as proxy
ProxyClient auth.ClientI
// ProxySSHAddr points to the SSH address of the proxy
ProxySSHAddr utils.NetAddr
// ProxyWebAddr points to the web (HTTPS) address of the proxy
ProxyWebAddr utils.NetAddr
// ProxyPublicAddr contains web proxy public addresses.
ProxyPublicAddrs []utils.NetAddr
// CipherSuites is the list of cipher suites Teleport suppports.
CipherSuites []uint16
// FIPS mode means Teleport started in a FedRAMP/FIPS 140-2 compliant
// configuration.
FIPS bool
// AccessPoint holds a cache to the Auth Server.
AccessPoint auth.ProxyAccessPoint
// Emitter is event emitter
Emitter events.StreamEmitter
// HostUUID is the UUID of this process.
HostUUID string
// Context is used to signal process exit.
Context context.Context
// StaticFS optionally specifies the HTTP file system to use.
// Enables web UI if set.
StaticFS http.FileSystem
// cachedSessionLingeringThreshold specifies the time the session will linger
// in the cache before getting purged after it has expired.
// Defaults to cachedSessionLingeringThreshold if unspecified.
cachedSessionLingeringThreshold *time.Duration
// ClusterFeatures contains flags for supported/unsupported features.
ClusterFeatures proto.Features
// ProxySettings allows fetching the current proxy settings.
ProxySettings proxySettingsGetter
}
type WebAPIHandler struct {
handler *Handler
// appHandler is a http.Handler to forward requests to applications.
appHandler *app.Handler
}
// Check if this request should be forwarded to an application handler to
// be handled by the UI and handle the request appropriately.
func (h *WebAPIHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// If the request is either to the fragment authentication endpoint or if the
// request is already authenticated (has a session cookie), forward to
// application handlers. If the request is unauthenticated and requesting a
// FQDN that is not of the proxy, redirect to application launcher.
if app.HasFragment(r) || app.HasSession(r) || app.HasClientCert(r) {
h.appHandler.ServeHTTP(w, r)
return
}
if redir, ok := app.HasName(r, h.handler.cfg.ProxyPublicAddrs); ok {
http.Redirect(w, r, redir, http.StatusFound)
return
}
// Serve the Web UI.
h.handler.ServeHTTP(w, r)
}
func (h *WebAPIHandler) Close() error {
return h.handler.Close()
}
// NewHandler returns a new instance of web proxy handler
func NewHandler(cfg Config, opts ...HandlerOption) (*WebAPIHandler, error) {
const apiPrefix = "/" + teleport.WebAPIVersion
h := &Handler{
cfg: cfg,
log: newPackageLogger(),
clock: clockwork.NewRealClock(),
ClusterFeatures: cfg.ClusterFeatures,
}
for _, o := range opts {
if err := o(h); err != nil {
return nil, trace.Wrap(err)
}
}
sessionLingeringThreshold := cachedSessionLingeringThreshold
if cfg.cachedSessionLingeringThreshold != nil {
sessionLingeringThreshold = *cfg.cachedSessionLingeringThreshold
}
auth, err := newSessionCache(sessionCacheOptions{
proxyClient: cfg.ProxyClient,
accessPoint: cfg.AccessPoint,
servers: []utils.NetAddr{cfg.AuthServers},
cipherSuites: cfg.CipherSuites,
clock: h.clock,
sessionLingeringThreshold: sessionLingeringThreshold,
})
if err != nil {
return nil, trace.Wrap(err)
}
h.auth = auth
_, sshPort, err := net.SplitHostPort(cfg.ProxySSHAddr.String())
if err != nil {
h.log.WithError(err).Warnf("Invalid SSH proxy address %q, will use default port %v.",
cfg.ProxySSHAddr.String(), defaults.SSHProxyListenPort)
sshPort = strconv.Itoa(defaults.SSHProxyListenPort)
}
h.sshPort = sshPort
// ping endpoint is used to check if the server is up. the /webapi/ping
// endpoint returns the default authentication method and configuration that
// the server supports. the /webapi/ping/:connector endpoint can be used to
// query the authentication configuration for a specific connector.
h.GET("/webapi/ping", httplib.MakeHandler(h.ping))
h.GET("/webapi/ping/:connector", httplib.MakeHandler(h.pingWithConnector))
// find is like ping, but is faster because it is optimized for servers
// and does not fetch the data that servers don't need, e.g.
// OIDC connectors and auth preferences
h.GET("/webapi/find", httplib.MakeHandler(h.find))
// Unauthenticated access to JWT public keys.
h.GET("/.well-known/jwks.json", httplib.MakeHandler(h.jwks))
// Unauthenticated access to the message of the day
h.GET("/webapi/motd", httplib.MakeHandler(h.motd))
// DELETE IN: 5.1.0
//
// Migrated this endpoint to /webapi/sessions/web below.
h.POST("/webapi/sessions", httplib.WithCSRFProtection(h.createWebSession))
// Web sessions
h.POST("/webapi/sessions/web", httplib.WithCSRFProtection(h.createWebSession))
h.POST("/webapi/sessions/app", h.WithAuth(h.createAppSession))
h.DELETE("/webapi/sessions", h.WithAuth(h.deleteSession))
h.POST("/webapi/sessions/renew", h.WithAuth(h.renewSession))
h.POST("/webapi/users", h.WithAuth(h.createUserHandle))
h.PUT("/webapi/users", h.WithAuth(h.updateUserHandle))
h.GET("/webapi/users", h.WithAuth(h.getUsersHandle))
h.DELETE("/webapi/users/:username", h.WithAuth(h.deleteUserHandle))
h.GET("/webapi/users/password/token/:token", httplib.MakeHandler(h.getResetPasswordTokenHandle))
h.PUT("/webapi/users/password/token", httplib.WithCSRFProtection(h.changeUserAuthentication))
h.PUT("/webapi/users/password", h.WithAuth(h.changePassword))
h.POST("/webapi/users/password/token", h.WithAuth(h.createResetPasswordToken))
h.POST("/webapi/users/privilege/token", h.WithAuth(h.createPrivilegeTokenHandle))
// Issues SSH temp certificates based on 2FA access creds
h.POST("/webapi/ssh/certs", httplib.MakeHandler(h.createSSHCert))
// list available sites
h.GET("/webapi/sites", h.WithAuth(h.getClusters))
// Site specific API
// get namespaces
h.GET("/webapi/sites/:site/namespaces", h.WithClusterAuth(h.getSiteNamespaces))
// get nodes
h.GET("/webapi/sites/:site/nodes", h.WithClusterAuth(h.siteNodesGet))
// Get applications.
h.GET("/webapi/sites/:site/apps", h.WithClusterAuth(h.clusterAppsGet))
// active sessions handlers
h.GET("/webapi/sites/:site/connect", h.WithClusterAuth(h.siteNodeConnect)) // connect to an active session (via websocket)
h.GET("/webapi/sites/:site/sessions", h.WithClusterAuth(h.siteSessionsGet)) // get active list of sessions
h.POST("/webapi/sites/:site/sessions", h.WithClusterAuth(h.siteSessionGenerate)) // create active session metadata
h.GET("/webapi/sites/:site/sessions/:sid", h.WithClusterAuth(h.siteSessionGet)) // get active session metadata
// Audit events handlers.
h.GET("/webapi/sites/:site/events/search", h.WithClusterAuth(h.clusterSearchEvents)) // search site events
h.GET("/webapi/sites/:site/events/search/sessions", h.WithClusterAuth(h.clusterSearchSessionEvents)) // search site session events
h.GET("/webapi/sites/:site/sessions/:sid/events", h.WithClusterAuth(h.siteSessionEventsGet)) // get recorded session's timing information (from events)
h.GET("/webapi/sites/:site/sessions/:sid/stream", h.siteSessionStreamGet) // get recorded session's bytes (from events)
// scp file transfer
h.GET("/webapi/sites/:site/nodes/:server/:login/scp", h.WithClusterAuth(h.transferFile))
h.POST("/webapi/sites/:site/nodes/:server/:login/scp", h.WithClusterAuth(h.transferFile))
// web context
h.GET("/webapi/sites/:site/context", h.WithClusterAuth(h.getUserContext))
// Database access handlers.
h.GET("/webapi/sites/:site/databases", h.WithClusterAuth(h.clusterDatabasesGet))
// Kube access handlers.
h.GET("/webapi/sites/:site/kubernetes", h.WithClusterAuth(h.clusterKubesGet))
// OIDC related callback handlers
h.GET("/webapi/oidc/login/web", h.WithRedirect(h.oidcLoginWeb))
h.GET("/webapi/oidc/callback", h.WithMetaRedirect(h.oidcCallback))
h.POST("/webapi/oidc/login/console", httplib.MakeHandler(h.oidcLoginConsole))
// SAML 2.0 handlers
h.POST("/webapi/saml/acs", h.WithRedirect(h.samlACS))
h.GET("/webapi/saml/sso", h.WithMetaRedirect(h.samlSSO))
h.POST("/webapi/saml/login/console", httplib.MakeHandler(h.samlSSOConsole))
// Github connector handlers
h.GET("/webapi/github/login/web", h.WithRedirect(h.githubLoginWeb))
h.GET("/webapi/github/callback", h.WithMetaRedirect(h.githubCallback))
h.POST("/webapi/github/login/console", httplib.MakeHandler(h.githubLoginConsole))
// U2F related APIs
// DELETE IN 9.x, superseded by /mfa/ endpoints (codingllama)
h.GET("/webapi/u2f/signuptokens/:token", httplib.MakeHandler(h.u2fRegisterRequest)) // replaced with /webapi/mfa/token/:token/registerchallenge
h.POST("/webapi/u2f/password/changerequest", h.WithAuth(h.createAuthenticateChallengeWithPassword)) // replaced with /webapi/mfa/authenticatechallenge/password
h.POST("/webapi/u2f/signrequest", httplib.MakeHandler(h.mfaLoginBegin)) // replaced with /webapi/mfa/login/begin
h.POST("/webapi/u2f/sessions", httplib.MakeHandler(h.mfaLoginFinishSession)) // replaced with /webapi/mfa/login/finishsession
h.POST("/webapi/u2f/certs", httplib.MakeHandler(h.mfaLoginFinish)) // replaced with /webapi/mfa/login/finish
// MFA public endpoints.
h.POST("/webapi/mfa/login/begin", httplib.MakeHandler(h.mfaLoginBegin))
h.POST("/webapi/mfa/login/finish", httplib.MakeHandler(h.mfaLoginFinish))
h.POST("/webapi/mfa/login/finishsession", httplib.MakeHandler(h.mfaLoginFinishSession))
h.DELETE("/webapi/mfa/token/:token/devices/:devicename", httplib.MakeHandler(h.deleteMFADeviceWithTokenHandle))
h.GET("/webapi/mfa/token/:token/devices", httplib.MakeHandler(h.getMFADevicesWithTokenHandle))
h.POST("/webapi/mfa/token/:token/authenticatechallenge", httplib.MakeHandler(h.createAuthenticateChallengeWithTokenHandle))
h.POST("/webapi/mfa/token/:token/registerchallenge", httplib.MakeHandler(h.createRegisterChallengeWithTokenHandle))
// MFA private endpoints.
h.GET("/webapi/mfa/devices", h.WithAuth(h.getMFADevicesHandle))
h.POST("/webapi/mfa/authenticatechallenge", h.WithAuth(h.createAuthenticateChallengeHandle))
h.POST("/webapi/mfa/devices", h.WithAuth(h.addMFADeviceHandle))
h.POST("/webapi/mfa/authenticatechallenge/password", h.WithAuth(h.createAuthenticateChallengeWithPassword))
// trusted clusters
h.POST("/webapi/trustedclusters/validate", httplib.MakeHandler(h.validateTrustedCluster))
// User Status (used by client to check if user session is valid)
h.GET("/webapi/user/status", h.WithAuth(h.getUserStatus))
// Issue host credentials.
h.POST("/webapi/host/credentials", httplib.MakeHandler(h.hostCredentials))
h.GET("/webapi/roles", h.WithAuth(h.getRolesHandle))
h.PUT("/webapi/roles", h.WithAuth(h.upsertRoleHandle))
h.POST("/webapi/roles", h.WithAuth(h.upsertRoleHandle))
h.DELETE("/webapi/roles/:name", h.WithAuth(h.deleteRole))
h.GET("/webapi/github", h.WithAuth(h.getGithubConnectorsHandle))
h.PUT("/webapi/github", h.WithAuth(h.upsertGithubConnectorHandle))
h.POST("/webapi/github", h.WithAuth(h.upsertGithubConnectorHandle))
h.DELETE("/webapi/github/:name", h.WithAuth(h.deleteGithubConnector))
h.GET("/webapi/trustedcluster", h.WithAuth(h.getTrustedClustersHandle))
h.PUT("/webapi/trustedcluster", h.WithAuth(h.upsertTrustedClusterHandle))
h.POST("/webapi/trustedcluster", h.WithAuth(h.upsertTrustedClusterHandle))
h.DELETE("/webapi/trustedcluster/:name", h.WithAuth(h.deleteTrustedCluster))
h.GET("/webapi/apps/:fqdnHint", h.WithAuth(h.getAppFQDN))
h.GET("/webapi/apps/:fqdnHint/:clusterName/:publicAddr", h.WithAuth(h.getAppFQDN))
// Desktop access endpoints.
h.GET("/webapi/sites/:site/desktops", h.WithClusterAuth(h.getDesktopsHandle))
h.GET("/webapi/sites/:site/desktops/:desktopName", h.WithClusterAuth(h.getDesktopHandle))
// GET //webapi/sites/:site/desktops/:desktopName/connect?access_token=<bearer_token>&username=<username>&width=<width>&height=<height>
h.GET("/webapi/sites/:site/desktops/:desktopName/connect", h.WithClusterAuth(h.desktopConnectHandle))
// if Web UI is enabled, check the assets dir:
var indexPage *template.Template
if cfg.StaticFS != nil {
index, err := cfg.StaticFS.Open("/index.html")
if err != nil {
h.log.WithError(err).Error("Failed to open index file.")
return nil, trace.Wrap(err)
}
defer index.Close()
indexContent, err := ioutil.ReadAll(index)
if err != nil {
return nil, trace.ConvertSystemError(err)
}
indexPage, err = template.New("index").Parse(string(indexContent))
if err != nil {
return nil, trace.BadParameter("failed parsing index.html template: %v", err)
}
h.Handle("GET", "/web/config.js", httplib.MakeHandler(h.getWebConfig))
}
routingHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// request is going to the API?
if strings.HasPrefix(r.URL.Path, apiPrefix) {
http.StripPrefix(apiPrefix, h).ServeHTTP(w, r)
return
}
// request is going to the web UI
if cfg.StaticFS == nil {
w.WriteHeader(http.StatusNotImplemented)
return
}
// redirect to "/web" when someone hits "/"
if r.URL.Path == "/" {
http.Redirect(w, r, "/web", http.StatusFound)
return
}
// serve Web UI:
if strings.HasPrefix(r.URL.Path, "/web/app") {
httplib.SetStaticFileHeaders(w.Header())
http.StripPrefix("/web", makeGzipHandler(http.FileServer(cfg.StaticFS))).ServeHTTP(w, r)
} else if strings.HasPrefix(r.URL.Path, "/web/") || r.URL.Path == "/web" {
csrfToken, err := csrf.AddCSRFProtection(w, r)
if err != nil {
h.log.WithError(err).Warn("Failed to generate CSRF token.")
}
session := struct {
Session string
XCSRF string
}{
XCSRF: csrfToken,
}
ctx, err := h.AuthenticateRequest(w, r, false)
if err == nil {
resp, err := newSessionResponse(ctx)
if err == nil {
out, err := json.Marshal(resp)
if err == nil {
session.Session = base64.StdEncoding.EncodeToString(out)
}
} else {
h.log.WithError(err).Debug("Could not authenticate.")
}
}
httplib.SetIndexHTMLHeaders(w.Header())
if err := indexPage.Execute(w, session); err != nil {
h.log.WithError(err).Error("Failed to execute index page template.")
}
} else {
http.NotFound(w, r)
}
})
h.NotFound = routingHandler
if cfg.PluginRegistry != nil {
if err := cfg.PluginRegistry.RegisterProxyWebHandlers(h); err != nil {
return nil, trace.Wrap(err)
}
}
resp, err := h.cfg.ProxySettings.GetProxySettings(cfg.Context)
if err != nil {
return nil, trace.Wrap(err)
}
// Create application specific handler. This handler handles sessions and
// forwarding for application access.
appHandler, err := app.NewHandler(cfg.Context, &app.HandlerConfig{
Clock: h.clock,
AuthClient: cfg.ProxyClient,
AccessPoint: cfg.AccessPoint,
ProxyClient: cfg.Proxy,
CipherSuites: cfg.CipherSuites,
WebPublicAddr: resp.SSH.PublicAddr,
})
if err != nil {
return nil, trace.Wrap(err)
}
return &WebAPIHandler{
handler: h,
appHandler: appHandler,
}, nil
}
// GetProxyClient returns authenticated auth server client
func (h *Handler) GetProxyClient() auth.ClientI {
return h.cfg.ProxyClient
}
// Close closes associated session cache operations
func (h *Handler) Close() error {
return h.auth.Close()
}
func (h *Handler) getUserStatus(w http.ResponseWriter, r *http.Request, _ httprouter.Params, c *SessionContext) (interface{}, error) {
return OK(), nil
}
// getUserContext returns user context
//
// GET /webapi/sites/:site/context
//
func (h *Handler) getUserContext(w http.ResponseWriter, r *http.Request, p httprouter.Params, c *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) {
cn, err := h.cfg.AccessPoint.GetClusterName()
if err != nil {
return nil, trace.Wrap(err)
}
if cn.GetClusterName() != site.GetName() {
return nil, trace.BadParameter("endpoint only implemented for root cluster")
}
roleset, err := c.GetUserRoles()
if err != nil {
return nil, trace.Wrap(err)
}
clt, err := c.GetClient()
if err != nil {
return nil, trace.Wrap(err)
}
user, err := clt.GetUser(c.GetUser(), false)
if err != nil {
return nil, trace.Wrap(err)
}
userContext, err := ui.NewUserContext(user, roleset, h.ClusterFeatures)
if err != nil {
return nil, trace.Wrap(err)
}
res, err := clt.GetAccessCapabilities(r.Context(), types.AccessCapabilitiesRequest{
RequestableRoles: true,
SuggestedReviewers: true,
})
if err != nil {
return nil, trace.Wrap(err)
}
userContext.AccessCapabilities = ui.AccessCapabilities{
RequestableRoles: res.RequestableRoles,
SuggestedReviewers: res.SuggestedReviewers,
}
userContext.Cluster, err = ui.GetClusterDetails(r.Context(), site)
if err != nil {
return nil, trace.Wrap(err)
}
return userContext, nil
}
func localSettings(cap types.AuthPreference) (webclient.AuthenticationSettings, error) {
as := webclient.AuthenticationSettings{
Type: constants.Local,
SecondFactor: cap.GetSecondFactor(),
PreferredLocalMFA: cap.GetPreferredLocalMFA(),
}
// U2F settings.
switch u2f, err := cap.GetU2F(); {
case err == nil:
as.U2F = &webclient.U2FSettings{AppID: u2f.AppID}
case !trace.IsNotFound(err):
log.WithError(err).Warnf("Error reading U2F settings")
}
// Webauthn settings.
switch webConfig, err := cap.GetWebauthn(); {
case err == nil:
as.Webauthn = &webclient.Webauthn{
RPID: webConfig.RPID,
}
case !trace.IsNotFound(err):
log.WithError(err).Warnf("Error reading WebAuthn settings")
}
return as, nil
}
func oidcSettings(connector types.OIDCConnector, cap types.AuthPreference) webclient.AuthenticationSettings {
return webclient.AuthenticationSettings{
Type: constants.OIDC,
OIDC: &webclient.OIDCSettings{
Name: connector.GetName(),
Display: connector.GetDisplay(),
},
// if you falling back to local accounts
SecondFactor: cap.GetSecondFactor(),
}
}
func samlSettings(connector types.SAMLConnector, cap types.AuthPreference) webclient.AuthenticationSettings {
return webclient.AuthenticationSettings{
Type: constants.SAML,
SAML: &webclient.SAMLSettings{
Name: connector.GetName(),
Display: connector.GetDisplay(),
},
// if you are falling back to local accounts
SecondFactor: cap.GetSecondFactor(),
}
}
func githubSettings(connector types.GithubConnector, cap types.AuthPreference) webclient.AuthenticationSettings {
return webclient.AuthenticationSettings{
Type: constants.Github,
Github: &webclient.GithubSettings{
Name: connector.GetName(),
Display: connector.GetDisplay(),
},
SecondFactor: cap.GetSecondFactor(),
}
}
func defaultAuthenticationSettings(ctx context.Context, authClient auth.ClientI) (webclient.AuthenticationSettings, error) {
cap, err := authClient.GetAuthPreference(ctx)
if err != nil {
return webclient.AuthenticationSettings{}, trace.Wrap(err)
}
var as webclient.AuthenticationSettings
switch cap.GetType() {
case constants.Local:
as, err = localSettings(cap)
if err != nil {
return webclient.AuthenticationSettings{}, trace.Wrap(err)
}
case constants.OIDC:
if cap.GetConnectorName() != "" {
oidcConnector, err := authClient.GetOIDCConnector(ctx, cap.GetConnectorName(), false)
if err != nil {
return webclient.AuthenticationSettings{}, trace.Wrap(err)
}
as = oidcSettings(oidcConnector, cap)
} else {
oidcConnectors, err := authClient.GetOIDCConnectors(ctx, false)
if err != nil {
return webclient.AuthenticationSettings{}, trace.Wrap(err)
}
if len(oidcConnectors) == 0 {
return webclient.AuthenticationSettings{}, trace.BadParameter("no oidc connectors found")
}
as = oidcSettings(oidcConnectors[0], cap)
}
case constants.SAML:
if cap.GetConnectorName() != "" {
samlConnector, err := authClient.GetSAMLConnector(ctx, cap.GetConnectorName(), false)
if err != nil {
return webclient.AuthenticationSettings{}, trace.Wrap(err)
}
as = samlSettings(samlConnector, cap)
} else {
samlConnectors, err := authClient.GetSAMLConnectors(ctx, false)
if err != nil {
return webclient.AuthenticationSettings{}, trace.Wrap(err)
}
if len(samlConnectors) == 0 {
return webclient.AuthenticationSettings{}, trace.BadParameter("no saml connectors found")
}
as = samlSettings(samlConnectors[0], cap)
}
case constants.Github:
if cap.GetConnectorName() != "" {
githubConnector, err := authClient.GetGithubConnector(ctx, cap.GetConnectorName(), false)
if err != nil {
return webclient.AuthenticationSettings{}, trace.Wrap(err)
}
as = githubSettings(githubConnector, cap)
} else {
githubConnectors, err := authClient.GetGithubConnectors(ctx, false)
if err != nil {
return webclient.AuthenticationSettings{}, trace.Wrap(err)
}
if len(githubConnectors) == 0 {
return webclient.AuthenticationSettings{}, trace.BadParameter("no github connectors found")
}
as = githubSettings(githubConnectors[0], cap)
}
default:
return webclient.AuthenticationSettings{}, trace.BadParameter("unknown type %v", cap.GetType())
}
as.HasMessageOfTheDay = cap.GetMessageOfTheDay() != ""
return as, nil
}
func (h *Handler) ping(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
var err error
defaultSettings, err := defaultAuthenticationSettings(r.Context(), h.cfg.ProxyClient)
if err != nil {
return nil, trace.Wrap(err)
}
proxyConfig, err := h.cfg.ProxySettings.GetProxySettings(r.Context())
if err != nil {
return nil, trace.Wrap(err)
}
return webclient.PingResponse{
Auth: defaultSettings,
Proxy: *proxyConfig,
ServerVersion: teleport.Version,
MinClientVersion: teleport.MinClientVersion,
}, nil
}
func (h *Handler) find(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
proxyConfig, err := h.cfg.ProxySettings.GetProxySettings(r.Context())
if err != nil {
return nil, trace.Wrap(err)
}
return webclient.PingResponse{
Proxy: *proxyConfig,
ServerVersion: teleport.Version,
MinClientVersion: teleport.MinClientVersion,
}, nil
}
func (h *Handler) pingWithConnector(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
authClient := h.cfg.ProxyClient
connectorName := p.ByName("connector")
cap, err := authClient.GetAuthPreference(r.Context())
if err != nil {
return nil, trace.Wrap(err)
}
proxyConfig, err := h.cfg.ProxySettings.GetProxySettings(r.Context())
if err != nil {
return nil, trace.Wrap(err)
}
response := &webclient.PingResponse{
Proxy: *proxyConfig,
ServerVersion: teleport.Version,
}
if connectorName == constants.Local {
as, err := localSettings(cap)
if err != nil {
return nil, trace.Wrap(err)
}
response.Auth = as
return response, nil
}
// first look for a oidc connector with that name
oidcConnector, err := authClient.GetOIDCConnector(r.Context(), connectorName, false)
if err == nil {
response.Auth = oidcSettings(oidcConnector, cap)
return response, nil
}
// if no oidc connector was found, look for a saml connector
samlConnector, err := authClient.GetSAMLConnector(r.Context(), connectorName, false)
if err == nil {
response.Auth = samlSettings(samlConnector, cap)
return response, nil
}
// look for github connector
githubConnector, err := authClient.GetGithubConnector(r.Context(), connectorName, false)
if err == nil {
response.Auth = githubSettings(githubConnector, cap)
return response, nil
}
return nil, trace.BadParameter("invalid connector name %v", connectorName)
}
// getWebConfig returns configuration for the web application.
func (h *Handler) getWebConfig(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
httplib.SetWebConfigHeaders(w.Header())
authProviders := []ui.WebConfigAuthProvider{}
// get all OIDC connectors
oidcConnectors, err := h.cfg.ProxyClient.GetOIDCConnectors(r.Context(), false)
if err != nil {
h.log.WithError(err).Error("Cannot retrieve OIDC connectors.")
}
for _, item := range oidcConnectors {
authProviders = append(authProviders, ui.WebConfigAuthProvider{
Type: ui.WebConfigAuthProviderOIDCType,
WebAPIURL: ui.WebConfigAuthProviderOIDCURL,
Name: item.GetName(),
DisplayName: item.GetDisplay(),
})
}
// get all SAML connectors
samlConnectors, err := h.cfg.ProxyClient.GetSAMLConnectors(r.Context(), false)
if err != nil {
h.log.WithError(err).Error("Cannot retrieve SAML connectors.")
}
for _, item := range samlConnectors {
authProviders = append(authProviders, ui.WebConfigAuthProvider{
Type: ui.WebConfigAuthProviderSAMLType,
WebAPIURL: ui.WebConfigAuthProviderSAMLURL,
Name: item.GetName(),
DisplayName: item.GetDisplay(),
})
}
// get all Github connectors
githubConnectors, err := h.cfg.ProxyClient.GetGithubConnectors(r.Context(), false)
if err != nil {
h.log.WithError(err).Error("Cannot retrieve Github connectors.")
}
for _, item := range githubConnectors {
authProviders = append(authProviders, ui.WebConfigAuthProvider{
Type: ui.WebConfigAuthProviderGitHubType,
WebAPIURL: ui.WebConfigAuthProviderGitHubURL,
Name: item.GetName(),
DisplayName: item.GetDisplay(),
})
}
// get auth type & second factor type
authType := constants.Local
secondFactor := constants.SecondFactorOff
localAuth := true
cap, err := h.cfg.ProxyClient.GetAuthPreference(r.Context())
if err != nil {
h.log.WithError(err).Error("Cannot retrieve AuthPreferences.")
} else {
authType = cap.GetType()
secondFactor = cap.GetSecondFactor()
localAuth = cap.GetAllowLocalAuth()
}
// disable joining sessions if proxy session recording is enabled
canJoinSessions := true
recCfg, err := h.cfg.ProxyClient.GetSessionRecordingConfig(r.Context())
if err != nil {
h.log.WithError(err).Error("Cannot retrieve SessionRecordingConfig.")
} else {
canJoinSessions = services.IsRecordAtProxy(recCfg.GetMode()) == false
}
authSettings := ui.WebConfigAuthSettings{
Providers: authProviders,
SecondFactor: secondFactor,
LocalAuthEnabled: localAuth,
AuthType: authType,
PreferredLocalMFA: cap.GetPreferredLocalMFA(),
}
webCfg := ui.WebConfig{
Auth: authSettings,
CanJoinSessions: canJoinSessions,
IsCloud: h.ClusterFeatures.GetCloud(),
}
resource, err := h.cfg.ProxyClient.GetClusterName()
if err != nil {
h.log.WithError(err).Warn("Failed to query cluster name.")
} else {
webCfg.ProxyClusterName = resource.GetClusterName()
}
out, err := json.Marshal(webCfg)
if err != nil {
return nil, trace.Wrap(err)
}
fmt.Fprintf(w, "var GRV_CONFIG = %v;", string(out))
return nil, nil
}
type JWKSResponse struct {
// Keys is a list of public keys in JWK format.
Keys []jwt.JWK `json:"keys"`
}
// jwks returns all public keys used to sign JWT tokens for this cluster.
func (h *Handler) jwks(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
clusterName, err := h.cfg.ProxyClient.GetDomainName()
if err != nil {
return nil, trace.Wrap(err)
}
// Fetch the JWT public keys only.
ca, err := h.cfg.ProxyClient.GetCertAuthority(types.CertAuthID{
Type: types.JWTSigner,
DomainName: clusterName,
}, false)
if err != nil {
return nil, trace.Wrap(err)
}
pairs := ca.GetTrustedJWTKeyPairs()
// Create response and allocate space for the keys.
var resp JWKSResponse
resp.Keys = make([]jwt.JWK, 0, len(pairs))
// Loop over and all add public keys in JWK format.
for _, pair := range pairs {
jwk, err := jwt.MarshalJWK(pair.PublicKey)
if err != nil {
return nil, trace.Wrap(err)
}
resp.Keys = append(resp.Keys, jwk)
}
return &resp, nil
}
func (h *Handler) motd(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
authPrefs, err := h.cfg.ProxyClient.GetAuthPreference(r.Context())
if err != nil {
return nil, trace.Wrap(err)
}
return webclient.MotD{Text: authPrefs.GetMessageOfTheDay()}, nil
}
func (h *Handler) oidcLoginWeb(w http.ResponseWriter, r *http.Request, p httprouter.Params) string {
logger := h.log.WithField("auth", "oidc")
logger.Debug("Web login start.")
req, err := parseSSORequestParams(r)
if err != nil {
logger.WithError(err).Error("Failed to extract SSO parameters from request.")
return client.LoginFailedRedirectURL
}
response, err := h.cfg.ProxyClient.CreateOIDCAuthRequest(
services.OIDCAuthRequest{
CSRFToken: req.csrfToken,
ConnectorID: req.connectorID,
CreateWebSession: true,
ClientRedirectURL: req.clientRedirectURL,
CheckUser: true,
})
if err != nil {
logger.WithError(err).Error("Error creating auth request.")
return client.LoginFailedRedirectURL
}
return response.RedirectURL
}
func (h *Handler) githubLoginWeb(w http.ResponseWriter, r *http.Request, p httprouter.Params) string {
logger := h.log.WithField("auth", "github")
logger.Debug("Web login start.")
req, err := parseSSORequestParams(r)
if err != nil {
logger.WithError(err).Error("Failed to extract SSO parameters from request.")
return client.LoginFailedRedirectURL
}