forked from gravitational/teleport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clt.go
1485 lines (1318 loc) · 46.4 KB
/
clt.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 auth
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/gravitational/roundtrip"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/defaults"
"github.com/gravitational/teleport/lib/events"
"github.com/gravitational/teleport/lib/httplib"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/trace"
log "github.com/Sirupsen/logrus"
"github.com/tstranex/u2f"
)
// CurrentVersion is a current API version
const CurrentVersion = services.V2
type Dialer func(network, addr string) (net.Conn, error)
// Client is HTTP Auth API client. It works by connecting to auth servers
// via HTTP.
//
// When Teleport servers connect to auth API, they usually establish an SSH
// tunnel first, and then do HTTP-over-SSH. This client is wrapped by auth.TunClient
// in lib/auth/tun.go
type Client struct {
roundtrip.Client
transport *http.Transport
}
// NewTracer returns request tracer based on the logging level
func NewTracer() roundtrip.RequestTracer {
if log.GetLevel() >= log.DebugLevel {
return roundtrip.NewWriterTracer(log.StandardLogger().Writer())
}
return roundtrip.NewNopTracer()
}
// NewAuthClient returns a new instance of the client which talks to
// an Auth server API (aka "site API") via HTTP-over-SSH
func NewClient(addr string, dialer Dialer, params ...roundtrip.ClientParam) (*Client, error) {
if dialer == nil {
dialer = net.Dial
}
transport := &http.Transport{
Dial: dialer,
ResponseHeaderTimeout: defaults.DefaultDialTimeout,
}
params = append(params,
roundtrip.HTTPClient(&http.Client{
Transport: transport,
}),
roundtrip.Tracer(NewTracer),
)
c, err := roundtrip.NewClient(addr, CurrentVersion, params...)
if err != nil {
return nil, err
}
return &Client{
Client: *c,
transport: transport,
}, nil
}
func (c *Client) GetTransport() *http.Transport {
return c.transport
}
// PostJSON is a generic method that issues http POST request to the server
func (c *Client) PostJSON(
endpoint string, val interface{}) (*roundtrip.Response, error) {
return httplib.ConvertResponse(c.Client.PostJSON(endpoint, val))
}
// PutJSON is a generic method that issues http PUT request to the server
func (c *Client) PutJSON(
endpoint string, val interface{}) (*roundtrip.Response, error) {
return httplib.ConvertResponse(c.Client.PutJSON(endpoint, val))
}
// PostForm is a generic method that issues http POST request to the server
func (c *Client) PostForm(
endpoint string,
vals url.Values,
files ...roundtrip.File) (*roundtrip.Response, error) {
return httplib.ConvertResponse(c.Client.PostForm(endpoint, vals, files...))
}
// Get issues http GET request to the server
func (c *Client) Get(u string, params url.Values) (*roundtrip.Response, error) {
return httplib.ConvertResponse(c.Client.Get(u, params))
}
// Delete issues http Delete Request to the server
func (c *Client) Delete(u string) (*roundtrip.Response, error) {
return httplib.ConvertResponse(c.Client.Delete(u))
}
// GetSessions returns a list of active sessions in the cluster
// as reported by auth server
func (c *Client) GetSessions(namespace string) ([]session.Session, error) {
if namespace == "" {
return nil, trace.BadParameter("missing namespace parameter")
}
out, err := c.Get(c.Endpoint("namespaces", namespace, "sessions"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var sessions []session.Session
if err := json.Unmarshal(out.Bytes(), &sessions); err != nil {
return nil, err
}
return sessions, nil
}
// GetSession returns a session by ID
func (c *Client) GetSession(namespace string, id session.ID) (*session.Session, error) {
if namespace == "" {
return nil, trace.BadParameter("missing parameter namespace")
}
// saving extra round-trip
if err := id.Check(); err != nil {
return nil, trace.Wrap(err)
}
out, err := c.Get(c.Endpoint("namespaces", namespace, "sessions", string(id)), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var sess *session.Session
if err := json.Unmarshal(out.Bytes(), &sess); err != nil {
return nil, trace.Wrap(err)
}
return sess, nil
}
// DeleteSession deletes a session by ID
func (c *Client) DeleteSession(namespace, id string) error {
if namespace == "" {
return trace.BadParameter("missing namespace parameter")
}
_, err := c.Delete(c.Endpoint("namespaces", namespace, "sessions", id))
return trace.Wrap(err)
}
// CreateSession creates new session
func (c *Client) CreateSession(sess session.Session) error {
if sess.Namespace == "" {
return trace.BadParameter("missing parameter namespace")
}
_, err := c.PostJSON(c.Endpoint("namespaces", sess.Namespace, "sessions"), createSessionReq{Session: sess})
return trace.Wrap(err)
}
// UpdateSession updates existing session
func (c *Client) UpdateSession(req session.UpdateRequest) error {
if err := req.Check(); err != nil {
return trace.Wrap(err)
}
_, err := c.PutJSON(c.Endpoint("namespaces", req.Namespace, "sessions", string(req.ID)), updateSessionReq{Update: req})
return trace.Wrap(err)
}
// GetDomainName returns local auth domain of the current auth server
func (c *Client) GetDomainName() (string, error) {
out, err := c.Get(c.Endpoint("domain"), url.Values{})
if err != nil {
return "", trace.Wrap(err)
}
var domain string
if err := json.Unmarshal(out.Bytes(), &domain); err != nil {
return "", trace.Wrap(err)
}
return domain, nil
}
func (c *Client) Close() error {
return nil
}
// UpsertCertAuthority updates or inserts new cert authority
func (c *Client) UpsertCertAuthority(ca services.CertAuthority) error {
if err := ca.Check(); err != nil {
return trace.Wrap(err)
}
data, err := services.GetCertAuthorityMarshaler().MarshalCertAuthority(ca)
if err != nil {
return trace.Wrap(err)
}
_, err = c.PostJSON(c.Endpoint("authorities", string(ca.GetType())),
&upsertCertAuthorityRawReq{CA: data})
return trace.Wrap(err)
}
// GetCertAuthorities returns a list of certificate authorities
func (c *Client) GetCertAuthorities(caType services.CertAuthType, loadKeys bool) ([]services.CertAuthority, error) {
if err := caType.Check(); err != nil {
return nil, trace.Wrap(err)
}
out, err := c.Get(c.Endpoint("authorities", string(caType)), url.Values{
"load_keys": []string{fmt.Sprintf("%t", loadKeys)},
})
if err != nil {
return nil, trace.Wrap(err)
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, err
}
re := make([]services.CertAuthority, len(items))
for i, raw := range items {
ca, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(raw)
if err != nil {
return nil, trace.Wrap(err)
}
re[i] = ca
}
return re, nil
}
// GetCertAuthority returns certificate authority by given id. Parameter loadSigningKeys
// controls if signing keys are loaded
func (c *Client) GetCertAuthority(id services.CertAuthID, loadSigningKeys bool) (services.CertAuthority, error) {
if err := id.Check(); err != nil {
return nil, trace.Wrap(err)
}
out, err := c.Get(c.Endpoint("authorities", string(id.Type), id.DomainName), url.Values{
"load_keys": []string{fmt.Sprintf("%t", loadSigningKeys)},
})
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(out.Bytes())
}
// DeleteCertAuthority deletes cert authority by ID
func (c *Client) DeleteCertAuthority(id services.CertAuthID) error {
if err := id.Check(); err != nil {
return trace.Wrap(err)
}
_, err := c.Delete(c.Endpoint("authorities", string(id.Type), id.DomainName))
return trace.Wrap(err)
}
// GenerateToken creates a special provisioning token for a new SSH server
// that is valid for ttl period seconds.
//
// This token is used by SSH server to authenticate with Auth server
// and get signed certificate and private key from the auth server.
//
// The token can be used only once.
func (c *Client) GenerateToken(roles teleport.Roles, ttl time.Duration) (string, error) {
out, err := c.PostJSON(c.Endpoint("tokens"), generateTokenReq{
Roles: roles,
TTL: ttl,
})
if err != nil {
return "", trace.Wrap(err)
}
var token string
if err := json.Unmarshal(out.Bytes(), &token); err != nil {
return "", trace.Wrap(err)
}
return token, nil
}
// RegisterUsingToken calls the auth service API to register a new node using a registration token
// which was previously issued via GenerateToken.
func (c *Client) RegisterUsingToken(token, hostID string, nodeName string, role teleport.Role) (*PackedKeys, error) {
out, err := c.PostJSON(c.Endpoint("tokens", "register"),
registerUsingTokenReq{
HostID: hostID,
NodeName: nodeName,
Token: token,
Role: role,
})
if err != nil {
return nil, trace.Wrap(err)
}
var keys PackedKeys
if err := json.Unmarshal(out.Bytes(), &keys); err != nil {
return nil, trace.Wrap(err)
}
return &keys, nil
}
// GetTokens returns a list of active invitation tokens for nodes and users
func (c *Client) GetTokens() (tokens []services.ProvisionToken, err error) {
out, err := c.Get(c.Endpoint("tokens"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
if err := json.Unmarshal(out.Bytes(), &tokens); err != nil {
return nil, trace.Wrap(err)
}
return tokens, nil
}
// GetToken returns provisioning token
func (c *Client) GetToken(token string) (*services.ProvisionToken, error) {
out, err := c.Get(c.Endpoint("tokens", token), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var tok services.ProvisionToken
if err := json.Unmarshal(out.Bytes(), &tok); err != nil {
return nil, trace.Wrap(err)
}
return &tok, nil
}
// DeleteToken deletes a given provisioning token on the auth server (CA). It
// could be a user token or a machine token
func (c *Client) DeleteToken(token string) error {
_, err := c.Delete(c.Endpoint("tokens", token))
return trace.Wrap(err)
}
// RegisterNewAuthServer is used to register new auth server with token
func (c *Client) RegisterNewAuthServer(token string) error {
_, err := c.PostJSON(c.Endpoint("tokens", "register", "auth"), registerNewAuthServerReq{
Token: token,
})
return trace.Wrap(err)
}
// UpsertNode is used by SSH servers to reprt their presense
// to the auth servers in form of hearbeat expiring after ttl period.
func (c *Client) UpsertNode(s services.Server) error {
if s.GetNamespace() == "" {
return trace.BadParameter("missing node namespace")
}
data, err := services.GetServerMarshaler().MarshalServer(s)
if err != nil {
return trace.Wrap(err)
}
args := &upsertServerRawReq{
Server: data,
}
_, err = c.PostJSON(c.Endpoint("namespaces", s.GetNamespace(), "nodes"), args)
return trace.Wrap(err)
}
// GetNodes returns the list of servers registered in the cluster.
func (c *Client) GetNodes(namespace string) ([]services.Server, error) {
if namespace == "" {
return nil, trace.BadParameter("missing parameter namespace")
}
out, err := c.Get(c.Endpoint("namespaces", namespace, "nodes"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, trace.Wrap(err)
}
re := make([]services.Server, len(items))
for i, raw := range items {
s, err := services.GetServerMarshaler().UnmarshalServer(raw, services.KindNode)
if err != nil {
return nil, trace.Wrap(err)
}
re[i] = s
}
return re, nil
}
// UpsertReverseTunnel is used by admins to create a new reverse tunnel
// to the remote proxy to bypass firewall restrictions
func (c *Client) UpsertReverseTunnel(tunnel services.ReverseTunnel) error {
data, err := services.GetReverseTunnelMarshaler().MarshalReverseTunnel(tunnel)
if err != nil {
return trace.Wrap(err)
}
args := &upsertReverseTunnelRawReq{
ReverseTunnel: data,
}
_, err = c.PostJSON(c.Endpoint("reversetunnels"), args)
return trace.Wrap(err)
}
// GetReverseTunnels returns the list of created reverse tunnels
func (c *Client) GetReverseTunnels() ([]services.ReverseTunnel, error) {
out, err := c.Get(c.Endpoint("reversetunnels"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, trace.Wrap(err)
}
tunnels := make([]services.ReverseTunnel, len(items))
for i, raw := range items {
tunnel, err := services.GetReverseTunnelMarshaler().UnmarshalReverseTunnel(raw)
if err != nil {
return nil, trace.Wrap(err)
}
tunnels[i] = tunnel
}
return tunnels, nil
}
// DeleteReverseTunnel deletes reverse tunnel by domain name
func (c *Client) DeleteReverseTunnel(domainName string) error {
// this is to avoid confusing error in case if domain emtpy for example
// HTTP route will fail producing generic not found error
// instead we catch the error here
if strings.TrimSpace(domainName) == "" {
return trace.BadParameter("empty domain name")
}
_, err := c.Delete(c.Endpoint("reversetunnels", domainName))
return trace.Wrap(err)
}
// UpsertAuthServer is used by auth servers to report their presense
// to other auth servers in form of hearbeat expiring after ttl period.
func (c *Client) UpsertAuthServer(s services.Server) error {
data, err := services.GetServerMarshaler().MarshalServer(s)
if err != nil {
return trace.Wrap(err)
}
args := &upsertServerRawReq{
Server: data,
}
_, err = c.PostJSON(c.Endpoint("authservers"), args)
return trace.Wrap(err)
}
// GetAuthServers returns the list of auth servers registered in the cluster.
func (c *Client) GetAuthServers() ([]services.Server, error) {
out, err := c.Get(c.Endpoint("authservers"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, trace.Wrap(err)
}
re := make([]services.Server, len(items))
for i, raw := range items {
server, err := services.GetServerMarshaler().UnmarshalServer(raw, services.KindAuthServer)
if err != nil {
return nil, trace.Wrap(err)
}
re[i] = server
}
return re, nil
}
// UpsertProxy is used by proxies to report their presense
// to other auth servers in form of hearbeat expiring after ttl period.
func (c *Client) UpsertProxy(s services.Server) error {
data, err := services.GetServerMarshaler().MarshalServer(s)
if err != nil {
return trace.Wrap(err)
}
args := &upsertServerRawReq{
Server: data,
}
_, err = c.PostJSON(c.Endpoint("proxies"), args)
return trace.Wrap(err)
}
// GetProxies returns the list of auth servers registered in the cluster.
func (c *Client) GetProxies() ([]services.Server, error) {
out, err := c.Get(c.Endpoint("proxies"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, trace.Wrap(err)
}
re := make([]services.Server, len(items))
for i, raw := range items {
server, err := services.GetServerMarshaler().UnmarshalServer(raw, services.KindProxy)
if err != nil {
return nil, trace.Wrap(err)
}
re[i] = server
}
return re, nil
}
// GetU2FAppID returns U2F settings, like App ID and Facets
func (c *Client) GetU2FAppID() (string, error) {
out, err := c.Get(c.Endpoint("u2f", "appID"), url.Values{})
if err != nil {
return "", trace.Wrap(err)
}
var appid string
if err := json.Unmarshal(out.Bytes(), &appid); err != nil {
return "", trace.Wrap(err)
}
return appid, nil
}
// UpsertPassword updates web access password for the user
func (c *Client) UpsertPassword(user string, password []byte) error {
_, err := c.PostJSON(
c.Endpoint("users", user, "web", "password"),
upsertPasswordReq{
Password: string(password),
})
if err != nil {
return trace.Wrap(err)
}
return nil
}
// UpsertUser user updates or inserts user entry
func (c *Client) UpsertUser(user services.User) error {
data, err := services.GetUserMarshaler().MarshalUser(user)
if err != nil {
return trace.Wrap(err)
}
_, err = c.PostJSON(c.Endpoint("users"), &upsertUserRawReq{User: data})
return trace.Wrap(err)
}
// CheckPassword checks if the suplied web access password is valid.
func (c *Client) CheckPassword(user string, password []byte, otpToken string) error {
_, err := c.PostJSON(
c.Endpoint("users", user, "web", "password", "check"),
checkPasswordReq{
Password: string(password),
OTPToken: otpToken,
})
return trace.Wrap(err)
}
// SignIn checks if the web access password is valid, and if it is valid
// returns a secure web session id.
func (c *Client) SignIn(user string, password []byte) (services.WebSession, error) {
out, err := c.PostJSON(
c.Endpoint("users", user, "web", "signin"),
signInReq{
Password: string(password),
},
)
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}
// PreAuthenticatedSignIn is for 2-way authentication methods like U2F where the password is
// already checked before issueing the second factor challenge
func (c *Client) PreAuthenticatedSignIn(user string) (services.WebSession, error) {
out, err := c.Get(
c.Endpoint("users", user, "web", "signin", "preauth"),
url.Values{},
)
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}
// GetU2FSignRequest generates request for user trying to authenticate with U2F token
func (c *Client) GetU2FSignRequest(user string, password []byte) (*u2f.SignRequest, error) {
out, err := c.PostJSON(
c.Endpoint("u2f", "users", user, "sign"),
signInReq{
Password: string(password),
},
)
if err != nil {
return nil, trace.Wrap(err)
}
var signRequest *u2f.SignRequest
if err := json.Unmarshal(out.Bytes(), &signRequest); err != nil {
return nil, err
}
return signRequest, nil
}
// ExtendWebSession creates a new web session for a user based on another
// valid web session
func (c *Client) ExtendWebSession(user string, prevSessionID string) (services.WebSession, error) {
out, err := c.PostJSON(
c.Endpoint("users", user, "web", "sessions"),
createWebSessionReq{
PrevSessionID: prevSessionID,
},
)
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}
// CreateWebSession creates a new web session for a user
func (c *Client) CreateWebSession(user string) (services.WebSession, error) {
out, err := c.PostJSON(
c.Endpoint("users", user, "web", "sessions"),
createWebSessionReq{},
)
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}
// GetWebSessionInfo checks if a web sesion is valid, returns session id in case if
// it is valid, or error otherwise.
func (c *Client) GetWebSessionInfo(user string, sid string) (services.WebSession, error) {
out, err := c.Get(
c.Endpoint("users", user, "web", "sessions", sid), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}
// DeleteWebSession deletes a web session for this user by id
func (c *Client) DeleteWebSession(user string, sid string) error {
_, err := c.Delete(c.Endpoint("users", user, "web", "sessions", sid))
return trace.Wrap(err)
}
// GetUser returns a list of usernames registered in the system
func (c *Client) GetUser(name string) (services.User, error) {
if name == "" {
return nil, trace.BadParameter("missing username")
}
out, err := c.Get(c.Endpoint("users", name), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
user, err := services.GetUserMarshaler().UnmarshalUser(out.Bytes())
if err != nil {
return nil, trace.Wrap(err)
}
return user, nil
}
// GetUsers returns a list of usernames registered in the system
func (c *Client) GetUsers() ([]services.User, error) {
out, err := c.Get(c.Endpoint("users"), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, trace.Wrap(err)
}
users := make([]services.User, len(items))
for i, userBytes := range items {
user, err := services.GetUserMarshaler().UnmarshalUser(userBytes)
if err != nil {
return nil, trace.Wrap(err)
}
users[i] = user
}
return users, nil
}
// DeleteUser deletes a user by username
func (c *Client) DeleteUser(user string) error {
_, err := c.Delete(c.Endpoint("users", user))
return trace.Wrap(err)
}
// GenerateKeyPair generates SSH private/public key pair optionally protected
// by password. If the pass parameter is an empty string, the key pair
// is not password-protected.
func (c *Client) GenerateKeyPair(pass string) ([]byte, []byte, error) {
out, err := c.PostJSON(c.Endpoint("keypair"), generateKeyPairReq{Password: pass})
if err != nil {
return nil, nil, trace.Wrap(err)
}
var kp *generateKeyPairResponse
if err := json.Unmarshal(out.Bytes(), &kp); err != nil {
return nil, nil, err
}
return kp.PrivKey, []byte(kp.PubKey), err
}
// GenerateHostCert takes the public key in the Open SSH ``authorized_keys``
// plain text format, signs it using Host Certificate Authority private key and returns the
// resulting certificate.
func (c *Client) GenerateHostCert(
key []byte, hostID, nodeName, clusterName string, roles teleport.Roles, ttl time.Duration) ([]byte, error) {
out, err := c.PostJSON(c.Endpoint("ca", "host", "certs"),
generateHostCertReq{
Key: key,
HostID: hostID,
NodeName: nodeName,
ClusterName: clusterName,
Roles: roles,
TTL: ttl,
})
if err != nil {
return nil, trace.Wrap(err)
}
var cert string
if err := json.Unmarshal(out.Bytes(), &cert); err != nil {
return nil, err
}
return []byte(cert), nil
}
// GenerateUserCert takes the public key in the Open SSH ``authorized_keys``
// plain text format, signs it using User Certificate Authority signing key and returns the
// resulting certificate.
func (c *Client) GenerateUserCert(
key []byte, user string, ttl time.Duration) ([]byte, error) {
out, err := c.PostJSON(c.Endpoint("ca", "user", "certs"),
generateUserCertReq{
Key: key,
User: user,
TTL: ttl,
})
if err != nil {
return nil, trace.Wrap(err)
}
var cert string
if err := json.Unmarshal(out.Bytes(), &cert); err != nil {
return nil, trace.Wrap(err)
}
return []byte(cert), nil
}
// CreateSignupToken creates one time token for creating account for the user
// For each token it creates username and otp generator
func (c *Client) CreateSignupToken(user services.UserV1) (string, error) {
if err := user.Check(); err != nil {
return "", trace.Wrap(err)
}
out, err := c.PostJSON(c.Endpoint("signuptokens"), createSignupTokenReq{
User: user,
})
if err != nil {
return "", trace.Wrap(err)
}
var token string
if err := json.Unmarshal(out.Bytes(), &token); err != nil {
return "", trace.Wrap(err)
}
return token, nil
}
// GetSignupTokenData returns token data for a valid token
func (c *Client) GetSignupTokenData(token string) (user string, otpQRCode []byte, e error) {
out, err := c.Get(c.Endpoint("signuptokens", token), url.Values{})
if err != nil {
return "", nil, err
}
var tokenData getSignupTokenDataResponse
if err := json.Unmarshal(out.Bytes(), &tokenData); err != nil {
return "", nil, err
}
return tokenData.User, tokenData.QRImg, nil
}
// GetSignupU2FRegisterRequest generates sign request for user trying to sign up with invite tokenx
func (c *Client) GetSignupU2FRegisterRequest(token string) (u2fRegisterRequest *u2f.RegisterRequest, e error) {
out, err := c.Get(c.Endpoint("u2f", "signuptokens", token), url.Values{})
if err != nil {
return nil, err
}
var u2fRegReq u2f.RegisterRequest
if err := json.Unmarshal(out.Bytes(), &u2fRegReq); err != nil {
return nil, err
}
return &u2fRegReq, nil
}
// CreateUserWithOTP creates account with provided token and password.
// Account username and OTP key are taken from token data.
// Deletes token after account creation.
func (c *Client) CreateUserWithOTP(token, password, otpToken string) (services.WebSession, error) {
out, err := c.PostJSON(c.Endpoint("signuptokens", "users"), createUserWithTokenReq{
Token: token,
Password: password,
OTPToken: otpToken,
})
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}
// CreateUserWithoutOTP validates a given token creates a user
// with the given password and deletes the token afterwards.
func (c *Client) CreateUserWithoutOTP(token string, password string) (services.WebSession, error) {
out, err := c.PostJSON(c.Endpoint("signuptokens", "users"), createUserWithTokenReq{
Token: token,
Password: password,
})
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}
// CreateUserWithU2FToken creates user account with provided token and U2F sign response
func (c *Client) CreateUserWithU2FToken(token string, password string, u2fRegisterResponse u2f.RegisterResponse) (services.WebSession, error) {
out, err := c.PostJSON(c.Endpoint("u2f", "users"), createUserWithU2FTokenReq{
Token: token,
Password: password,
U2FRegisterResponse: u2fRegisterResponse,
})
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}
// UpsertOIDCConnector updates or creates OIDC connector
func (c *Client) UpsertOIDCConnector(connector services.OIDCConnector) error {
data, err := services.GetOIDCConnectorMarshaler().MarshalOIDCConnector(connector)
if err != nil {
return trace.Wrap(err)
}
_, err = c.PostJSON(c.Endpoint("oidc", "connectors"), &upsertOIDCConnectorRawReq{
Connector: data,
})
if err != nil {
return trace.Wrap(err)
}
return nil
}
// GetOIDCConnector returns OIDC connector information by id
func (c *Client) GetOIDCConnector(id string, withSecrets bool) (services.OIDCConnector, error) {
if id == "" {
return nil, trace.BadParameter("missing connector id")
}
out, err := c.Get(c.Endpoint("oidc", "connectors", id),
url.Values{"with_secrets": []string{fmt.Sprintf("%t", withSecrets)}})
if err != nil {
return nil, err
}
return services.GetOIDCConnectorMarshaler().UnmarshalOIDCConnector(out.Bytes())
}
// GetOIDCConnector gets OIDC connectors list
func (c *Client) GetOIDCConnectors(withSecrets bool) ([]services.OIDCConnector, error) {
out, err := c.Get(c.Endpoint("oidc", "connectors"),
url.Values{"with_secrets": []string{fmt.Sprintf("%t", withSecrets)}})
if err != nil {
return nil, err
}
var items []json.RawMessage
if err := json.Unmarshal(out.Bytes(), &items); err != nil {
return nil, trace.Wrap(err)
}
connectors := make([]services.OIDCConnector, len(items))
for i, raw := range items {
connector, err := services.GetOIDCConnectorMarshaler().UnmarshalOIDCConnector(raw)
if err != nil {
return nil, trace.Wrap(err)
}
connectors[i] = connector
}
return connectors, nil
}
// DeleteOIDCConnector deletes OIDC connector by ID
func (c *Client) DeleteOIDCConnector(connectorID string) error {
if connectorID == "" {
return trace.BadParameter("missing connector id")
}
_, err := c.Delete(c.Endpoint("oidc", "connectors", connectorID))
return trace.Wrap(err)
}
// CreateOIDCAuthRequest creates OIDCAuthRequest
func (c *Client) CreateOIDCAuthRequest(req services.OIDCAuthRequest) (*services.OIDCAuthRequest, error) {
out, err := c.PostJSON(c.Endpoint("oidc", "requests", "create"), createOIDCAuthRequestReq{
Req: req,
})
if err != nil {
return nil, trace.Wrap(err)
}
var response *services.OIDCAuthRequest
if err := json.Unmarshal(out.Bytes(), &response); err != nil {
return nil, trace.Wrap(err)
}
return response, nil
}
// ValidateOIDCAuthCallback validates OIDC auth callback returned from redirect
func (c *Client) ValidateOIDCAuthCallback(q url.Values) (*OIDCAuthResponse, error) {
out, err := c.PostJSON(c.Endpoint("oidc", "requests", "validate"), validateOIDCAuthCallbackReq{
Query: q,
})
if err != nil {
return nil, trace.Wrap(err)
}
var rawResponse *oidcAuthRawResponse
if err := json.Unmarshal(out.Bytes(), &rawResponse); err != nil {
return nil, trace.Wrap(err)
}
response := OIDCAuthResponse{
Username: rawResponse.Username,
Identity: rawResponse.Identity,
Cert: rawResponse.Cert,
Req: rawResponse.Req,
}
if len(rawResponse.Session) != 0 {
session, err := services.GetWebSessionMarshaler().UnmarshalWebSession(rawResponse.Session)
if err != nil {
return nil, trace.Wrap(err)
}
response.Session = session
}
response.HostSigners = make([]services.CertAuthority, len(rawResponse.HostSigners))
for i, raw := range rawResponse.HostSigners {
ca, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(raw)
if err != nil {
return nil, trace.Wrap(err)
}
response.HostSigners[i] = ca
}
return &response, nil
}
// EmitAuditEvent sends an auditable event to the auth server (part of evets.IAuditLog interface)
func (c *Client) EmitAuditEvent(eventType string, fields events.EventFields) error {
_, err := c.PostJSON(c.Endpoint("events"), &auditEventReq{
Type: eventType,
Fields: fields,
})
if err != nil {
return trace.Wrap(err)
}
return nil
}
// PostSessionChunk allows clients to submit session stream chunks to the audit log
// (part of evets.IAuditLog interface)
//
// The data is POSTed to HTTP server as a simple binary body (no encodings of any
// kind are needed)
func (c *Client) PostSessionChunk(namespace string, sid session.ID, reader io.Reader) error {
if namespace == "" {
return trace.BadParameter("missing parameter namespace")
}
r, err := http.NewRequest("POST", c.Endpoint("namespaces", namespace, "sessions", string(sid), "stream"), reader)
if err != nil {
return trace.Wrap(err)
}
r.Header.Set("Content-Type", "application/octet-stream")
c.Client.SetAuthHeader(r.Header)
re, err := c.Client.HTTPClient().Do(r)
if err != nil {
return trace.Wrap(err)
}
// we **must** consume response by reading all of its body, otherwise the http
// client will allocate a new connection for subsequent requests
defer re.Body.Close()
responseBytes, _ := ioutil.ReadAll(re.Body)
return trace.ReadError(re.StatusCode, responseBytes)
}
// GetSessionChunk allows clients to receive a byte array (chunk) from a recorded
// session stream, starting from 'offset', up to 'max' in length. The upper bound