-
Notifications
You must be signed in to change notification settings - Fork 0
/
apiserver.go
1737 lines (1558 loc) · 52.5 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 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"
"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/lib/auth"
"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/reversetunnel"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/web/ui"
log "github.com/Sirupsen/logrus"
"github.com/gravitational/roundtrip"
"github.com/gravitational/trace"
"github.com/jonboulle/clockwork"
"github.com/julienschmidt/httprouter"
"github.com/mailgun/lemma/secret"
"github.com/mailgun/ttlmap"
"github.com/tstranex/u2f"
)
// Handler is HTTP web proxy handler
type Handler struct {
sync.Mutex
httprouter.Router
cfg Config
auth *sessionCache
sites *ttlmap.TtlMap
sessionStreamPollPeriod time.Duration
clock clockwork.Clock
}
// 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
}
}
// Config represents web handler configuration parameters
type Config struct {
// Proxy is a reverse tunnel proxy that handles connections
// to various sites
Proxy reversetunnel.Server
// 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
// DisableUI allows to turn off serving web based UI
DisableUI bool
// 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
}
type RewritingHandler struct {
http.Handler
handler *Handler
}
func (r *RewritingHandler) GetHandler() *Handler {
return r.handler
}
func (r *RewritingHandler) Close() error {
return r.handler.Close()
}
// NewHandler returns a new instance of web proxy handler
func NewHandler(cfg Config, opts ...HandlerOption) (*RewritingHandler, error) {
const apiPrefix = "/" + teleport.WebAPIVersion
lauth, err := newSessionCache([]utils.NetAddr{cfg.AuthServers})
if err != nil {
return nil, trace.Wrap(err)
}
h := &Handler{
cfg: cfg,
auth: lauth,
}
for _, o := range opts {
if err := o(h); err != nil {
return nil, trace.Wrap(err)
}
}
if h.sessionStreamPollPeriod == 0 {
h.sessionStreamPollPeriod = sessionStreamPollPeriod
}
if h.clock == nil {
h.clock = clockwork.NewRealClock()
}
// a response indicates if the server is up and the response data
// indicates the type of authentication methods that are supported
// TODO(russjones): Where is /webapi, that was the old /ping?
h.GET("/webapi/ping", httplib.MakeHandler(h.getAuthenticationSettings))
// Web sessions
h.POST("/webapi/sessions", httplib.MakeHandler(h.createSession))
h.DELETE("/webapi/sessions", h.WithAuth(h.deleteSession))
h.POST("/webapi/sessions/renew", h.WithAuth(h.renewSession))
// Users
h.GET("/webapi/users/invites/:token", httplib.MakeHandler(h.renderUserInvite))
h.POST("/webapi/users", httplib.MakeHandler(h.createNewUser))
// 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.getSites))
// Site specific API
// get namespaces
h.GET("/webapi/sites/:site/namespaces", h.WithClusterAuth(h.getSiteNamespaces))
// get nodes
h.GET("/webapi/sites/:site/namespaces/:namespace/nodes", h.WithClusterAuth(h.getSiteNodes))
// connect to node via websocket (that's why it's a GET method)
h.GET("/webapi/sites/:site/namespaces/:namespace/connect", h.WithClusterAuth(h.siteNodeConnect))
// get session event stream
h.GET("/webapi/sites/:site/namespaces/:namespace/sessions/:sid/events/stream", h.WithClusterAuth(h.siteSessionStream))
// generate a new session
h.POST("/webapi/sites/:site/namespaces/:namespace/sessions", h.WithClusterAuth(h.siteSessionGenerate))
// update session parameters
h.PUT("/webapi/sites/:site/namespaces/:namespace/sessions/:sid", h.WithClusterAuth(h.siteSessionUpdate))
// get the session list
h.GET("/webapi/sites/:site/namespaces/:namespace/sessions", h.WithClusterAuth(h.siteSessionsGet))
// get a session
h.GET("/webapi/sites/:site/namespaces/:namespace/sessions/:sid", h.WithClusterAuth(h.siteSessionGet))
// get session's events
h.GET("/webapi/sites/:site/namespaces/:namespace/sessions/:sid/events", h.WithClusterAuth(h.siteSessionEventsGet))
// get session's bytestream
h.GET("/webapi/sites/:site/namespaces/:namespace/sessions/:sid/stream", h.siteSessionStreamGet)
// search site events
h.GET("/webapi/sites/:site/events", h.WithClusterAuth(h.siteEventsGet))
// OIDC related callback handlers
h.GET("/webapi/oidc/login/web", httplib.MakeHandler(h.oidcLoginWeb))
h.POST("/webapi/oidc/login/console", httplib.MakeHandler(h.oidcLoginConsole))
h.GET("/webapi/oidc/callback", httplib.MakeHandler(h.oidcCallback))
// U2F related APIs
h.GET("/webapi/u2f/signuptokens/:token", httplib.MakeHandler(h.u2fRegisterRequest))
h.POST("/webapi/u2f/users", httplib.MakeHandler(h.createNewU2FUser))
h.POST("/webapi/u2f/signrequest", httplib.MakeHandler(h.u2fSignRequest))
h.POST("/webapi/u2f/sessions", httplib.MakeHandler(h.createSessionWithU2FSignResponse))
h.POST("/webapi/u2f/certs", httplib.MakeHandler(h.createSSHCertWithU2FSignResponse))
// 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))
h.GET("/webapi/user/acl", h.WithAuth(h.getUserACL))
// if Web UI is enabled, check the assets dir:
var (
writeSettings http.HandlerFunc
indexPage *template.Template
staticFS http.FileSystem
)
if !cfg.DisableUI {
staticFS, err = NewStaticFileSystem(isDebugMode())
if err != nil {
return nil, trace.Wrap(err)
}
index, err := staticFS.Open("/index.html")
if err != nil {
log.Error(err)
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)
}
writeSettings = httplib.MakeStdHandler(h.getConfigurationSettings)
}
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.DisableUI {
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") {
http.StripPrefix("/web", http.FileServer(staticFS)).ServeHTTP(w, r)
} else if strings.HasPrefix(r.URL.Path, "/web/config.js") {
writeSettings.ServeHTTP(w, r)
} else if strings.HasPrefix(r.URL.Path, "/web") {
ctx, err := h.AuthenticateRequest(w, r, false)
session := struct {
Session string
}{Session: base64.StdEncoding.EncodeToString([]byte("{}"))}
if err == nil {
re, err := NewSessionResponse(ctx)
if err == nil {
out, err := json.Marshal(re)
if err == nil {
session.Session = base64.StdEncoding.EncodeToString(out)
}
}
}
indexPage.Execute(w, session)
} else {
http.NotFound(w, r)
}
})
h.NotFound = routingHandler
plugin := GetPlugin()
if plugin != nil {
plugin.AddHandlers(h)
}
return &RewritingHandler{
Handler: httplib.RewritePaths(h,
httplib.Rewrite("/webapi/sites/([^/]+)/sessions/(.*)", "/webapi/sites/$1/namespaces/default/sessions/$2"),
httplib.Rewrite("/webapi/sites/([^/]+)/sessions", "/webapi/sites/$1/namespaces/default/sessions"),
httplib.Rewrite("/webapi/sites/([^/]+)/nodes", "/webapi/sites/$1/namespaces/default/nodes"),
httplib.Rewrite("/webapi/sites/([^/]+)/connect", "/webapi/sites/$1/namespaces/default/connect"),
),
handler: h,
}, nil
}
// Close closes associated session cache operations
func (m *Handler) Close() error {
return m.auth.Close()
}
func (m *Handler) getUserStatus(w http.ResponseWriter, r *http.Request, _ httprouter.Params, c *SessionContext) (interface{}, error) {
return ok(), nil
}
// getUserACL returns currently signed-in user permissions
//
// GET /webapi/user/acl
//
// { "admin": { "enabled": false }, "kubernetes": { "groups": null }, "license": { "enabled": false }, "applications": { "fullAccess": false }, "cluster": { "enabled": false }, "ssh": { "logins": null } }
//
func (m *Handler) getUserACL(w http.ResponseWriter, r *http.Request, _ httprouter.Params, c *SessionContext) (interface{}, error) {
clt, err := c.GetClient()
if err != nil {
return nil, trace.Wrap(err)
}
allTeleRoles, err := clt.GetRoles()
if err != nil {
return nil, trace.Wrap(err)
}
user, err := clt.GetUser(c.GetUser())
if err != nil {
return nil, trace.Wrap(err)
}
userTeleRoles := user.GetRoles()
roleNamesMap := map[string]bool{}
for _, name := range userTeleRoles {
roleNamesMap[name] = true
}
accessSet := []*ui.RoleAccess{}
for _, item := range allTeleRoles {
if roleNamesMap[item.GetName()] {
uiRole := ui.NewRole(item)
accessSet = append(accessSet, &uiRole.Access)
}
}
uiaccess := ui.MergeAccessSet(accessSet)
return uiaccess, nil
}
func buildUniversalSecondFactorSettings(authClient auth.ClientI) *client.U2FSettings {
universalSecondFactor, err := authClient.GetUniversalSecondFactor()
if err != nil {
// if we have nothing set on the backend, return we have nothing
if trace.IsNotFound(err) {
return nil
}
log.Debugf("Unable to get U2F Settings: %v", err)
return nil
}
return &client.U2FSettings{AppID: universalSecondFactor.GetAppID()}
}
func buildOIDCConnectorSettings(authClient auth.ClientI) *client.OIDCSettings {
oidcConnectors, err := authClient.GetOIDCConnectors(false)
if err != nil {
// if we have nothing set on the backend, return we have nothing
if trace.IsNotFound(err) {
return nil
}
log.Debugf("Unable to get OIDC Connectors: %v", err)
return nil
}
if len(oidcConnectors) < 1 {
log.Debugf("No OIDC Connectors found")
return nil
}
// always use the first one as only allow a single oidc connector now
return &client.OIDCSettings{
Name: oidcConnectors[0].GetName(),
Display: oidcConnectors[0].GetDisplay(),
}
}
func buildAuthenticationSettings(authClient auth.ClientI) (*client.AuthenticationSettings, error) {
as := &client.AuthenticationSettings{}
cap, err := authClient.GetClusterAuthPreference()
if err != nil {
return nil, trace.Wrap(err)
}
as.Type = cap.GetType()
as.SecondFactor = cap.GetSecondFactor()
// if we have u2f or oidc settings, build those as well
if cap.GetSecondFactor() == teleport.U2F {
as.U2F = buildUniversalSecondFactorSettings(authClient)
}
if cap.GetType() == teleport.OIDC {
as.OIDC = buildOIDCConnectorSettings(authClient)
}
return as, nil
}
func (m *Handler) getAuthenticationSettings(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
as, err := buildAuthenticationSettings(m.cfg.ProxyClient)
if err != nil {
return nil, trace.Wrap(err)
}
return &client.PingResponse{
Auth: *as,
ServerVersion: teleport.Version,
}, nil
}
type webConfig struct {
// Auth contains the forms of authentication the auth server supports.
Auth *client.AuthenticationSettings `json:"auth,omitempty"`
// ServerVersion is the version of Teleport that is running.
ServerVersion string `json:"serverVersion"`
}
// getConfigurationSettings returns configuration for the web application.
func (m *Handler) getConfigurationSettings(w http.ResponseWriter, r *http.Request) (interface{}, error) {
var as, err = buildAuthenticationSettings(m.cfg.ProxyClient)
if err != nil {
log.Infof("Cannot retrieve cluster auth preferences: %v", err)
}
webCfg := webConfig{
Auth: as,
ServerVersion: teleport.Version,
}
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
}
func (m *Handler) oidcLoginWeb(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
log.Infof("oidcLoginWeb start")
query := r.URL.Query()
clientRedirectURL := query.Get("redirect_url")
if clientRedirectURL == "" {
return nil, trace.BadParameter("missing redirect_url query parameter")
}
connectorID := query.Get("connector_id")
if connectorID == "" {
return nil, trace.BadParameter("missing connector_id query parameter")
}
response, err := m.cfg.ProxyClient.CreateOIDCAuthRequest(
services.OIDCAuthRequest{
ConnectorID: connectorID,
CreateWebSession: true,
ClientRedirectURL: clientRedirectURL,
CheckUser: true,
})
if err != nil {
return nil, trace.Wrap(err)
}
http.Redirect(w, r, response.RedirectURL, http.StatusFound)
return nil, nil
}
func (m *Handler) oidcLoginConsole(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
log.Infof("oidcLoginConsole start")
var req *client.OIDCLoginConsoleReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
if req.RedirectURL == "" {
return nil, trace.BadParameter("missing RedirectURL")
}
if len(req.PublicKey) == 0 {
return nil, trace.BadParameter("missing PublicKey")
}
if req.ConnectorID == "" {
return nil, trace.BadParameter("missing ConnectorID")
}
response, err := m.cfg.ProxyClient.CreateOIDCAuthRequest(
services.OIDCAuthRequest{
ConnectorID: req.ConnectorID,
ClientRedirectURL: req.RedirectURL,
PublicKey: req.PublicKey,
CertTTL: req.CertTTL,
CheckUser: true,
})
if err != nil {
return nil, trace.Wrap(err)
}
return &client.OIDCLoginConsoleResponse{RedirectURL: response.RedirectURL}, nil
}
func (m *Handler) oidcCallback(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
log.Infof("oidcCallback start")
response, err := m.cfg.ProxyClient.ValidateOIDCAuthCallback(r.URL.Query())
if err != nil {
log.Infof("[OIDC] Error while processing callback: %v", err)
// redirect to an error page
pathToError := url.URL{
Path: "/web/msg/error/login_failed",
RawQuery: url.Values{"details": []string{"Unable to process callback from OIDC provider."}}.Encode(),
}
http.Redirect(w, r, pathToError.String(), http.StatusFound)
return nil, nil
}
// if we created web session, set session cookie and redirect to original url
if response.Req.CreateWebSession {
log.Infof("oidcCallback redirecting to web browser")
if err := SetSession(w, response.Username, response.Session.GetName()); err != nil {
return nil, trace.Wrap(err)
}
http.Redirect(w, r, response.Req.ClientRedirectURL, http.StatusFound)
return nil, nil
}
log.Infof("oidcCallback redirecting to console login")
if len(response.Req.PublicKey) == 0 {
return nil, trace.BadParameter("not a web or console oidc login request")
}
redirectURL, err := ConstructSSHResponse(response)
if err != nil {
return nil, trace.Wrap(err)
}
http.Redirect(w, r, redirectURL.String(), http.StatusFound)
return nil, nil
}
// ConstructSSHResponse creates a special SSH response for SSH login method
// that encodes everything using the client's secret key
func ConstructSSHResponse(response *auth.OIDCAuthResponse) (*url.URL, error) {
u, err := url.Parse(response.Req.ClientRedirectURL)
if err != nil {
return nil, trace.Wrap(err)
}
signers, err := services.CertAuthoritiesToV1(response.HostSigners)
if err != nil {
return nil, trace.Wrap(err)
}
consoleResponse := client.SSHLoginResponse{
Username: response.Username,
Cert: response.Cert,
HostSigners: signers,
}
out, err := json.Marshal(consoleResponse)
if err != nil {
return nil, trace.Wrap(err)
}
values := u.Query()
secretKey := values.Get("secret")
if secretKey == "" {
return nil, trace.BadParameter("missing secret")
}
values.Set("secret", "") // remove secret so others can't see it
secretKeyBytes, err := secret.EncodedStringToKey(secretKey)
if err != nil {
return nil, trace.BadParameter("bad secret")
}
encryptor, err := secret.New(&secret.Config{KeyBytes: secretKeyBytes})
if err != nil {
return nil, trace.Wrap(err)
}
sealedBytes, err := encryptor.Seal(out)
if err != nil {
return nil, trace.Wrap(err)
}
sealedBytesData, err := json.Marshal(sealedBytes)
if err != nil {
return nil, trace.Wrap(err)
}
values.Set("response", string(sealedBytesData))
u.RawQuery = values.Encode()
return u, nil
}
// createSessionReq is a request to create session from username, password and second
// factor token
type createSessionReq struct {
User string `json:"user"`
Pass string `json:"pass"`
SecondFactorToken string `json:"second_factor_token"`
}
// CreateSessionResponse returns OAuth compabible data about
// access token: https://tools.ietf.org/html/rfc6749
type CreateSessionResponse struct {
// Type is token type (bearer)
Type string `json:"type"`
// Token value
Token string `json:"token"`
// User represents the user
User interface{} `json:"user"`
// ExpiresIn sets seconds before this token is not valid
ExpiresIn int `json:"expires_in"`
}
type createSessionResponseRaw struct {
// Type is token type (bearer)
Type string `json:"type"`
// Token value
Token string `json:"token"`
// User represents the user
User json.RawMessage `json:"user"`
// ExpiresIn sets seconds before this token is not valid
ExpiresIn int `json:"expires_in"`
}
func (r createSessionResponseRaw) response() (*CreateSessionResponse, services.User, error) {
user, err := services.GetUserMarshaler().UnmarshalUser(r.User)
if err != nil {
return nil, nil, trace.Wrap(err)
}
return &CreateSessionResponse{Type: r.Type, Token: r.Token, ExpiresIn: r.ExpiresIn, User: user.WebSessionInfo(nil)}, user, nil
}
func NewSessionResponse(ctx *SessionContext) (*CreateSessionResponse, error) {
clt, err := ctx.GetClient()
if err != nil {
return nil, trace.Wrap(err)
}
webSession := ctx.GetWebSession()
user, err := clt.GetUser(webSession.GetUser())
if err != nil {
return nil, trace.Wrap(err)
}
var roles services.RoleSet
for _, roleName := range user.GetRoles() {
role, err := clt.GetRole(roleName)
if err != nil {
return nil, trace.Wrap(err)
}
roles = append(roles, role)
}
allowedLogins, err := roles.CheckLogins(0)
if err != nil {
return nil, trace.Wrap(err)
}
return &CreateSessionResponse{
Type: roundtrip.AuthBearer,
Token: webSession.GetBearerToken(),
User: user.WebSessionInfo(allowedLogins),
ExpiresIn: int(webSession.GetBearerTokenExpiryTime().Sub(time.Now()) / time.Second),
}, nil
}
// createSession creates a new web session based on user, pass and 2nd factor token
//
// POST /v1/webapi/sessions
//
// {"user": "alex", "pass": "abc123", "second_factor_token": "token", "second_factor_type": "totp"}
//
// Response
//
// {"type": "bearer", "token": "bearer token", "user": {"name": "alex", "allowed_logins": ["admin", "bob"]}, "expires_in": 20}
//
func (m *Handler) createSession(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
var req *createSessionReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
// get cluster preferences to see if we should login
// with password or password+otp
authClient := m.cfg.ProxyClient
cap, err := authClient.GetClusterAuthPreference()
if err != nil {
return nil, trace.Wrap(err)
}
var webSession services.WebSession
switch cap.GetSecondFactor() {
case teleport.OFF:
webSession, err = m.auth.AuthWithoutOTP(req.User, req.Pass)
case teleport.OTP, teleport.HOTP, teleport.TOTP:
webSession, err = m.auth.AuthWithOTP(req.User, req.Pass, req.SecondFactorToken)
default:
return nil, trace.AccessDenied("unknown second factor type: %q", cap.GetSecondFactor())
}
if err != nil {
return nil, trace.AccessDenied("bad auth credentials")
}
if err := SetSession(w, req.User, webSession.GetName()); err != nil {
return nil, trace.Wrap(err)
}
ctx, err := m.auth.ValidateSession(req.User, webSession.GetName())
if err != nil {
return nil, trace.AccessDenied("need auth")
}
return NewSessionResponse(ctx)
}
// deleteSession is called to sign out user
//
// DELETE /v1/webapi/sessions/:sid
//
// Response:
//
// {"message": "ok"}
//
func (m *Handler) deleteSession(w http.ResponseWriter, r *http.Request, _ httprouter.Params, ctx *SessionContext) (interface{}, error) {
if err := ctx.Invalidate(); err != nil {
return nil, trace.Wrap(err)
}
if err := ClearSession(w); err != nil {
return nil, trace.Wrap(err)
}
return ok(), nil
}
// renewSession is called to renew the session that is about to expire
// it issues the new session and generates new session cookie.
// It's important to understand that the old session becomes effectively invalid.
//
// POST /v1/webapi/sessions/renew
//
// Response
//
// {"type": "bearer", "token": "bearer token", "user": {"name": "alex", "allowed_logins": ["admin", "bob"]}, "expires_in": 20}
//
//
func (m *Handler) renewSession(w http.ResponseWriter, r *http.Request, _ httprouter.Params, ctx *SessionContext) (interface{}, error) {
newSess, err := ctx.ExtendWebSession()
if err != nil {
return nil, trace.Wrap(err)
}
// transfer ownership over connections that were opened in the
// sessionContext
newContext, err := ctx.parent.ValidateSession(newSess.GetUser(), newSess.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
newContext.AddClosers(ctx.TransferClosers()...)
if err := SetSession(w, newSess.GetUser(), newSess.GetName()); err != nil {
return nil, trace.Wrap(err)
}
return NewSessionResponse(newContext)
}
type renderUserInviteResponse struct {
InviteToken string `json:"invite_token"`
User string `json:"user"`
QR []byte `json:"qr"`
}
// renderUserInvite is called to show user the new user invitation page
//
// GET /v1/webapi/users/invites/:token
//
// Response:
//
// {"invite_token": "token", "user": "alex", qr: "base64-encoded-qr-code image"}
//
//
func (m *Handler) renderUserInvite(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
token := p[0].Value
user, qrCodeBytes, err := m.auth.GetUserInviteInfo(token)
if err != nil {
return nil, trace.Wrap(err)
}
return &renderUserInviteResponse{
InviteToken: token,
User: user,
QR: qrCodeBytes,
}, nil
}
// u2fRegisterRequest is called to get a U2F challenge for registering a U2F key
//
// GET /webapi/u2f/signuptokens/:token
//
// Response:
//
// {"version":"U2F_V2","challenge":"randombase64string","appId":"https://mycorp.com:3080"}
//
func (m *Handler) u2fRegisterRequest(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
token := p[0].Value
u2fRegisterRequest, err := m.auth.GetUserInviteU2FRegisterRequest(token)
if err != nil {
return nil, trace.Wrap(err)
}
return u2fRegisterRequest, nil
}
// u2fSignRequest is called to get a U2F challenge for authenticating
//
// POST /webapi/u2f/signrequest
//
// {"user": "alex", "pass": "abc123"}
//
// Successful response:
//
// {"version":"U2F_V2","challenge":"randombase64string","keyHandle":"longbase64string","appId":"https://mycorp.com:3080"}
//
func (m *Handler) u2fSignRequest(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
var req *client.U2fSignRequestReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
u2fSignReq, err := m.auth.GetU2FSignRequest(req.User, req.Pass)
if err != nil {
return nil, trace.AccessDenied("bad auth credentials")
}
return u2fSignReq, nil
}
// A request from the client to send the signature from the U2F key
type u2fSignResponseReq struct {
User string `json:"user"`
U2FSignResponse u2f.SignResponse `json:"u2f_sign_response"`
}
// createSessionWithU2FSignResponse is called to sign in with a U2F signature
//
// POST /webapi/u2f/session
//
// {"user": "alex", "u2f_sign_response": { "signatureData": "signatureinbase64", "clientData": "verylongbase64string", "challenge": "randombase64string" }}
//
// Successful response:
//
// {"type": "bearer", "token": "bearer token", "user": {"name": "alex", "allowed_logins": ["admin", "bob"]}, "expires_in": 20}
//
func (m *Handler) createSessionWithU2FSignResponse(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
var req *u2fSignResponseReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
sess, err := m.auth.AuthWithU2FSignResponse(req.User, &req.U2FSignResponse)
if err != nil {
return nil, trace.AccessDenied("bad auth credentials")
}
if err := SetSession(w, req.User, sess.GetName()); err != nil {
return nil, trace.Wrap(err)
}
ctx, err := m.auth.ValidateSession(req.User, sess.GetName())
if err != nil {
return nil, trace.AccessDenied("need auth")
}
return NewSessionResponse(ctx)
}
// createNewUser req is a request to create a new Teleport user
type createNewUserReq struct {
InviteToken string `json:"invite_token"`
Pass string `json:"pass"`
SecondFactorToken string `json:"second_factor_token,omitempty"`
}
// createNewUser creates new user entry based on the invite token
//
// POST /v1/webapi/users
//
// {"invite_token": "unique invite token", "pass": "user password", "second_factor_token": "valid second factor token"}
//
// Sucessful response: (session cookie is set)
//
// {"type": "bearer", "token": "bearer token", "user": "alex", "expires_in": 20}
func (m *Handler) createNewUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
var req *createNewUserReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
sess, err := m.auth.CreateNewUser(req.InviteToken, req.Pass, req.SecondFactorToken)
if err != nil {
return nil, trace.Wrap(err)
}
ctx, err := m.auth.ValidateSession(sess.GetUser(), sess.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
if err := SetSession(w, sess.GetUser(), sess.GetName()); err != nil {
return nil, trace.Wrap(err)
}
return NewSessionResponse(ctx)
}
// A request to create a new user which uses U2F as the second factor
type createNewU2FUserReq struct {
InviteToken string `json:"invite_token"`
Pass string `json:"pass"`
U2FRegisterResponse u2f.RegisterResponse `json:"u2f_register_response"`
}
// createNewU2FUser creates a new user configured to use U2F as the second factor
//
// POST /webapi/u2f/users
//
// {"invite_token": "unique invite token", "pass": "user password", "u2f_register_response": {"registrationData":"verylongbase64string","clientData":"longbase64string"}}
//
// Sucessful response: (session cookie is set)
//
// {"type": "bearer", "token": "bearer token", "user": "alex", "expires_in": 20}
func (m *Handler) createNewU2FUser(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error) {
var req *createNewU2FUserReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
sess, err := m.auth.CreateNewU2FUser(req.InviteToken, req.Pass, req.U2FRegisterResponse)
if err != nil {
return nil, trace.Wrap(err)
}
ctx, err := m.auth.ValidateSession(sess.GetUser(), sess.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
if err := SetSession(w, sess.GetUser(), sess.GetName()); err != nil {
return nil, trace.Wrap(err)
}
return NewSessionResponse(ctx)
}
type getSitesResponse struct {
Sites []site `json:"sites"`
}
type site struct {
Name string `json:"name"`
LastConnected time.Time `json:"last_connected"`
Status string `json:"status"`
}
func convertSites(rs []reversetunnel.RemoteSite) []site {
out := make([]site, len(rs))
for i := range rs {
out[i] = site{
Name: rs[i].GetName(),
LastConnected: rs[i].GetLastConnected(),
Status: rs[i].GetStatus(),
}
}
return out
}
// getSites returns a list of sites
//
// GET /v1/webapi/sites
//
// Sucessful response:
//
// {"sites": {"name": "localhost", "last_connected": "RFC3339 time", "status": "active"}}
//
func (m *Handler) getSites(w http.ResponseWriter, r *http.Request, _ httprouter.Params, c *SessionContext) (interface{}, error) {
return getSitesResponse{
Sites: convertSites(m.cfg.Proxy.GetSites()),
}, nil
}
type getSiteNamespacesResponse struct {
Namespaces []services.Namespace `json:"namespaces"`
}
/* getSiteNamespaces returns a list of namespaces for a given site
GET /v1/webapi/namespaces/:namespace/sites/:site/nodes
Sucessful response:
{"namespaces": [{..namespace resource...}]}
*/
func (m *Handler) getSiteNamespaces(w http.ResponseWriter, r *http.Request, _ httprouter.Params, c *SessionContext, site reversetunnel.RemoteSite) (interface{}, error) {
log.Debugf("[web] GET /namespaces")
clt, err := site.GetClient()
if err != nil {
return nil, trace.Wrap(err)
}
namespaces, err := clt.GetNamespaces()
if err != nil {
return nil, trace.Wrap(err)
}
return getSiteNamespacesResponse{
Namespaces: namespaces,
}, nil
}
type nodeWithSessions struct {
Node services.ServerV1 `json:"node"`
Sessions []session.Session `json:"sessions"`
}
type getSiteNodesResponse struct {
Nodes []nodeWithSessions `json:"nodes"`
}