-
Notifications
You must be signed in to change notification settings - Fork 0
/
clt.go
2292 lines (2051 loc) · 73.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 (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"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/teleport/lib/utils"
"github.com/gravitational/roundtrip"
"github.com/gravitational/trace"
"github.com/tstranex/u2f"
)
const (
// CurrentVersion is a current API version
CurrentVersion = services.V2
// MissingNamespaceError is a _very_ common error this file generatets
MissingNamespaceError = "missing required parameter: namespace"
)
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 {
tlsConfig *tls.Config
dialContext DialContext
roundtrip.Client
transport *http.Transport
}
// TLSConfig returns TLS config used by the client, could return nil
// if the client is not using TLS
func (c *Client) TLSConfig() *tls.Config {
return c.tlsConfig
}
// DialContext is a function that dials to the specified address
type DialContext func(in context.Context, network, addr string) (net.Conn, error)
// NewAddrDialer returns new dialer from a list of addresses
func NewAddrDialer(addrs []utils.NetAddr) DialContext {
dialer := net.Dialer{
Timeout: defaults.DefaultDialTimeout,
KeepAlive: defaults.ReverseTunnelAgentHeartbeatPeriod,
}
return func(in context.Context, network, _ string) (net.Conn, error) {
var err error
var conn net.Conn
for _, addr := range addrs {
conn, err = dialer.DialContext(in, network, addr.Addr)
if err == nil {
return conn, nil
}
log.Debugf("Failed to dial auth server %v: %v.", addr.Addr, err)
}
// not wrapping on purpose to preserve the original error
return nil, err
}
}
// NewTLSClientWithDialer returns new TLS client that uses mutual TLS authenticate
// and dials the remote server using dialer
func NewTLSClientWithDialer(dialContext DialContext, cfg *tls.Config, params ...roundtrip.ClientParam) (*Client, error) {
cfg.ServerName = teleport.APIDomain
transport := &http.Transport{
// notice that below roundtrip.Client is passed
// teleport.APIEndpoint as an address for the API server, this is
// to make sure client verifies the DNS name of the API server
// custom DialContext overrides this DNS name to the real address
// in addition this dialer tries multiple adresses if provided
DialContext: dialContext,
ResponseHeaderTimeout: defaults.DefaultDialTimeout,
TLSClientConfig: cfg,
MaxIdleConnsPerHost: defaults.HTTPIdleConnsPerHost,
// IdleConnTimeout defines the maximum amount of time before idle connections
// are closed. Leaving this unset will lead to connections open forever and
// will cause memory leaks in a long running process
IdleConnTimeout: defaults.HTTPIdleTimeout,
}
// this logic is necessary to force client to always send certificate
// regardless of the server setting, otherwise client may pick
// not to send the client certificate by looking at certificate request
if len(cfg.Certificates) != 0 {
cert := cfg.Certificates[0]
cfg.Certificates = nil
cfg.GetClientCertificate = func(_ *tls.CertificateRequestInfo) (*tls.Certificate, error) {
return &cert, nil
}
}
params = append(params, roundtrip.HTTPClient(&http.Client{
Transport: transport,
}))
roundtripClient, err := roundtrip.NewClient("https://"+teleport.APIDomain, CurrentVersion, params...)
if err != nil {
return nil, trace.Wrap(err)
}
return &Client{
tlsConfig: cfg,
dialContext: dialContext,
Client: *roundtripClient,
transport: transport,
}, nil
}
// NewTLSClient returns new client using TLS mutual authentication
func NewTLSClient(addrs []utils.NetAddr, cfg *tls.Config, params ...roundtrip.ClientParam) (*Client, error) {
return NewTLSClientWithDialer(NewAddrDialer(addrs), cfg, params...)
}
// 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,
}),
// TODO (ekontsevoy) this tracer pollutes the logs making it harder to work
// on issues that have nothing to do with the auth API, consider activating it
// via special environment variable?
// roundtrip.Tracer(NewTracer),
)
c, err := roundtrip.NewClient(addr, CurrentVersion, params...)
if err != nil {
return nil, err
}
return &Client{
Client: *c,
transport: transport,
}, nil
}
// DELETE IN: 2.6.0
// GetDialer and AccessPoint SSH subsystem are no longer used in Teleport
// as of 2.5.0 and should be removed.
// GetDialer returns dialer that will connect to auth server API
func (c *Client) GetDialer() AccessPointDialer {
return func(ctx context.Context) (conn net.Conn, err error) {
conn, err = c.dialContext(ctx, "tcp", teleport.APIDomain)
if err != nil {
return nil, trace.Wrap(err)
}
return tls.Client(conn, c.tlsConfig), nil
}
}
// GetAgent creates an SSH key agent (similar object to what CLI uses), this
// key agent fetches user keys directly from the auth server using a custom channel
// created via "ReqWebSessionAgent" reguest
func (c *Client) GetAgent() (AgentCloser, error) {
panic("not implemented")
}
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(MissingNamespaceError)
}
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(MissingNamespaceError)
}
// 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(MissingNamespaceError)
}
_, 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(MissingNamespaceError)
}
_, 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
}
func (c *Client) WaitForDelivery(context.Context) error {
return nil
}
// CreateCertAuthority inserts new cert authority
func (c *Client) CreateCertAuthority(ca services.CertAuthority) error {
return trace.BadParameter("not implemented")
}
// 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())
}
// GetAnyCertAuthority returns certificate authority by given id whether it's activated or not
func (c *Client) GetAnyCertAuthority(id services.CertAuthID) (services.CertAuthority, error) {
return nil, trace.BadParameter("not implemented")
}
// 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)
}
// ActivateCertAuthority moves a CertAuthority from the deactivated list to
// the normal list.
func (c *Client) ActivateCertAuthority(id services.CertAuthID) error {
return trace.BadParameter("not implemented")
}
// DeactivateCertAuthority moves a CertAuthority from the normal list to
// the deactivated list.
func (c *Client) DeactivateCertAuthority(id services.CertAuthID) error {
return trace.BadParameter("not implemented")
}
// 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.
//
// If token is not supplied, it will be auto generated and returned.
// If TTL is not supplied, token will be valid until removed.
func (c *Client) GenerateToken(req GenerateTokenRequest) (string, error) {
out, err := c.PostJSON(c.Endpoint("tokens"), req)
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(req RegisterUsingTokenRequest) (*PackedKeys, error) {
if err := req.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
out, err := c.PostJSON(c.Endpoint("tokens", "register"), req)
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
}
// RenewCredentials returns a new set of credentials associated
// with the server with the same privileges
func (c *Client) GenerateServerKeys(req GenerateServerKeysRequest) (*PackedKeys, error) {
if err := req.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
out, err := c.PostJSON(c.Endpoint("server", "credentials"), req)
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 presence
// 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(MissingNamespaceError)
}
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)
}
// GetReverseTunnel returns reverse tunnel by name
func (c *Client) GetReverseTunnel(name string) (services.ReverseTunnel, error) {
return nil, trace.BadParameter("not implemented")
}
// 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 empty 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)
}
// UpsertTunnelConnection upserts tunnel connection
func (c *Client) UpsertTunnelConnection(conn services.TunnelConnection) error {
data, err := services.MarshalTunnelConnection(conn)
if err != nil {
return trace.Wrap(err)
}
args := &upsertTunnelConnectionRawReq{
TunnelConnection: data,
}
_, err = c.PostJSON(c.Endpoint("tunnelconnections"), args)
return trace.Wrap(err)
}
// GetTunnelConnections returns tunnel connections for a given cluster
func (c *Client) GetTunnelConnections(clusterName string) ([]services.TunnelConnection, error) {
if clusterName == "" {
return nil, trace.BadParameter("missing cluster name parameter")
}
out, err := c.Get(c.Endpoint("tunnelconnections", clusterName), 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)
}
conns := make([]services.TunnelConnection, len(items))
for i, raw := range items {
conn, err := services.UnmarshalTunnelConnection(raw)
if err != nil {
return nil, trace.Wrap(err)
}
conns[i] = conn
}
return conns, nil
}
// GetAllTunnelConnections returns all tunnel connections
func (c *Client) GetAllTunnelConnections() ([]services.TunnelConnection, error) {
out, err := c.Get(c.Endpoint("tunnelconnections"), 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)
}
conns := make([]services.TunnelConnection, len(items))
for i, raw := range items {
conn, err := services.UnmarshalTunnelConnection(raw)
if err != nil {
return nil, trace.Wrap(err)
}
conns[i] = conn
}
return conns, nil
}
// DeleteTunnelConnection deletes tunnel connection by name
func (c *Client) DeleteTunnelConnection(clusterName string, connName string) error {
if clusterName == "" {
return trace.BadParameter("missing parameter cluster name")
}
if connName == "" {
return trace.BadParameter("missing parameter connection name")
}
_, err := c.Delete(c.Endpoint("tunnelconnections", clusterName, connName))
return trace.Wrap(err)
}
// DeleteTunnelConnections deletes all tunnel connections for cluster
func (c *Client) DeleteTunnelConnections(clusterName string) error {
if clusterName == "" {
return trace.BadParameter("missing parameter cluster name")
}
_, err := c.Delete(c.Endpoint("tunnelconnections", clusterName))
return trace.Wrap(err)
}
// DeleteAllTunnelConnections deletes all tunnel connections
func (c *Client) DeleteAllTunnelConnections() error {
_, err := c.Delete(c.Endpoint("tunnelconnections"))
return trace.Wrap(err)
}
// AddUserLoginAttempt logs user login attempt
func (c *Client) AddUserLoginAttempt(user string, attempt services.LoginAttempt, ttl time.Duration) error {
panic("not implemented")
}
// GetUserLoginAttempts returns user login attempts
func (c *Client) GetUserLoginAttempts(user string) ([]services.LoginAttempt, error) {
panic("not implemented")
}
// GetRemoteClusters returns a list of remote clusters
func (c *Client) GetRemoteClusters() ([]services.RemoteCluster, error) {
out, err := c.Get(c.Endpoint("remoteclusters"), 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)
}
conns := make([]services.RemoteCluster, len(items))
for i, raw := range items {
conn, err := services.UnmarshalRemoteCluster(raw)
if err != nil {
return nil, trace.Wrap(err)
}
conns[i] = conn
}
return conns, nil
}
// GetRemoteCluster returns a remote cluster by name
func (c *Client) GetRemoteCluster(clusterName string) (services.RemoteCluster, error) {
if clusterName == "" {
return nil, trace.BadParameter("missing cluster name")
}
out, err := c.Get(c.Endpoint("remoteclusters", clusterName), url.Values{})
if err != nil {
return nil, trace.Wrap(err)
}
return services.UnmarshalRemoteCluster(out.Bytes())
}
// DeleteRemoteCluster deletes remote cluster by name
func (c *Client) DeleteRemoteCluster(clusterName string) error {
if clusterName == "" {
return trace.BadParameter("missing parameter cluster name")
}
_, err := c.Delete(c.Endpoint("remoteclusters", clusterName))
return trace.Wrap(err)
}
// DeleteAllRemoteClusters deletes all remote clusters
func (c *Client) DeleteAllRemoteClusters() error {
_, err := c.Delete(c.Endpoint("remoteclusters"))
return trace.Wrap(err)
}
// CreateRemoteCluster creates remote cluster resource
func (c *Client) CreateRemoteCluster(rc services.RemoteCluster) error {
data, err := services.MarshalRemoteCluster(rc)
if err != nil {
return trace.Wrap(err)
}
args := &createRemoteClusterRawReq{
RemoteCluster: data,
}
_, err = c.PostJSON(c.Endpoint("remoteclusters"), args)
return trace.Wrap(err)
}
// UpsertAuthServer is used by auth servers to report their presence
// 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 presence
// 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)
}
// ChangePassword changes user password
func (c *Client) ChangePassword(req services.ChangePasswordReq) error {
_, err := c.PutJSON(c.Endpoint("users", req.User, "web", "password"), req)
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 issuing 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())
}
// DELETE IN: 2.6.0
// ExchangeCerts exchanges TLS certificates for established host certificate authorities
func (c *Client) ExchangeCerts(req ExchangeCertsRequest) (*ExchangeCertsResponse, error) {
out, err := c.PostJSON(
c.Endpoint("exchangecerts"),
req,
)
if err != nil {
return nil, trace.Wrap(err)
}
var re ExchangeCertsResponse
if err := json.Unmarshal(out.Bytes(), &re); err != nil {
return nil, trace.Wrap(err)
}
return &re, nil
}
// AuthenticateWebUser authenticates web user, creates and returns web session
// in case if authentication is successfull
func (c *Client) AuthenticateWebUser(req AuthenticateUserRequest) (services.WebSession, error) {
out, err := c.PostJSON(
c.Endpoint("users", req.Username, "web", "authenticate"),
req,
)
if err != nil {
return nil, trace.Wrap(err)
}
return services.GetWebSessionMarshaler().UnmarshalWebSession(out.Bytes())
}
// AuthenticateSSHUser authenticates SSH console user, creates and returns a pair of signed TLS and SSH
// short lived certificates as a result
func (c *Client) AuthenticateSSHUser(req AuthenticateSSHRequest) (*SSHLoginResponse, error) {
out, err := c.PostJSON(
c.Endpoint("users", req.Username, "ssh", "authenticate"),
req,
)
if err != nil {
return nil, trace.Wrap(err)
}
var re SSHLoginResponse
if err := json.Unmarshal(out.Bytes(), &re); err != nil {
return nil, trace.Wrap(err)
}
return &re, nil
}
// 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{})