-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
sessions.go
652 lines (573 loc) · 17.7 KB
/
sessions.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
/*
Copyright 2015-2019 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
import (
"context"
"crypto/tls"
"crypto/x509"
"io"
"net"
"net/http"
"sync"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"github.com/gravitational/teleport"
"github.com/gravitational/teleport/lib/auth"
"github.com/gravitational/teleport/lib/client"
"github.com/gravitational/teleport/lib/reversetunnel"
"github.com/gravitational/teleport/lib/services"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/trace"
"github.com/gravitational/ttlmap"
"github.com/jonboulle/clockwork"
log "github.com/sirupsen/logrus"
"github.com/tstranex/u2f"
)
// SessionContext is a context associated with users'
// web session, it stores connected client that persists
// between requests for example to avoid connecting
// to the auth server on every page hit
type SessionContext struct {
sync.Mutex
*log.Entry
sess services.WebSession
user string
clt auth.ClientI
remoteClt map[string]auth.ClientI
parent *sessionCache
closers []io.Closer
}
func (c *SessionContext) AddClosers(closers ...io.Closer) {
c.Lock()
defer c.Unlock()
c.closers = append(c.closers, closers...)
}
func (c *SessionContext) RemoveCloser(closer io.Closer) {
c.Lock()
defer c.Unlock()
for i := range c.closers {
if c.closers[i] == closer {
c.closers = append(c.closers[:i], c.closers[i+1:]...)
return
}
}
}
func (c *SessionContext) TransferClosers() []io.Closer {
c.Lock()
defer c.Unlock()
closers := c.closers
c.closers = nil
return closers
}
func (c *SessionContext) Invalidate() error {
return c.parent.InvalidateSession(c)
}
func (c *SessionContext) addRemoteClient(siteName string, remoteClient auth.ClientI) {
c.Lock()
defer c.Unlock()
c.remoteClt[siteName] = remoteClient
}
func (c *SessionContext) getRemoteClient(siteName string) (auth.ClientI, bool) {
c.Lock()
defer c.Unlock()
remoteClt, ok := c.remoteClt[siteName]
return remoteClt, ok
}
// GetClient returns the client connected to the auth server
func (c *SessionContext) GetClient() (auth.ClientI, error) {
return c.clt, nil
}
// GetUserClient will return an auth.ClientI with the role of the user at
// the requested site. If the site is local a client with the users local role
// is returned. If the site is remote a client with the users remote role is
// returned.
func (c *SessionContext) GetUserClient(site reversetunnel.RemoteSite) (auth.ClientI, error) {
// get the name of the current cluster
clt, err := c.GetClient()
if err != nil {
return nil, trace.Wrap(err)
}
cn, err := clt.GetClusterName()
if err != nil {
return nil, trace.Wrap(err)
}
// if we're trying to access the local cluster, pass back the local client.
if cn.GetClusterName() == site.GetName() {
return clt, nil
}
// look to see if we already have a connection to this cluster
remoteClt, ok := c.getRemoteClient(site.GetName())
if !ok {
rClt, rConn, err := c.newRemoteClient(site)
if err != nil {
return nil, trace.Wrap(err)
}
// add a closer for the underlying connection
if rConn != nil {
c.AddClosers(rConn)
}
// we'll save the remote client in our session context so we don't have to
// build a new connection next time. all remote clients will be closed when
// the session context is closed.
c.addRemoteClient(site.GetName(), rClt)
return rClt, nil
}
return remoteClt, nil
}
// newRemoteClient returns a client to a remote cluster with the role of
// the logged in user.
func (c *SessionContext) newRemoteClient(cluster reversetunnel.RemoteSite) (auth.ClientI, net.Conn, error) {
clt, err := c.tryRemoteTLSClient(cluster)
if err != nil {
return nil, nil, trace.Wrap(err)
}
return clt, nil, nil
}
// clusterDialer returns DialContext function using cluster's dial function
func clusterDialer(remoteCluster reversetunnel.RemoteSite) auth.ContextDialer {
return auth.ContextDialerFunc(func(in context.Context, network, _ string) (net.Conn, error) {
return remoteCluster.DialAuthServer()
})
}
// tryRemoteTLSClient tries creating TLS client and using it (the client may not be available
// due to older clusters), returns client if it is working properly
func (c *SessionContext) tryRemoteTLSClient(cluster reversetunnel.RemoteSite) (auth.ClientI, error) {
clt, err := c.newRemoteTLSClient(cluster)
if err != nil {
return nil, trace.Wrap(err)
}
_, err = clt.GetDomainName()
if err != nil {
return clt, trace.Wrap(err)
}
return clt, nil
}
// ClientTLSConfig returns client TLS authentication associated
// with the web session context
func (c *SessionContext) ClientTLSConfig(clusterName ...string) (*tls.Config, error) {
var certPool *x509.CertPool
if len(clusterName) == 0 {
certAuthorities, err := c.parent.proxyClient.GetCertAuthorities(services.HostCA, false)
if err != nil {
return nil, trace.Wrap(err)
}
certPool, err = services.CertPoolFromCertAuthorities(certAuthorities)
if err != nil {
return nil, trace.Wrap(err)
}
} else {
certAuthority, err := c.parent.proxyClient.GetCertAuthority(services.CertAuthID{
Type: services.HostCA,
DomainName: clusterName[0],
}, false)
if err != nil {
return nil, trace.Wrap(err)
}
certPool, err = services.CertPool(certAuthority)
if err != nil {
return nil, trace.Wrap(err)
}
}
tlsConfig := utils.TLSConfig(c.parent.cipherSuites)
tlsCert, err := tls.X509KeyPair(c.sess.GetTLSCert(), c.sess.GetPriv())
if err != nil {
return nil, trace.Wrap(err, "failed to parse TLS cert and key")
}
tlsConfig.Certificates = []tls.Certificate{tlsCert}
tlsConfig.RootCAs = certPool
tlsConfig.ServerName = auth.EncodeClusterName(c.parent.clusterName)
return tlsConfig, nil
}
func (c *SessionContext) newRemoteTLSClient(cluster reversetunnel.RemoteSite) (auth.ClientI, error) {
tlsConfig, err := c.ClientTLSConfig(cluster.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
return auth.NewTLSClient(auth.ClientConfig{Dialer: clusterDialer(cluster), TLS: tlsConfig})
}
// GetUser returns the authenticated teleport user
func (c *SessionContext) GetUser() string {
return c.user
}
// GetWebSession returns a web session
func (c *SessionContext) GetWebSession() services.WebSession {
return c.sess
}
// ExtendWebSession creates a new web session for this user
// based on the previous session
func (c *SessionContext) ExtendWebSession() (services.WebSession, error) {
sess, err := c.clt.ExtendWebSession(c.user, c.sess.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
return sess, nil
}
// GetAgent returns agent that can be used to answer challenges
// for the web to ssh connection as well as certificate
func (c *SessionContext) GetAgent() (agent.Agent, *ssh.Certificate, error) {
pub, _, _, _, err := ssh.ParseAuthorizedKey(c.sess.GetPub())
if err != nil {
return nil, nil, trace.Wrap(err)
}
cert, ok := pub.(*ssh.Certificate)
if !ok {
return nil, nil, trace.BadParameter("expected certificate, got %T", pub)
}
if len(cert.ValidPrincipals) == 0 {
return nil, nil, trace.BadParameter("expected at least valid principal in certificate")
}
privateKey, err := ssh.ParseRawPrivateKey(c.sess.GetPriv())
if err != nil {
return nil, nil, trace.Wrap(err, "failed to parse SSH private key")
}
keyring := agent.NewKeyring()
err = keyring.Add(agent.AddedKey{
PrivateKey: privateKey,
Certificate: cert,
})
if err != nil {
return nil, nil, trace.Wrap(err)
}
return keyring, cert, nil
}
// GetCertificates returns the *ssh.Certificate and *x509.Certificate
// associated with this session.
func (c *SessionContext) GetCertificates() (*ssh.Certificate, *x509.Certificate, error) {
pub, _, _, _, err := ssh.ParseAuthorizedKey(c.sess.GetPub())
if err != nil {
return nil, nil, trace.Wrap(err)
}
sshcert, ok := pub.(*ssh.Certificate)
if !ok {
return nil, nil, trace.BadParameter("not certificate")
}
tlscert, err := utils.ParseCertificatePEM(c.sess.GetTLSCert())
if err != nil {
return nil, nil, trace.Wrap(err)
}
return sshcert, tlscert, nil
}
// Close cleans up connections associated with requests
func (c *SessionContext) Close() error {
closers := c.TransferClosers()
for _, closer := range closers {
c.Debugf("Closing %v.", closer)
closer.Close()
}
if c.clt != nil {
return trace.Wrap(c.clt.Close())
}
return nil
}
// newSessionCache returns new instance of the session cache
func newSessionCache(proxyClient auth.ClientI, servers []utils.NetAddr, cipherSuites []uint16) (*sessionCache, error) {
clusterName, err := proxyClient.GetClusterName()
if err != nil {
return nil, trace.Wrap(err)
}
m, err := ttlmap.New(1024, ttlmap.CallOnExpire(closeContext))
if err != nil {
return nil, trace.Wrap(err)
}
cache := &sessionCache{
clusterName: clusterName.GetClusterName(),
proxyClient: proxyClient,
contexts: m,
authServers: servers,
closer: utils.NewCloseBroadcaster(),
cipherSuites: cipherSuites,
}
// periodically close expired and unused sessions
go cache.expireSessions()
return cache, nil
}
// sessionCache handles web session authentication,
// and holds in memory contexts associated with each session
type sessionCache struct {
sync.Mutex
proxyClient auth.ClientI
contexts *ttlmap.TTLMap
authServers []utils.NetAddr
closer *utils.CloseBroadcaster
clusterName string
// cipherSuites is the list of supported TLS cipher suites.
cipherSuites []uint16
}
// Close closes all allocated resources and stops goroutines
func (s *sessionCache) Close() error {
log.Infof("[WEB] closing session cache")
return s.closer.Close()
}
// closeContext is called when session context expires from
// cache and will clean up connections
func closeContext(key string, val interface{}) {
go func() {
log.Infof("[WEB] closing context %v", key)
ctx, ok := val.(*SessionContext)
if !ok {
log.Warningf("warning, not valid value type %T", val)
return
}
if err := ctx.Close(); err != nil {
log.Infof("failed to close context: %v", err)
}
}()
}
func (s *sessionCache) expireSessions() {
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
s.clearExpiredSessions()
case <-s.closer.C:
return
}
}
}
func (s *sessionCache) clearExpiredSessions() {
s.Lock()
defer s.Unlock()
expired := s.contexts.RemoveExpired(10)
if expired != 0 {
log.Infof("[WEB] removed %v expired sessions", expired)
}
}
func (s *sessionCache) AuthWithOTP(user, pass string, otpToken string) (services.WebSession, error) {
return s.proxyClient.AuthenticateWebUser(auth.AuthenticateUserRequest{
Username: user,
OTP: &auth.OTPCreds{
Password: []byte(pass),
Token: otpToken,
},
})
}
func (s *sessionCache) AuthWithoutOTP(user, pass string) (services.WebSession, error) {
return s.proxyClient.AuthenticateWebUser(auth.AuthenticateUserRequest{
Username: user,
Pass: &auth.PassCreds{
Password: []byte(pass),
},
})
}
func (s *sessionCache) GetU2FSignRequest(user, pass string) (*u2f.SignRequest, error) {
return s.proxyClient.GetU2FSignRequest(user, []byte(pass))
}
func (s *sessionCache) AuthWithU2FSignResponse(user string, response *u2f.SignResponse) (services.WebSession, error) {
return s.proxyClient.AuthenticateWebUser(auth.AuthenticateUserRequest{
Username: user,
U2F: &auth.U2FSignResponseCreds{
SignResponse: *response,
},
})
}
func (s *sessionCache) GetCertificateWithoutOTP(c client.CreateSSHCertReq) (*auth.SSHLoginResponse, error) {
return s.proxyClient.AuthenticateSSHUser(auth.AuthenticateSSHRequest{
AuthenticateUserRequest: auth.AuthenticateUserRequest{
Username: c.User,
Pass: &auth.PassCreds{
Password: []byte(c.Password),
},
},
PublicKey: c.PubKey,
CompatibilityMode: c.Compatibility,
TTL: c.TTL,
})
}
func (s *sessionCache) GetCertificateWithOTP(c client.CreateSSHCertReq) (*auth.SSHLoginResponse, error) {
return s.proxyClient.AuthenticateSSHUser(auth.AuthenticateSSHRequest{
AuthenticateUserRequest: auth.AuthenticateUserRequest{
Username: c.User,
OTP: &auth.OTPCreds{
Password: []byte(c.Password),
Token: c.OTPToken,
},
},
PublicKey: c.PubKey,
CompatibilityMode: c.Compatibility,
TTL: c.TTL,
})
}
func (s *sessionCache) GetCertificateWithU2F(c client.CreateSSHCertWithU2FReq) (*auth.SSHLoginResponse, error) {
return s.proxyClient.AuthenticateSSHUser(auth.AuthenticateSSHRequest{
AuthenticateUserRequest: auth.AuthenticateUserRequest{
Username: c.User,
U2F: &auth.U2FSignResponseCreds{
SignResponse: c.U2FSignResponse,
},
},
PublicKey: c.PubKey,
CompatibilityMode: c.Compatibility,
TTL: c.TTL,
})
}
func (s *sessionCache) GetUserInviteInfo(token string) (user string, otpQRCode []byte, err error) {
return s.proxyClient.GetSignupTokenData(token)
}
func (s *sessionCache) GetUserInviteU2FRegisterRequest(token string) (*u2f.RegisterRequest, error) {
return s.proxyClient.GetSignupU2FRegisterRequest(token)
}
func (s *sessionCache) CreateNewUser(token, password, otpToken string) (services.WebSession, error) {
cap, err := s.proxyClient.GetAuthPreference()
if err != nil {
return nil, trace.Wrap(err)
}
var webSession services.WebSession
switch cap.GetSecondFactor() {
case teleport.OFF:
webSession, err = s.proxyClient.CreateUserWithoutOTP(token, password)
case teleport.OTP, teleport.TOTP, teleport.HOTP:
webSession, err = s.proxyClient.CreateUserWithOTP(token, password, otpToken)
}
if err != nil {
return nil, trace.Wrap(err)
}
return webSession, nil
}
func (s *sessionCache) CreateNewU2FUser(token string, password string, u2fRegisterResponse u2f.RegisterResponse) (services.WebSession, error) {
return s.proxyClient.CreateUserWithU2FToken(token, password, u2fRegisterResponse)
}
func (s *sessionCache) ValidateTrustedCluster(validateRequest *auth.ValidateTrustedClusterRequest) (*auth.ValidateTrustedClusterResponse, error) {
return s.proxyClient.ValidateTrustedCluster(validateRequest)
}
func (s *sessionCache) InvalidateSession(ctx *SessionContext) error {
defer ctx.Close()
if err := s.resetContext(ctx.GetUser(), ctx.GetWebSession().GetName()); err != nil {
return trace.Wrap(err)
}
clt, err := ctx.GetClient()
if err != nil {
return trace.Wrap(err)
}
err = clt.DeleteWebSession(ctx.GetUser(), ctx.GetWebSession().GetName())
return trace.Wrap(err)
}
func (s *sessionCache) getContext(user, sid string) (*SessionContext, error) {
s.Lock()
defer s.Unlock()
val, ok := s.contexts.Get(user + sid)
if ok {
return val.(*SessionContext), nil
}
return nil, trace.NotFound("sessionContext not found")
}
func (s *sessionCache) insertContext(user, sid string, ctx *SessionContext, ttl time.Duration) (*SessionContext, error) {
s.Lock()
defer s.Unlock()
val, ok := s.contexts.Get(user + sid)
if ok && val != nil { // nil means that we've just invalidated the context now and set it to nil in the cache
return val.(*SessionContext), trace.AlreadyExists("exists")
}
if err := s.contexts.Set(user+sid, ctx, ttl); err != nil {
return nil, trace.Wrap(err)
}
return ctx, nil
}
func (s *sessionCache) resetContext(user, sid string) error {
s.Lock()
defer s.Unlock()
context, ok := s.contexts.Remove(user + sid)
if ok {
closeContext(user+sid, context)
}
return nil
}
func (s *sessionCache) ValidateSession(user, sid string) (*SessionContext, error) {
ctx, err := s.getContext(user, sid)
if err == nil {
return ctx, nil
}
sess, err := s.proxyClient.AuthenticateWebUser(auth.AuthenticateUserRequest{
Username: user,
Session: &auth.SessionCreds{
ID: sid,
},
})
if err != nil {
return nil, trace.Wrap(err)
}
ca, err := s.proxyClient.GetCertAuthority(services.CertAuthID{
Type: services.HostCA,
DomainName: s.clusterName,
}, false)
if err != nil {
return nil, trace.Wrap(err)
}
certPool, err := services.CertPool(ca)
if err != nil {
return nil, trace.Wrap(err)
}
tlsConfig := utils.TLSConfig(s.cipherSuites)
tlsCert, err := tls.X509KeyPair(sess.GetTLSCert(), sess.GetPriv())
if err != nil {
return nil, trace.Wrap(err, "failed to parse TLS cert and key")
}
tlsConfig.Certificates = []tls.Certificate{tlsCert}
tlsConfig.RootCAs = certPool
tlsConfig.ServerName = auth.EncodeClusterName(s.clusterName)
userClient, err := auth.NewTLSClient(auth.ClientConfig{
Addrs: s.authServers,
TLS: tlsConfig,
})
if err != nil {
return nil, trace.Wrap(err)
}
c := &SessionContext{
clt: userClient,
remoteClt: make(map[string]auth.ClientI),
user: user,
sess: sess,
parent: s,
}
c.Entry = log.WithFields(log.Fields{
"user": user,
"sess": sess.GetShortName(),
})
ttl := utils.ToTTL(clockwork.NewRealClock(), sess.GetBearerTokenExpiryTime())
out, err := s.insertContext(user, sid, c, ttl)
if err != nil {
// this means that someone has just inserted the context, so
// close our extra context and return
if trace.IsAlreadyExists(err) {
defer c.Close()
return out, nil
}
return nil, trace.Wrap(err)
}
return out, nil
}
func (s *sessionCache) SetSession(w http.ResponseWriter, user, sid string) error {
d, err := EncodeCookie(user, sid)
if err != nil {
return err
}
c := &http.Cookie{
Name: "session",
Value: d,
Path: "/",
HttpOnly: true,
Secure: true,
}
http.SetCookie(w, c)
return nil
}
func (s *sessionCache) ClearSession(w http.ResponseWriter) {
http.SetCookie(w, &http.Cookie{
Name: "session",
Value: "",
Path: "/",
HttpOnly: true,
Secure: true,
})
}