repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/memory/memory.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L344-L374
go
train
// CompareAndSwap compares item with existing item and replaces it with replaceWith item
func (m *Memory) CompareAndSwap(ctx context.Context, expected backend.Item, replaceWith backend.Item) (*backend.Lease, error)
// CompareAndSwap compares item with existing item and replaces it with replaceWith item func (m *Memory) CompareAndSwap(ctx context.Context, expected backend.Item, replaceWith backend.Item) (*backend.Lease, error)
{ if len(expected.Key) == 0 { return nil, trace.BadParameter("missing parameter Key") } if len(replaceWith.Key) == 0 { return nil, trace.BadParameter("missing parameter Key") } if bytes.Compare(expected.Key, replaceWith.Key) != 0 { return nil, trace.BadParameter("expected and replaceWith keys should match") } m.Lock() defer m.Unlock() m.removeExpired() i := m.tree.Get(&btreeItem{Item: expected}) if i == nil { return nil, trace.CompareFailed("key %q is not found", string(expected.Key)) } existingItem := i.(*btreeItem).Item if bytes.Compare(existingItem.Value, expected.Value) != 0 { return nil, trace.CompareFailed("current value does not match expected for %v", string(expected.Key)) } event := backend.Event{ Type: backend.OpPut, Item: replaceWith, } m.processEvent(event) if !m.EventsOff { m.buf.Push(event) } return m.newLease(replaceWith), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/memory/memory.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L377-L382
go
train
// NewWatcher returns a new event watcher
func (m *Memory) NewWatcher(ctx context.Context, watch backend.Watch) (backend.Watcher, error)
// NewWatcher returns a new event watcher func (m *Memory) NewWatcher(ctx context.Context, watch backend.Watch) (backend.Watcher, error)
{ if m.EventsOff { return nil, trace.BadParameter("events are turned off for this backend") } return m.buf.NewWatcher(ctx, watch) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/memory/memory.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/memory/memory.go#L412-L432
go
train
// removeExpired makes a pass through map and removes expired elements // returns the number of expired elements removed
func (m *Memory) removeExpired() int
// removeExpired makes a pass through map and removes expired elements // returns the number of expired elements removed func (m *Memory) removeExpired() int
{ removed := 0 now := m.Clock().Now().UTC() for { if len(*m.heap) == 0 { break } item := m.heap.PeekEl() if now.Before(item.Expires) { break } m.heap.PopEl() m.tree.Delete(item) m.Debugf("Removed expired %v %v item.", string(item.Key), item.Expires) removed++ } if removed > 0 { m.Debugf("Removed %v expired items.", removed) } return removed }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L58-L65
go
train
// Set makes ID cli compatible, lets to set value from string
func (s *ID) Set(v string) error
// Set makes ID cli compatible, lets to set value from string func (s *ID) Set(v string) error
{ id, err := ParseID(v) if err != nil { return trace.Wrap(err) } *s = *id return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L68-L75
go
train
// Time returns time portion of this ID
func (s *ID) Time() time.Time
// Time returns time portion of this ID func (s *ID) Time() time.Time
{ tm, ok := s.UUID().Time() if !ok { return time.Time{} } sec, nsec := tm.UnixTime() return time.Unix(sec, nsec).UTC() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L78-L81
go
train
// Check checks if it's a valid UUID
func (s *ID) Check() error
// Check checks if it's a valid UUID func (s *ID) Check() error
{ _, err := ParseID(string(*s)) return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L84-L94
go
train
// ParseID parses ID and checks if it's correct
func ParseID(id string) (*ID, error)
// ParseID parses ID and checks if it's correct func ParseID(id string) (*ID, error)
{ val := uuid.Parse(id) if val == nil { return nil, trace.BadParameter("'%v' is not a valid Time UUID v1", id) } if ver, ok := val.Version(); !ok || ver != 1 { return nil, trace.BadParameter("'%v' is not a be a valid Time UUID v1", id) } uid := ID(id) return &uid, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L128-L136
go
train
// RemoveParty helper allows to remove a party by it's ID from the // session's list. Returns 'false' if pid couldn't be found
func (s *Session) RemoveParty(pid ID) bool
// RemoveParty helper allows to remove a party by it's ID from the // session's list. Returns 'false' if pid couldn't be found func (s *Session) RemoveParty(pid ID) bool
{ for i := range s.Parties { if s.Parties[i].ID == pid { s.Parties = append(s.Parties[:i], s.Parties[i+1:]...) return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L154-L159
go
train
// String returns debug friendly representation
func (p *Party) String() string
// String returns debug friendly representation func (p *Party) String() string
{ return fmt.Sprintf( "party(id=%v, remote=%v, user=%v, server=%v, last_active=%v)", p.ID, p.RemoteAddr, p.User, p.ServerID, p.LastActive, ) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L169-L188
go
train
// UnmarshalTerminalParams takes a serialized string that contains the // terminal parameters and returns a *TerminalParams.
func UnmarshalTerminalParams(s string) (*TerminalParams, error)
// UnmarshalTerminalParams takes a serialized string that contains the // terminal parameters and returns a *TerminalParams. func UnmarshalTerminalParams(s string) (*TerminalParams, error)
{ parts := strings.Split(s, ":") if len(parts) != 2 { return nil, trace.BadParameter("failed to unmarshal: too many parts") } w, err := strconv.Atoi(parts[0]) if err != nil { return nil, trace.Wrap(err) } h, err := strconv.Atoi(parts[1]) if err != nil { return nil, trace.Wrap(err) } return &TerminalParams{ W: w, H: h, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L194-L196
go
train
// Serialize is a more strict version of String(): it returns a string // representation of terminal size, this is used in our APIs. // Format : "W:H" // Example: "80:25"
func (p *TerminalParams) Serialize() string
// Serialize is a more strict version of String(): it returns a string // representation of terminal size, this is used in our APIs. // Format : "W:H" // Example: "80:25" func (p *TerminalParams) Serialize() string
{ return fmt.Sprintf("%d:%d", p.W, p.H) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L199-L201
go
train
// String returns debug friendly representation of terminal
func (p *TerminalParams) String() string
// String returns debug friendly representation of terminal func (p *TerminalParams) String() string
{ return fmt.Sprintf("TerminalParams(w=%v, h=%v)", p.W, p.H) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L204-L209
go
train
// Winsize returns low-level parameters for changing PTY
func (p *TerminalParams) Winsize() *term.Winsize
// Winsize returns low-level parameters for changing PTY func (p *TerminalParams) Winsize() *term.Winsize
{ return &term.Winsize{ Width: uint16(p.W), Height: uint16(p.H), } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L230-L244
go
train
// Check returns nil if request is valid, error otherwize
func (u *UpdateRequest) Check() error
// Check returns nil if request is valid, error otherwize func (u *UpdateRequest) Check() error
{ if err := u.ID.Check(); err != nil { return trace.Wrap(err) } if u.Namespace == "" { return trace.BadParameter("missing parameter Namespace") } if u.TerminalParams != nil { _, err := NewTerminalParamsFromInt(u.TerminalParams.W, u.TerminalParams.H) if err != nil { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L277-L286
go
train
// New returns new session server that uses sqlite to manage // active sessions
func New(bk backend.Backend) (Service, error)
// New returns new session server that uses sqlite to manage // active sessions func New(bk backend.Backend) (Service, error)
{ s := &server{ bk: bk, clock: clockwork.NewRealClock(), } if s.activeSessionTTL == 0 { s.activeSessionTTL = defaults.ActiveSessionTTL } return s, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L298-L316
go
train
// GetSessions returns a list of active sessions. Returns an empty slice // if no sessions are active
func (s *server) GetSessions(namespace string) ([]Session, error)
// GetSessions returns a list of active sessions. Returns an empty slice // if no sessions are active func (s *server) GetSessions(namespace string) ([]Session, error)
{ prefix := activePrefix(namespace) result, err := s.bk.GetRange(context.TODO(), prefix, backend.RangeEnd(prefix), MaxSessionSliceLength) if err != nil { return nil, trace.Wrap(err) } out := make(Sessions, 0, len(result.Items)) for i := range result.Items { var session Session if err := json.Unmarshal(result.Items[i].Value, &session); err != nil { return nil, trace.Wrap(err) } out = append(out, session) } sort.Stable(out) return out, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L323-L327
go
train
// Swap is part of sort.Interface implementation for []Session
func (slice Sessions) Swap(i, j int)
// Swap is part of sort.Interface implementation for []Session func (slice Sessions) Swap(i, j int)
{ s := slice[i] slice[i] = slice[j] slice[j] = s }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L330-L332
go
train
// Less is part of sort.Interface implementation for []Session
func (slice Sessions) Less(i, j int) bool
// Less is part of sort.Interface implementation for []Session func (slice Sessions) Less(i, j int) bool
{ return slice[i].Created.Before(slice[j].Created) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L341-L354
go
train
// GetSession returns the session by it's id. Returns NotFound if a session // is not found
func (s *server) GetSession(namespace string, id ID) (*Session, error)
// GetSession returns the session by it's id. Returns NotFound if a session // is not found func (s *server) GetSession(namespace string, id ID) (*Session, error)
{ item, err := s.bk.Get(context.TODO(), activeKey(namespace, string(id))) if err != nil { if trace.IsNotFound(err) { return nil, trace.NotFound("session(%v, %v) is not found", namespace, id) } return nil, trace.Wrap(err) } var sess Session if err := json.Unmarshal(item.Value, &sess); err != nil { return nil, trace.Wrap(err) } return &sess, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L359-L394
go
train
// CreateSession creates a new session if it does not exist, if the session // exists the function will return AlreadyExists error // The session will be marked as active for TTL period of time
func (s *server) CreateSession(sess Session) error
// CreateSession creates a new session if it does not exist, if the session // exists the function will return AlreadyExists error // The session will be marked as active for TTL period of time func (s *server) CreateSession(sess Session) error
{ if err := sess.ID.Check(); err != nil { return trace.Wrap(err) } if sess.Namespace == "" { return trace.BadParameter("session namespace can not be empty") } if sess.Login == "" { return trace.BadParameter("session login can not be empty") } if sess.Created.IsZero() { return trace.BadParameter("created can not be empty") } if sess.LastActive.IsZero() { return trace.BadParameter("last_active can not be empty") } _, err := NewTerminalParamsFromInt(sess.TerminalParams.W, sess.TerminalParams.H) if err != nil { return trace.Wrap(err) } sess.Parties = nil data, err := json.Marshal(sess) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: activeKey(sess.Namespace, string(sess.ID)), Value: data, Expires: s.clock.Now().UTC().Add(s.activeSessionTTL), } _, err = s.bk.Create(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L402-L452
go
train
// UpdateSession updates session parameters - can mark it as inactive and update it's terminal parameters
func (s *server) UpdateSession(req UpdateRequest) error
// UpdateSession updates session parameters - can mark it as inactive and update it's terminal parameters func (s *server) UpdateSession(req UpdateRequest) error
{ if err := req.Check(); err != nil { return trace.Wrap(err) } key := activeKey(req.Namespace, string(req.ID)) // Try several times, then give up for i := 0; i < sessionUpdateAttempts; i++ { item, err := s.bk.Get(context.TODO(), key) if err != nil { return trace.Wrap(err) } var session Session if err := json.Unmarshal(item.Value, &session); err != nil { return trace.Wrap(err) } if req.TerminalParams != nil { session.TerminalParams = *req.TerminalParams } if req.Active != nil { session.Active = *req.Active } if req.Parties != nil { session.Parties = *req.Parties } newValue, err := json.Marshal(session) if err != nil { return trace.Wrap(err) } newItem := backend.Item{ Key: key, Value: newValue, Expires: s.clock.Now().UTC().Add(s.activeSessionTTL), } _, err = s.bk.CompareAndSwap(context.TODO(), *item, newItem) if err != nil { if trace.IsCompareFailed(err) || trace.IsConnectionProblem(err) { s.clock.Sleep(sessionUpdateRetryPeriod) continue } return trace.Wrap(err) } else { return nil } } return trace.ConnectionProblem(nil, "failed concurrently update the session") }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L471-L473
go
train
// GetSession always returns a zero session.
func (d *discardSessionServer) GetSession(namespace string, id ID) (*Session, error)
// GetSession always returns a zero session. func (d *discardSessionServer) GetSession(namespace string, id ID) (*Session, error)
{ return &Session{}, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/session/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/session/session.go#L486-L494
go
train
// NewTerminalParamsFromUint32 returns new terminal parameters from uint32 width and height
func NewTerminalParamsFromUint32(w uint32, h uint32) (*TerminalParams, error)
// NewTerminalParamsFromUint32 returns new terminal parameters from uint32 width and height func NewTerminalParamsFromUint32(w uint32, h uint32) (*TerminalParams, error)
{ if w > maxSize || w < minSize { return nil, trace.BadParameter("bad width") } if h > maxSize || h < minSize { return nil, trace.BadParameter("bad height") } return &TerminalParams{W: int(w), H: int(h)}, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L188-L202
go
train
// isAuditedAtProxy returns true if sessions are being recorded at the proxy // and this is a Teleport node.
func (s *Server) isAuditedAtProxy() bool
// isAuditedAtProxy returns true if sessions are being recorded at the proxy // and this is a Teleport node. func (s *Server) isAuditedAtProxy() bool
{ // always be safe, better to double record than not record at all clusterConfig, err := s.GetAccessPoint().GetClusterConfig() if err != nil { return false } isRecordAtProxy := clusterConfig.GetSessionRecording() == services.RecordAtProxy isTeleportNode := s.Component() == teleport.ComponentNode if isRecordAtProxy && isTeleportNode { return true } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L208-L218
go
train
// Close closes listening socket and stops accepting connections
func (s *Server) Close() error
// Close closes listening socket and stops accepting connections func (s *Server) Close() error
{ s.cancel() s.reg.Close() if s.heartbeat != nil { if err := s.heartbeat.Close(); err != nil { s.Warningf("Failed to close heartbeat: %v", err) } s.heartbeat = nil } return s.srv.Close() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L221-L233
go
train
// Shutdown performs graceful shutdown
func (s *Server) Shutdown(ctx context.Context) error
// Shutdown performs graceful shutdown func (s *Server) Shutdown(ctx context.Context) error
{ // wait until connections drain off err := s.srv.Shutdown(ctx) s.cancel() s.reg.Close() if s.heartbeat != nil { if err := s.heartbeat.Close(); err != nil { s.Warningf("Failed to close heartbeat: %v.", err) } s.heartbeat = nil } return err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L236-L248
go
train
// Start starts server
func (s *Server) Start() error
// Start starts server func (s *Server) Start() error
{ if len(s.getCommandLabels()) > 0 { s.updateLabels() } go s.heartbeat.Run() // If the server requested connections to it arrive over a reverse tunnel, // don't call Start() which listens on a socket, return right away. if s.useTunnel { return nil } return s.srv.Start() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L251-L257
go
train
// Serve servers service on started listener
func (s *Server) Serve(l net.Listener) error
// Serve servers service on started listener func (s *Server) Serve(l net.Listener) error
{ if len(s.getCommandLabels()) > 0 { s.updateLabels() } go s.heartbeat.Run() return s.srv.Serve(l) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L266-L268
go
train
// HandleConnection is called after a connection has been accepted and starts // to perform the SSH handshake immediately.
func (s *Server) HandleConnection(conn net.Conn)
// HandleConnection is called after a connection has been accepted and starts // to perform the SSH handshake immediately. func (s *Server) HandleConnection(conn net.Conn)
{ s.srv.HandleConnection(conn) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L274-L279
go
train
// SetRotationGetter sets rotation state getter
func SetRotationGetter(getter RotationGetter) ServerOption
// SetRotationGetter sets rotation state getter func SetRotationGetter(getter RotationGetter) ServerOption
{ return func(s *Server) error { s.getRotation = getter return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L283-L288
go
train
// SetShell sets default shell that will be executed for interactive // sessions
func SetShell(shell string) ServerOption
// SetShell sets default shell that will be executed for interactive // sessions func SetShell(shell string) ServerOption
{ return func(s *Server) error { s.shell = shell return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L291-L296
go
train
// SetSessionServer represents realtime session registry server
func SetSessionServer(sessionServer rsession.Service) ServerOption
// SetSessionServer represents realtime session registry server func SetSessionServer(sessionServer rsession.Service) ServerOption
{ return func(s *Server) error { s.sessionServer = sessionServer return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L299-L308
go
train
// SetProxyMode starts this server in SSH proxying mode
func SetProxyMode(tsrv reversetunnel.Server) ServerOption
// SetProxyMode starts this server in SSH proxying mode func SetProxyMode(tsrv reversetunnel.Server) ServerOption
{ return func(s *Server) error { // always set proxy mode to true, // because in some tests reverse tunnel is disabled, // but proxy is still used without it. s.proxyMode = true s.proxyTun = tsrv return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L312-L329
go
train
// SetLabels sets dynamic and static labels that server will report to the // auth servers
func SetLabels(labels map[string]string, cmdLabels services.CommandLabels) ServerOption
// SetLabels sets dynamic and static labels that server will report to the // auth servers func SetLabels(labels map[string]string, cmdLabels services.CommandLabels) ServerOption
{ return func(s *Server) error { // make sure to clone labels to avoid // concurrent writes to the map during reloads cmdLabels = cmdLabels.Clone() for name, label := range cmdLabels { if label.GetPeriod() < time.Second { label.SetPeriod(time.Second) cmdLabels[name] = label log.Warningf("label period can't be less that 1 second. Period for label '%v' was set to 1 second", name) } } s.labels = labels s.cmdLabels = cmdLabels return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L340-L345
go
train
// SetAuditLog assigns an audit log interfaces to this server
func SetAuditLog(alog events.IAuditLog) ServerOption
// SetAuditLog assigns an audit log interfaces to this server func SetAuditLog(alog events.IAuditLog) ServerOption
{ return func(s *Server) error { s.alog = alog return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L348-L353
go
train
// SetUUID sets server unique ID
func SetUUID(uuid string) ServerOption
// SetUUID sets server unique ID func SetUUID(uuid string) ServerOption
{ return func(s *Server) error { s.uuid = uuid return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L363-L368
go
train
// SetPermitUserEnvironment allows you to set the value of permitUserEnvironment.
func SetPermitUserEnvironment(permitUserEnvironment bool) ServerOption
// SetPermitUserEnvironment allows you to set the value of permitUserEnvironment. func SetPermitUserEnvironment(permitUserEnvironment bool) ServerOption
{ return func(s *Server) error { s.permitUserEnvironment = permitUserEnvironment return nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L406-L527
go
train
// New returns an unstarted server
func New(addr utils.NetAddr, hostname string, signers []ssh.Signer, authService auth.AccessPoint, dataDir string, advertiseIP string, proxyPublicAddr utils.NetAddr, options ...ServerOption) (*Server, error)
// New returns an unstarted server func New(addr utils.NetAddr, hostname string, signers []ssh.Signer, authService auth.AccessPoint, dataDir string, advertiseIP string, proxyPublicAddr utils.NetAddr, options ...ServerOption) (*Server, error)
{ // read the host UUID: uuid, err := utils.ReadOrMakeHostUUID(dataDir) if err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(context.TODO()) s := &Server{ addr: addr, authService: authService, hostname: hostname, labelsMutex: &sync.Mutex{}, advertiseIP: advertiseIP, proxyPublicAddr: proxyPublicAddr, uuid: uuid, cancel: cancel, ctx: ctx, clock: clockwork.NewRealClock(), dataDir: dataDir, } s.limiter, err = limiter.NewLimiter(limiter.LimiterConfig{}) if err != nil { return nil, trace.Wrap(err) } for _, o := range options { if err := o(s); err != nil { return nil, trace.Wrap(err) } } // TODO(klizhentas): replace function arguments with struct if s.alog == nil { return nil, trace.BadParameter("setup valid AuditLog parameter using SetAuditLog") } if s.namespace == "" { return nil, trace.BadParameter("setup valid namespace parameter using SetNamespace") } var component string if s.proxyMode { component = teleport.ComponentProxy } else { component = teleport.ComponentNode } s.Entry = logrus.WithFields(logrus.Fields{ trace.Component: component, trace.ComponentFields: logrus.Fields{}, }) s.reg, err = srv.NewSessionRegistry(s) if err != nil { return nil, trace.Wrap(err) } // add in common auth handlers s.authHandlers = &srv.AuthHandlers{ Entry: logrus.WithFields(logrus.Fields{ trace.Component: component, trace.ComponentFields: logrus.Fields{}, }), Server: s, Component: component, AuditLog: s.alog, AccessPoint: s.authService, } // common term handlers s.termHandlers = &srv.TermHandlers{ SessionRegistry: s.reg, } server, err := sshutils.NewServer( component, addr, s, signers, sshutils.AuthMethods{PublicKey: s.authHandlers.UserKeyAuth}, sshutils.SetLimiter(s.limiter), sshutils.SetRequestHandler(s), sshutils.SetCiphers(s.ciphers), sshutils.SetKEXAlgorithms(s.kexAlgorithms), sshutils.SetMACAlgorithms(s.macAlgorithms)) if err != nil { return nil, trace.Wrap(err) } s.srv = server var heartbeatMode srv.HeartbeatMode if s.proxyMode { heartbeatMode = srv.HeartbeatModeProxy } else { heartbeatMode = srv.HeartbeatModeNode } heartbeat, err := srv.NewHeartbeat(srv.HeartbeatConfig{ Mode: heartbeatMode, Context: ctx, Component: component, Announcer: s.authService, GetServerInfo: s.getServerInfo, KeepAlivePeriod: defaults.ServerKeepAliveTTL, AnnouncePeriod: defaults.ServerAnnounceTTL/2 + utils.RandomDuration(defaults.ServerAnnounceTTL/10), ServerTTL: defaults.ServerAnnounceTTL, CheckPeriod: defaults.HeartbeatCheckPeriod, Clock: s.clock, }) if err != nil { s.srv.Close() return nil, trace.Wrap(err) } s.heartbeat = heartbeat return s, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L570-L586
go
train
// AdvertiseAddr returns an address this server should be publicly accessible // as, in "ip:host" form
func (s *Server) AdvertiseAddr() string
// AdvertiseAddr returns an address this server should be publicly accessible // as, in "ip:host" form func (s *Server) AdvertiseAddr() string
{ // set if we have explicit --advertise-ip option advertiseIP := s.getAdvertiseIP() if advertiseIP == "" { return s.addr.Addr } _, port, _ := net.SplitHostPort(s.addr.Addr) ahost, aport, err := utils.ParseAdvertiseAddr(advertiseIP) if err != nil { log.Warningf("Failed to parse advertise address %q, %v, using default value %q.", advertiseIP, err, s.addr.Addr) return s.addr.Addr } if aport == "" { aport = port } return fmt.Sprintf("%v:%v", ahost, aport) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L596-L612
go
train
// GetInfo returns a services.Server that represents this server.
func (s *Server) GetInfo() services.Server
// GetInfo returns a services.Server that represents this server. func (s *Server) GetInfo() services.Server
{ return &services.ServerV2{ Kind: services.KindNode, Version: services.V2, Metadata: services.Metadata{ Name: s.ID(), Namespace: s.getNamespace(), Labels: s.labels, }, Spec: services.ServerSpecV2{ CmdLabels: services.LabelsToV2(s.getCommandLabels()), Addr: s.AdvertiseAddr(), Hostname: s.hostname, UseTunnel: s.useTunnel, }, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L683-L728
go
train
// serveAgent will build the a sock path for this user and serve an SSH agent on unix socket.
func (s *Server) serveAgent(ctx *srv.ServerContext) error
// serveAgent will build the a sock path for this user and serve an SSH agent on unix socket. func (s *Server) serveAgent(ctx *srv.ServerContext) error
{ // gather information about user and process. this will be used to set the // socket path and permissions systemUser, err := user.Lookup(ctx.Identity.Login) if err != nil { return trace.ConvertSystemError(err) } uid, err := strconv.Atoi(systemUser.Uid) if err != nil { return trace.Wrap(err) } gid, err := strconv.Atoi(systemUser.Gid) if err != nil { return trace.Wrap(err) } pid := os.Getpid() // build the socket path and set permissions socketDir, err := ioutil.TempDir(os.TempDir(), "teleport-") if err != nil { return trace.Wrap(err) } dirCloser := &utils.RemoveDirCloser{Path: socketDir} socketPath := filepath.Join(socketDir, fmt.Sprintf("teleport-%v.socket", pid)) if err := os.Chown(socketDir, uid, gid); err != nil { if err := dirCloser.Close(); err != nil { log.Warnf("failed to remove directory: %v", err) } return trace.ConvertSystemError(err) } // start an agent on a unix socket agentServer := &teleagent.AgentServer{Agent: ctx.GetAgent()} err = agentServer.ListenUnixSocket(socketPath, uid, gid, 0600) if err != nil { return trace.Wrap(err) } ctx.SetEnv(teleport.SSHAuthSock, socketPath) ctx.SetEnv(teleport.SSHAgentPID, fmt.Sprintf("%v", pid)) ctx.AddCloser(agentServer) ctx.AddCloser(dirCloser) ctx.Debugf("Opened agent channel for Teleport user %v and socket %v.", ctx.Identity.TeleportUser, socketPath) go agentServer.Serve() return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L732-L744
go
train
// EmitAuditEvent logs a given event to the audit log attached to the // server who owns these sessions
func (s *Server) EmitAuditEvent(event events.Event, fields events.EventFields)
// EmitAuditEvent logs a given event to the audit log attached to the // server who owns these sessions func (s *Server) EmitAuditEvent(event events.Event, fields events.EventFields)
{ log.Debugf("server.EmitAuditEvent(%v)", event.Name) alog := s.alog if alog != nil { // record the event time with ms precision fields[events.EventTime] = s.clock.Now().In(time.UTC).Round(time.Millisecond) if err := alog.EmitAuditEvent(event, fields); err != nil { log.Error(trace.DebugReport(err)) } } else { log.Warn("SSH server has no audit log") } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L753-L765
go
train
// HandleRequest processes global out-of-band requests. Global out-of-band // requests are processed in order (this way the originator knows which // request we are responding to). If Teleport does not support the request // type or an error occurs while processing that request Teleport will reply // req.Reply(false, nil). // // For more details: https://tools.ietf.org/html/rfc4254.html#page-4
func (s *Server) HandleRequest(r *ssh.Request)
// HandleRequest processes global out-of-band requests. Global out-of-band // requests are processed in order (this way the originator knows which // request we are responding to). If Teleport does not support the request // type or an error occurs while processing that request Teleport will reply // req.Reply(false, nil). // // For more details: https://tools.ietf.org/html/rfc4254.html#page-4 func (s *Server) HandleRequest(r *ssh.Request)
{ switch r.Type { case teleport.KeepAliveReqType: s.handleKeepAlive(r) case teleport.RecordingProxyReqType: s.handleRecordingProxy(r) default: if r.WantReply { r.Reply(false, nil) } log.Debugf("Discarding %q global request: %+v", r.Type, r) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L768-L823
go
train
// HandleNewChan is called when new channel is opened
func (s *Server) HandleNewChan(wconn net.Conn, sconn *ssh.ServerConn, nch ssh.NewChannel)
// HandleNewChan is called when new channel is opened func (s *Server) HandleNewChan(wconn net.Conn, sconn *ssh.ServerConn, nch ssh.NewChannel)
{ identityContext, err := s.authHandlers.CreateIdentityContext(sconn) if err != nil { nch.Reject(ssh.Prohibited, fmt.Sprintf("Unable to create identity from connection: %v", err)) return } channelType := nch.ChannelType() if s.proxyMode { // Channels of type "session" handle requests that are involved in running // commands on a server. In the case of proxy mode subsystem and agent // forwarding requests occur over the "session" channel. if channelType == "session" { ch, requests, err := nch.Accept() if err != nil { log.Warnf("Unable to accept channel: %v.", err) nch.Reject(ssh.ConnectionFailed, fmt.Sprintf("unable to accept channel: %v", err)) return } go s.handleSessionRequests(wconn, sconn, identityContext, ch, requests) } else { nch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %v", channelType)) } return } switch channelType { // Channels of type "session" handle requests that are involved in running // commands on a server, subsystem requests, and agent forwarding. case "session": ch, requests, err := nch.Accept() if err != nil { log.Warnf("Unable to accept channel: %v.", err) nch.Reject(ssh.ConnectionFailed, fmt.Sprintf("unable to accept channel: %v", err)) return } go s.handleSessionRequests(wconn, sconn, identityContext, ch, requests) // Channels of type "direct-tcpip" handles request for port forwarding. case "direct-tcpip": req, err := sshutils.ParseDirectTCPIPReq(nch.ExtraData()) if err != nil { log.Errorf("Failed to parse request data: %v, err: %v.", string(nch.ExtraData()), err) nch.Reject(ssh.UnknownChannelType, "failed to parse direct-tcpip request") return } ch, _, err := nch.Accept() if err != nil { log.Warnf("Unable to accept channel: %v.", err) nch.Reject(ssh.ConnectionFailed, fmt.Sprintf("unable to accept channel: %v", err)) return } go s.handleDirectTCPIPRequest(wconn, sconn, identityContext, ch, req) default: nch.Reject(ssh.UnknownChannelType, fmt.Sprintf("unknown channel type: %v", channelType)) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L826-L914
go
train
// handleDirectTCPIPRequest handles port forwarding requests.
func (s *Server) handleDirectTCPIPRequest(wconn net.Conn, sconn *ssh.ServerConn, identityContext srv.IdentityContext, ch ssh.Channel, req *sshutils.DirectTCPIPReq)
// handleDirectTCPIPRequest handles port forwarding requests. func (s *Server) handleDirectTCPIPRequest(wconn net.Conn, sconn *ssh.ServerConn, identityContext srv.IdentityContext, ch ssh.Channel, req *sshutils.DirectTCPIPReq)
{ // Create context for this channel. This context will be closed when // forwarding is complete. ctx, err := srv.NewServerContext(s, sconn, identityContext) if err != nil { ctx.Errorf("Unable to create connection context: %v.", err) ch.Stderr().Write([]byte("Unable to create connection context.")) return } ctx.Connection = wconn ctx.IsTestStub = s.isTestStub ctx.AddCloser(ch) defer ctx.Debugf("direct-tcp closed") defer ctx.Close() srcAddr := net.JoinHostPort(req.Orig, strconv.Itoa(int(req.OrigPort))) dstAddr := net.JoinHostPort(req.Host, strconv.Itoa(int(req.Port))) // check if the role allows port forwarding for this user err = s.authHandlers.CheckPortForward(dstAddr, ctx) if err != nil { ch.Stderr().Write([]byte(err.Error())) return } ctx.Debugf("Opening direct-tcpip channel from %v to %v", srcAddr, dstAddr) // If PAM is enabled check the account and open a session. var pamContext *pam.PAM if s.pamConfig.Enabled { // Note, stdout/stderr is discarded here, otherwise MOTD would be printed to // the users screen during port forwarding. pamContext, err = pam.Open(&pam.Config{ ServiceName: s.pamConfig.ServiceName, Username: ctx.Identity.Login, Stdin: ch, Stderr: ioutil.Discard, Stdout: ioutil.Discard, }) if err != nil { ctx.Errorf("Unable to open PAM context for direct-tcpip request: %v.", err) ch.Stderr().Write([]byte(err.Error())) return } ctx.Debugf("Opening PAM context for direct-tcpip request.") } conn, err := net.Dial("tcp", dstAddr) if err != nil { ctx.Infof("Failed to connect to: %v: %v", dstAddr, err) return } defer conn.Close() // audit event: s.EmitAuditEvent(events.PortForward, events.EventFields{ events.PortForwardAddr: dstAddr, events.PortForwardSuccess: true, events.EventLogin: ctx.Identity.Login, events.EventUser: ctx.Identity.TeleportUser, events.LocalAddr: sconn.LocalAddr().String(), events.RemoteAddr: sconn.RemoteAddr().String(), }) wg := &sync.WaitGroup{} wg.Add(1) go func() { defer wg.Done() io.Copy(ch, conn) ch.Close() }() wg.Add(1) go func() { defer wg.Done() io.Copy(conn, srv.NewTrackingReader(ctx, ch)) conn.Close() }() wg.Wait() // If PAM is enabled, close the PAM context after port forwarding is complete. if s.pamConfig.Enabled { err = pamContext.Close() if err != nil { ctx.Errorf("Unable to close PAM context for direct-tcpip request: %v.", err) return } ctx.Debugf("Closing PAM context for direct-tcpip request.") } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L919-L1010
go
train
// handleSessionRequests handles out of band session requests once the session // channel has been created this function's loop handles all the "exec", // "subsystem" and "shell" requests.
func (s *Server) handleSessionRequests(conn net.Conn, sconn *ssh.ServerConn, identityContext srv.IdentityContext, ch ssh.Channel, in <-chan *ssh.Request)
// handleSessionRequests handles out of band session requests once the session // channel has been created this function's loop handles all the "exec", // "subsystem" and "shell" requests. func (s *Server) handleSessionRequests(conn net.Conn, sconn *ssh.ServerConn, identityContext srv.IdentityContext, ch ssh.Channel, in <-chan *ssh.Request)
{ // Create context for this channel. This context will be closed when the // session request is complete. ctx, err := srv.NewServerContext(s, sconn, identityContext) if err != nil { log.Errorf("Unable to create connection context: %v.", err) ch.Stderr().Write([]byte("Unable to create connection context.")) return } ctx.Connection = conn ctx.IsTestStub = s.isTestStub ctx.AddCloser(ch) defer ctx.Close() // Create a close context used to signal between the server and the // keep-alive loop when to close the connection (from either side). closeContext, closeCancel := context.WithCancel(context.Background()) defer closeCancel() clusterConfig, err := s.GetAccessPoint().GetClusterConfig() if err != nil { log.Errorf("Unable to fetch cluster config: %v.", err) ch.Stderr().Write([]byte("Unable to fetch cluster configuration.")) return } // The keep-alive loop will keep pinging the remote server and after it has // missed a certain number of keep-alive requests it will cancel the // closeContext which signals the server to shutdown. go srv.StartKeepAliveLoop(srv.KeepAliveParams{ Conns: []srv.RequestSender{ sconn, }, Interval: clusterConfig.GetKeepAliveInterval(), MaxCount: clusterConfig.GetKeepAliveCountMax(), CloseContext: closeContext, CloseCancel: closeCancel, }) for { // update ctx with the session ID: if !s.proxyMode { err := ctx.CreateOrJoinSession(s.reg) if err != nil { errorMessage := fmt.Sprintf("unable to update context: %v", err) ctx.Errorf("Unable to update context: %v.", errorMessage) // write the error to channel and close it ch.Stderr().Write([]byte(errorMessage)) _, err := ch.SendRequest("exit-status", false, ssh.Marshal(struct{ C uint32 }{C: teleport.RemoteCommandFailure})) if err != nil { ctx.Errorf("Failed to send exit status %v.", errorMessage) } return } } select { case creq := <-ctx.SubsystemResultCh: // this means that subsystem has finished executing and // want us to close session and the channel ctx.Debugf("Close session request: %v.", creq.Err) return case req := <-in: if req == nil { // this will happen when the client closes/drops the connection ctx.Debugf("Client %v disconnected.", sconn.RemoteAddr()) return } if err := s.dispatch(ch, req, ctx); err != nil { s.replyError(ch, req, err) return } if req.WantReply { req.Reply(true, nil) } case result := <-ctx.ExecResultCh: ctx.Debugf("Exec request (%q) complete: %v", result.Command, result.Code) // The exec process has finished and delivered the execution result, send // the result back to the client, and close the session and channel. _, err := ch.SendRequest("exit-status", false, ssh.Marshal(struct{ C uint32 }{C: uint32(result.Code)})) if err != nil { ctx.Infof("Failed to send exit status for %v: %v", result.Command, err) } return case <-closeContext.Done(): log.Debugf("Closing session due to missed heartbeat.") return } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L1079-L1102
go
train
// handleAgentForwardNode will create a unix socket and serve the agent running // on the client on it.
func (s *Server) handleAgentForwardNode(req *ssh.Request, ctx *srv.ServerContext) error
// handleAgentForwardNode will create a unix socket and serve the agent running // on the client on it. func (s *Server) handleAgentForwardNode(req *ssh.Request, ctx *srv.ServerContext) error
{ // check if the user's RBAC role allows agent forwarding err := s.authHandlers.CheckAgentForward(ctx) if err != nil { return trace.Wrap(err) } // open a channel to the client where the client will serve an agent authChannel, _, err := ctx.Conn.OpenChannel(sshutils.AuthAgentRequest, nil) if err != nil { return trace.Wrap(err) } // save the agent in the context so it can be used later ctx.SetAgent(agent.NewClient(authChannel), authChannel) // serve an agent on a unix socket on this node err = s.serveAgent(ctx) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L1109-L1134
go
train
// handleAgentForwardProxy will forward the clients agent to the proxy (when // the proxy is running in recording mode). When running in normal mode, this // request will do nothing. To maintain interoperability, agent forwarding // requests should never fail, all errors should be logged and we should // continue processing requests.
func (s *Server) handleAgentForwardProxy(req *ssh.Request, ctx *srv.ServerContext) error
// handleAgentForwardProxy will forward the clients agent to the proxy (when // the proxy is running in recording mode). When running in normal mode, this // request will do nothing. To maintain interoperability, agent forwarding // requests should never fail, all errors should be logged and we should // continue processing requests. func (s *Server) handleAgentForwardProxy(req *ssh.Request, ctx *srv.ServerContext) error
{ // Forwarding an agent to the proxy is only supported when the proxy is in // recording mode. if ctx.ClusterConfig.GetSessionRecording() != services.RecordAtProxy { return trace.BadParameter("agent forwarding to proxy only supported in recording mode") } // Check if the user's RBAC role allows agent forwarding. err := s.authHandlers.CheckAgentForward(ctx) if err != nil { return trace.Wrap(err) } // Open a channel to the client where the client will serve an agent. authChannel, _, err := ctx.Conn.OpenChannel(sshutils.AuthAgentRequest, nil) if err != nil { return trace.Wrap(err) } // Save the agent so it can be used when making a proxy subsystem request // later. It will also be used when building a remote connection to the // target node. ctx.SetAgent(agent.NewClient(authChannel), authChannel) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L1171-L1184
go
train
// handleKeepAlive accepts and replies to keepalive@openssh.com requests.
func (s *Server) handleKeepAlive(req *ssh.Request)
// handleKeepAlive accepts and replies to keepalive@openssh.com requests. func (s *Server) handleKeepAlive(req *ssh.Request)
{ log.Debugf("Received %q: WantReply: %v", req.Type, req.WantReply) // only reply if the sender actually wants a response if req.WantReply { err := req.Reply(true, nil) if err != nil { log.Warnf("Unable to reply to %q request: %v", req.Type, err) return } } log.Debugf("Replied to %q", req.Type) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sshserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sshserver.go#L1188-L1215
go
train
// handleRecordingProxy responds to global out-of-band with a bool which // indicates if it is in recording mode or not.
func (s *Server) handleRecordingProxy(req *ssh.Request)
// handleRecordingProxy responds to global out-of-band with a bool which // indicates if it is in recording mode or not. func (s *Server) handleRecordingProxy(req *ssh.Request)
{ var recordingProxy bool log.Debugf("Global request (%v, %v) received", req.Type, req.WantReply) if req.WantReply { // get the cluster config, if we can't get it, reply false clusterConfig, err := s.authService.GetClusterConfig() if err != nil { err := req.Reply(false, nil) if err != nil { log.Warnf("Unable to respond to global request (%v, %v): %v", req.Type, req.WantReply, err) } return } // reply true that we were able to process the message and reply with a // bool if we are in recording mode or not recordingProxy = clusterConfig.GetSessionRecording() == services.RecordAtProxy err = req.Reply(true, []byte(strconv.FormatBool(recordingProxy))) if err != nil { log.Warnf("Unable to respond to global request (%v, %v): %v: %v", req.Type, req.WantReply, recordingProxy, err) return } } log.Debugf("Replied to global request (%v, %v): %v", req.Type, req.WantReply, recordingProxy) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/wrappers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/wrappers.go#L34-L36
go
train
// MarshalTo marshals value to the array
func (l Traits) MarshalTo(data []byte) (int, error)
// MarshalTo marshals value to the array func (l Traits) MarshalTo(data []byte) (int, error)
{ return l.protoType().MarshalTo(data) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/wrappers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/wrappers.go#L39-L53
go
train
// Unmarshal unmarshals value from protobuf
func (l *Traits) Unmarshal(data []byte) error
// Unmarshal unmarshals value from protobuf func (l *Traits) Unmarshal(data []byte) error
{ protoValues := &LabelValues{} err := proto.Unmarshal(data, protoValues) if err != nil { return err } if protoValues.Values == nil { return nil } *l = make(map[string][]string, len(protoValues.Values)) for key := range protoValues.Values { (*l)[key] = protoValues.Values[key].Values } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/wrappers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/wrappers.go#L76-L78
go
train
// MarshalTo marshals value to the array
func (s Strings) MarshalTo(data []byte) (int, error)
// MarshalTo marshals value to the array func (s Strings) MarshalTo(data []byte) (int, error)
{ return s.protoType().MarshalTo(data) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/wrappers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/wrappers.go#L81-L91
go
train
// Unmarshal unmarshals value from protobuf
func (s *Strings) Unmarshal(data []byte) error
// Unmarshal unmarshals value from protobuf func (s *Strings) Unmarshal(data []byte) error
{ protoValues := &StringValues{} err := proto.Unmarshal(data, protoValues) if err != nil { return err } if protoValues.Values != nil { *s = protoValues.Values } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/wrappers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/wrappers.go#L99-L114
go
train
// UnmarshalJSON unmarshals scalar string or strings slice to Strings
func (s *Strings) UnmarshalJSON(data []byte) error
// UnmarshalJSON unmarshals scalar string or strings slice to Strings func (s *Strings) UnmarshalJSON(data []byte) error
{ if len(data) == 0 { return nil } var stringVar string if err := json.Unmarshal(data, &stringVar); err == nil { *s = []string{stringVar} return nil } var stringsVar []string if err := json.Unmarshal(data, &stringsVar); err != nil { return trace.Wrap(err) } *s = stringsVar return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/wrappers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/wrappers.go#L118-L136
go
train
// UnmarshalYAML is used to allow Strings to unmarshal from // scalar string value or from the list
func (s *Strings) UnmarshalYAML(unmarshal func(interface{}) error) error
// UnmarshalYAML is used to allow Strings to unmarshal from // scalar string value or from the list func (s *Strings) UnmarshalYAML(unmarshal func(interface{}) error) error
{ // try unmarshal as string var val string err := unmarshal(&val) if err == nil { *s = []string{val} return nil } // try unmarshal as slice var slice []string err = unmarshal(&slice) if err == nil { *s = slice return nil } return err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/wrappers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/wrappers.go#L141-L146
go
train
// MarshalJSON marshals to scalar value // if there is only one value in the list // to list otherwise
func (s Strings) MarshalJSON() ([]byte, error)
// MarshalJSON marshals to scalar value // if there is only one value in the list // to list otherwise func (s Strings) MarshalJSON() ([]byte, error)
{ if len(s) == 1 { return json.Marshal(s[0]) } return json.Marshal([]string(s)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/wrappers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/wrappers.go#L151-L156
go
train
// MarshalYAML marshals to scalar value // if there is only one value in the list, // marshals to list otherwise
func (s Strings) MarshalYAML() (interface{}, error)
// MarshalYAML marshals to scalar value // if there is only one value in the list, // marshals to list otherwise func (s Strings) MarshalYAML() (interface{}, error)
{ if len(s) == 1 { return s[0], nil } return []string(s), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L50-L52
go
train
// NewTracer returns a new tracer
func NewTracer(description string) *Tracer
// NewTracer returns a new tracer func NewTracer(description string) *Tracer
{ return &Tracer{Started: time.Now().UTC(), Description: description} }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L61-L64
go
train
// Stop logs stop of the trace
func (t *Tracer) Stop() *Tracer
// Stop logs stop of the trace func (t *Tracer) Stop() *Tracer
{ log.Debugf("Tracer completed %v in %v.", t.Description, time.Now().Sub(t.Started)) return t }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L67-L71
go
train
// ThisFunction returns calling function name
func ThisFunction() string
// ThisFunction returns calling function name func ThisFunction() string
{ var pc [32]uintptr runtime.Callers(2, pc[:]) return runtime.FuncForPC(pc[0]).Name() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L81-L85
go
train
// Value returns value of the string
func (s *SyncString) Value() string
// Value returns value of the string func (s *SyncString) Value() string
{ s.Lock() defer s.Unlock() return s.string }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L88-L92
go
train
// Set sets the value of the string
func (s *SyncString) Set(v string)
// Set sets the value of the string func (s *SyncString) Set(v string)
{ s.Lock() defer s.Unlock() s.string = v }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L97-L114
go
train
// ClickableURL fixes address in url to make sure // it's clickable, e.g. it replaces "undefined" address like // 0.0.0.0 used in network listeners format with loopback 127.0.0.1
func ClickableURL(in string) string
// ClickableURL fixes address in url to make sure // it's clickable, e.g. it replaces "undefined" address like // 0.0.0.0 used in network listeners format with loopback 127.0.0.1 func ClickableURL(in string) string
{ out, err := url.Parse(in) if err != nil { return in } host, port, err := net.SplitHostPort(out.Host) if err != nil { return in } ip := net.ParseIP(host) // if address is not an IP, unspecified, e.g. all interfaces 0.0.0.0 or multicast, // replace with localhost that is clickable if len(ip) == 0 || ip.IsUnspecified() || ip.IsMulticast() { out.Host = fmt.Sprintf("127.0.0.1:%v", port) return out.String() } return out.String() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L118-L124
go
train
// AsBool converts string to bool, in case of the value is empty // or unknown, defaults to false
func AsBool(v string) bool
// AsBool converts string to bool, in case of the value is empty // or unknown, defaults to false func AsBool(v string) bool
{ if v == "" { return false } out, _ := ParseBool(v) return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L128-L137
go
train
// ParseBool parses string as boolean value, // returns error in case if value is not recognized
func ParseBool(value string) (bool, error)
// ParseBool parses string as boolean value, // returns error in case if value is not recognized func ParseBool(value string) (bool, error)
{ switch strings.ToLower(value) { case "yes", "yeah", "y", "true", "1", "on": return true, nil case "no", "nope", "n", "false", "0", "off": return false, nil default: return false, trace.BadParameter("unsupported value: %q", value) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L143-L167
go
train
// ParseAdvertiseAddr validates advertise address, // makes sure it's not an unreachable or multicast address // returns address split into host and port, port could be empty // if not specified
func ParseAdvertiseAddr(advertiseIP string) (string, string, error)
// ParseAdvertiseAddr validates advertise address, // makes sure it's not an unreachable or multicast address // returns address split into host and port, port could be empty // if not specified func ParseAdvertiseAddr(advertiseIP string) (string, string, error)
{ advertiseIP = strings.TrimSpace(advertiseIP) host := advertiseIP port := "" if len(net.ParseIP(host)) == 0 && strings.Contains(advertiseIP, ":") { var err error host, port, err = net.SplitHostPort(advertiseIP) if err != nil { return "", "", trace.BadParameter("failed to parse address %q", advertiseIP) } if _, err := strconv.Atoi(port); err != nil { return "", "", trace.BadParameter("bad port %q, expected integer", port) } if host == "" { return "", "", trace.BadParameter("missing host parameter") } } ip := net.ParseIP(host) if len(ip) != 0 { if ip.IsUnspecified() || ip.IsMulticast() { return "", "", trace.BadParameter("unreachable advertise IP: %v", advertiseIP) } } return host, port, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L171-L180
go
train
// StringsSet creates set of string (map[string]struct{}) // from a list of strings
func StringsSet(in []string) map[string]struct{}
// StringsSet creates set of string (map[string]struct{}) // from a list of strings func StringsSet(in []string) map[string]struct{}
{ if in == nil { return nil } out := make(map[string]struct{}) for _, v := range in { out[v] = struct{}{} } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L184-L195
go
train
// ParseOnOff parses whether value is "on" or "off", parameterName is passed for error // reporting purposes, defaultValue is returned when no value is set
func ParseOnOff(parameterName, val string, defaultValue bool) (bool, error)
// ParseOnOff parses whether value is "on" or "off", parameterName is passed for error // reporting purposes, defaultValue is returned when no value is set func ParseOnOff(parameterName, val string, defaultValue bool) (bool, error)
{ switch val { case teleport.On: return true, nil case teleport.Off: return false, nil case "": return defaultValue, nil default: return false, trace.BadParameter("bad %q parameter value: %q, supported values are on or off", parameterName, val) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L198-L209
go
train
// IsGroupMember returns whether currently logged user is a member of a group
func IsGroupMember(gid int) (bool, error)
// IsGroupMember returns whether currently logged user is a member of a group func IsGroupMember(gid int) (bool, error)
{ groups, err := os.Getgroups() if err != nil { return false, trace.ConvertSystemError(err) } for _, group := range groups { if group == gid { return true, nil } } return false, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L212-L221
go
train
// Host extracts host from host:port string
func Host(hostname string) (string, error)
// Host extracts host from host:port string func Host(hostname string) (string, error)
{ if hostname == "" { return "", trace.BadParameter("missing parameter hostname") } if !strings.Contains(hostname, ":") { return hostname, nil } host, _, err := SplitHostPort(hostname) return host, err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L224-L233
go
train
// SplitHostPort splits host and port and checks that host is not empty
func SplitHostPort(hostname string) (string, string, error)
// SplitHostPort splits host and port and checks that host is not empty func SplitHostPort(hostname string) (string, string, error)
{ host, port, err := net.SplitHostPort(hostname) if err != nil { return "", "", trace.Wrap(err) } if host == "" { return "", "", trace.BadParameter("empty hostname") } return host, port, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L236-L253
go
train
// ReadPath reads file contents
func ReadPath(path string) ([]byte, error)
// ReadPath reads file contents func ReadPath(path string) ([]byte, error)
{ if path == "" { return nil, trace.NotFound("empty path") } s, err := filepath.Abs(path) if err != nil { return nil, trace.ConvertSystemError(err) } abs, err := filepath.EvalSymlinks(s) if err != nil { return nil, trace.ConvertSystemError(err) } bytes, err := ioutil.ReadFile(abs) if err != nil { return nil, trace.ConvertSystemError(err) } return bytes, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L277-L282
go
train
// IsHandshakeFailedError specifies whether this error indicates // failed handshake
func IsHandshakeFailedError(err error) bool
// IsHandshakeFailedError specifies whether this error indicates // failed handshake func IsHandshakeFailedError(err error) bool
{ if err == nil { return false } return strings.Contains(trace.Unwrap(err).Error(), "ssh: handshake failed") }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L303-L310
go
train
// Pop returns a value from the list, it panics if the value is not there
func (p *PortList) Pop() string
// Pop returns a value from the list, it panics if the value is not there func (p *PortList) Pop() string
{ if len(*p) == 0 { panic("list is empty") } val := (*p)[len(*p)-1] *p = (*p)[:len(*p)-1] return val }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L314-L320
go
train
// PopInt returns a value from the list, it panics if not enough values // were allocated
func (p *PortList) PopInt() int
// PopInt returns a value from the list, it panics if not enough values // were allocated func (p *PortList) PopInt() int
{ i, err := strconv.Atoi(p.Pop()) if err != nil { panic(err) } return i }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L324-L330
go
train
// PopIntSlice returns a slice of values from the list, it panics if not enough // ports were allocated
func (p *PortList) PopIntSlice(num int) []int
// PopIntSlice returns a slice of values from the list, it panics if not enough // ports were allocated func (p *PortList) PopIntSlice(num int) []int
{ ports := make([]int, num) for i := range ports { ports[i] = p.PopInt() } return ports }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L336-L346
go
train
// GetFreeTCPPorts returns n ports starting from port 20000.
func GetFreeTCPPorts(n int, offset ...int) (PortList, error)
// GetFreeTCPPorts returns n ports starting from port 20000. func GetFreeTCPPorts(n int, offset ...int) (PortList, error)
{ list := make(PortList, 0, n) start := PortStartingNumber if len(offset) != 0 { start = offset[0] } for i := start; i < start+n; i++ { list = append(list, strconv.Itoa(i)) } return list, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L349-L355
go
train
// ReadHostUUID reads host UUID from the file in the data dir
func ReadHostUUID(dataDir string) (string, error)
// ReadHostUUID reads host UUID from the file in the data dir func ReadHostUUID(dataDir string) (string, error)
{ out, err := ReadPath(filepath.Join(dataDir, HostUUIDFile)) if err != nil { return "", trace.Wrap(err) } return strings.TrimSpace(string(out)), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L358-L364
go
train
// WriteHostUUID writes host UUID into a file
func WriteHostUUID(dataDir string, id string) error
// WriteHostUUID writes host UUID into a file func WriteHostUUID(dataDir string, id string) error
{ err := ioutil.WriteFile(filepath.Join(dataDir, HostUUIDFile), []byte(id), os.ModeExclusive|0400) if err != nil { return trace.ConvertSystemError(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L368-L381
go
train
// ReadOrMakeHostUUID looks for a hostid file in the data dir. If present, // returns the UUID from it, otherwise generates one
func ReadOrMakeHostUUID(dataDir string) (string, error)
// ReadOrMakeHostUUID looks for a hostid file in the data dir. If present, // returns the UUID from it, otherwise generates one func ReadOrMakeHostUUID(dataDir string) (string, error)
{ id, err := ReadHostUUID(dataDir) if err == nil { return id, nil } if !trace.IsNotFound(err) { return "", trace.Wrap(err) } id = uuid.New() if err = WriteHostUUID(dataDir, id); err != nil { return "", trace.Wrap(err) } return id, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L394-L407
go
train
// Deduplicate deduplicates list of strings
func Deduplicate(in []string) []string
// Deduplicate deduplicates list of strings func Deduplicate(in []string) []string
{ if len(in) == 0 { return in } out := make([]string, 0, len(in)) seen := make(map[string]bool, len(in)) for _, val := range in { if _, ok := seen[val]; !ok { out = append(out, val) seen[val] = true } } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L410-L417
go
train
// SliceContainsStr returns 'true' if the slice contains the given value
func SliceContainsStr(slice []string, value string) bool
// SliceContainsStr returns 'true' if the slice contains the given value func SliceContainsStr(slice []string, value string) bool
{ for i := range slice { if slice[i] == value { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L420-L437
go
train
// RemoveFromSlice makes a copy of the slice and removes the passed in values from the copy.
func RemoveFromSlice(slice []string, values ...string) []string
// RemoveFromSlice makes a copy of the slice and removes the passed in values from the copy. func RemoveFromSlice(slice []string, values ...string) []string
{ output := make([]string, 0, len(slice)) remove := make(map[string]bool) for _, value := range values { remove[value] = true } for _, s := range slice { _, ok := remove[s] if ok { continue } output = append(output, s) } return output }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L440-L447
go
train
// CheckCertificateFormatFlag checks if the certificate format is valid.
func CheckCertificateFormatFlag(s string) (string, error)
// CheckCertificateFormatFlag checks if the certificate format is valid. func CheckCertificateFormatFlag(s string) (string, error)
{ switch s { case teleport.CertificateFormatStandard, teleport.CertificateFormatOldSSH, teleport.CertificateFormatUnspecified: return s, nil default: return "", trace.BadParameter("invalid certificate format parameter: %q", s) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/utils.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/utils.go#L514-L524
go
train
// Addrs returns strings list converted to address list
func (s Strings) Addrs(defaultPort int) ([]NetAddr, error)
// Addrs returns strings list converted to address list func (s Strings) Addrs(defaultPort int) ([]NetAddr, error)
{ addrs := make([]NetAddr, len(s)) for i, val := range s { addr, err := ParseHostPortAddr(val, defaultPort) if err != nil { return nil, trace.Wrap(err) } addrs[i] = *addr } return addrs, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/tctl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/tctl.go#L63-L125
go
train
// Run() is the same as 'make'. It helps to share the code between different // "distributions" like OSS or Enterprise // // distribution: name of the Teleport distribution
func Run(commands []CLICommand)
// Run() is the same as 'make'. It helps to share the code between different // "distributions" like OSS or Enterprise // // distribution: name of the Teleport distribution func Run(commands []CLICommand)
{ utils.InitLogger(utils.LoggingForCLI, logrus.WarnLevel) // app is the command line parser app := utils.InitCLIParser("tctl", GlobalHelpString) // cfg (teleport auth server configuration) is going to be shared by all // commands cfg := service.MakeDefaultConfig() // each command will add itself to the CLI parser: for i := range commands { commands[i].Initialize(app, cfg) } // these global flags apply to all commands var ccf GlobalCLIFlags app.Flag("debug", "Enable verbose logging to stderr"). Short('d'). BoolVar(&ccf.Debug) app.Flag("config", fmt.Sprintf("Path to a configuration file [%v]", defaults.ConfigFilePath)). Short('c'). ExistingFileVar(&ccf.ConfigFile) app.Flag("config-string", "Base64 encoded configuration string").Hidden().Envar(defaults.ConfigEnvar).StringVar(&ccf.ConfigString) // "version" command is always available: ver := app.Command("version", "Print cluster version") app.HelpFlag.Short('h') // parse CLI commands+flags: selectedCmd, err := app.Parse(os.Args[1:]) if err != nil { utils.FatalError(err) } // "version" command? if selectedCmd == ver.FullCommand() { utils.PrintVersion() return } // configure all commands with Teleport configuration (they share 'cfg') applyConfig(&ccf, cfg) // connect to the auth sever: client, err := connectToAuthService(cfg) if err != nil { utils.FatalError(err) } // execute whatever is selected: var match bool for _, c := range commands { match, err = c.TryRun(selectedCmd, client) if err != nil { utils.FatalError(err) } if match { break } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/tctl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/tctl.go#L128-L163
go
train
// connectToAuthService creates a valid client connection to the auth service
func connectToAuthService(cfg *service.Config) (client auth.ClientI, err error)
// connectToAuthService creates a valid client connection to the auth service func connectToAuthService(cfg *service.Config) (client auth.ClientI, err error)
{ // connect to the local auth server by default: cfg.Auth.Enabled = true if len(cfg.AuthServers) == 0 { cfg.AuthServers = []utils.NetAddr{ *defaults.AuthConnectAddr(), } } // read the host SSH keys and use them to open an SSH connection to the auth service i, err := auth.ReadLocalIdentity(filepath.Join(cfg.DataDir, teleport.ComponentProcess), auth.IdentityID{Role: teleport.RoleAdmin, HostUUID: cfg.HostUUID}) if err != nil { // the "admin" identity is not present? this means the tctl is running NOT on the auth server. if trace.IsNotFound(err) { return nil, trace.AccessDenied("tctl must be used on the auth server") } return nil, trace.Wrap(err) } tlsConfig, err := i.TLSConfig(cfg.CipherSuites) if err != nil { return nil, trace.Wrap(err) } client, err = auth.NewTLSClient(auth.ClientConfig{Addrs: cfg.AuthServers, TLS: tlsConfig}) if err != nil { return nil, trace.Wrap(err) } // Check connectivity by calling something on the client. _, err = client.GetClusterName() if err != nil { utils.Consolef(os.Stderr, teleport.ComponentClient, "Cannot connect to the auth server: %v.\nIs the auth server running on %v?", err, cfg.AuthServers[0].Addr) os.Exit(1) } return client, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/tctl.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/tctl.go#L167-L197
go
train
// applyConfig takes configuration values from the config file and applies // them to 'service.Config' object
func applyConfig(ccf *GlobalCLIFlags, cfg *service.Config) error
// applyConfig takes configuration values from the config file and applies // them to 'service.Config' object func applyConfig(ccf *GlobalCLIFlags, cfg *service.Config) error
{ // load /etc/teleport.yaml and apply it's values: fileConf, err := config.ReadConfigFile(ccf.ConfigFile) if err != nil { return trace.Wrap(err) } // if configuration is passed as an environment variable, // try to decode it and override the config file if ccf.ConfigString != "" { fileConf, err = config.ReadFromString(ccf.ConfigString) if err != nil { return trace.Wrap(err) } } if err = config.ApplyFileConfig(fileConf, cfg); err != nil { return trace.Wrap(err) } // --debug flag if ccf.Debug { cfg.Debug = ccf.Debug utils.InitLogger(utils.LoggingForCLI, logrus.DebugLevel) logrus.Debugf("DEBUG logging enabled") } // read a host UUID for this node cfg.HostUUID, err = utils.ReadHostUUID(cfg.DataDir) if err != nil { utils.FatalError(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/limiter/limiter.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/limiter/limiter.go#L49-L54
go
train
// SetEnv reads LimiterConfig from JSON string
func (l *LimiterConfig) SetEnv(v string) error
// SetEnv reads LimiterConfig from JSON string func (l *LimiterConfig) SetEnv(v string) error
{ if err := json.Unmarshal([]byte(v), l); err != nil { return trace.Wrap(err, "expected JSON encoded remote certificate") } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/limiter/limiter.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/limiter/limiter.go#L57-L72
go
train
// NewLimiter returns new rate and connection limiter
func NewLimiter(config LimiterConfig) (*Limiter, error)
// NewLimiter returns new rate and connection limiter func NewLimiter(config LimiterConfig) (*Limiter, error)
{ var err error limiter := Limiter{} limiter.ConnectionsLimiter, err = NewConnectionsLimiter(config) if err != nil { return nil, trace.Wrap(err) } limiter.rateLimiter, err = NewRateLimiter(config) if err != nil { return nil, trace.Wrap(err) } return &limiter, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/limiter/limiter.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/limiter/limiter.go#L79-L82
go
train
// Add limiter to the handle
func (l *Limiter) WrapHandle(h http.Handler)
// Add limiter to the handle func (l *Limiter) WrapHandle(h http.Handler)
{ l.rateLimiter.Wrap(h) l.ConnLimiter.Wrap(l.rateLimiter) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/apiserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L79-L87
go
train
// SetSessionStreamPollPeriod sets polling period for session streams
func SetSessionStreamPollPeriod(period time.Duration) HandlerOption
// 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 } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/apiserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L128-L331
go
train
// NewHandler returns a new instance of web proxy handler
func NewHandler(cfg Config, opts ...HandlerOption) (*RewritingHandler, error)
// NewHandler returns a new instance of web proxy handler func NewHandler(cfg Config, opts ...HandlerOption) (*RewritingHandler, error)
{ const apiPrefix = "/" + teleport.WebAPIVersion lauth, err := newSessionCache(cfg.ProxyClient, []utils.NetAddr{cfg.AuthServers}, cfg.CipherSuites) 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.clock == nil { h.clock = clockwork.NewRealClock() } // ping endpoint is used to check if the server is up. the /webapi/ping // endpoint returns the default authentication method and configuration that // the server supports. the /webapi/ping/:connector endpoint can be used to // query the authentication configuration for a specific connector. h.GET("/webapi/ping", httplib.MakeHandler(h.ping)) h.GET("/webapi/ping/:connector", httplib.MakeHandler(h.pingWithConnector)) // find is like ping, but is faster because it is optimized for servers // and does not fetch the data that servers don't need, e.g. // OIDC connectors and auth preferences h.GET("/webapi/find", httplib.MakeHandler(h.find)) // Web sessions h.POST("/webapi/sessions", httplib.WithCSRFProtection(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)) h.PUT("/webapi/users/password", h.WithAuth(h.changePassword)) // Issues SSH temp certificates based on 2FA access creds h.POST("/webapi/ssh/certs", httplib.MakeHandler(h.createSSHCert)) // list available sites h.GET("/webapi/sites", h.WithAuth(h.getClusters)) // Site specific API // get namespaces h.GET("/webapi/sites/:site/namespaces", h.WithClusterAuth(h.getSiteNamespaces)) // get nodes h.GET("/webapi/sites/:site/namespaces/:namespace/nodes", h.WithClusterAuth(h.siteNodesGet)) // active sessions handlers h.GET("/webapi/sites/:site/namespaces/:namespace/connect", h.WithClusterAuth(h.siteNodeConnect)) // connect to an active session (via websocket) h.GET("/webapi/sites/:site/namespaces/:namespace/sessions", h.WithClusterAuth(h.siteSessionsGet)) // get active list of sessions h.POST("/webapi/sites/:site/namespaces/:namespace/sessions", h.WithClusterAuth(h.siteSessionGenerate)) // create active session metadata h.GET("/webapi/sites/:site/namespaces/:namespace/sessions/:sid", h.WithClusterAuth(h.siteSessionGet)) // get active session metadata // recorded sessions handlers h.GET("/webapi/sites/:site/events", h.WithClusterAuth(h.clusterSearchSessionEvents)) // get recorded list of sessions (from events) h.GET("/webapi/sites/:site/events/search", h.WithClusterAuth(h.clusterSearchEvents)) // search site events h.GET("/webapi/sites/:site/namespaces/:namespace/sessions/:sid/events", h.WithClusterAuth(h.siteSessionEventsGet)) // get recorded session's timing information (from events) h.GET("/webapi/sites/:site/namespaces/:namespace/sessions/:sid/stream", h.siteSessionStreamGet) // get recorded session's bytes (from events) // scp file transfer h.GET("/webapi/sites/:site/namespaces/:namespace/nodes/:server/:login/scp", h.WithClusterAuth(h.transferFile)) h.POST("/webapi/sites/:site/namespaces/:namespace/nodes/:server/:login/scp", h.WithClusterAuth(h.transferFile)) // 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)) // SAML 2.0 handlers h.POST("/webapi/saml/acs", httplib.MakeHandler(h.samlACS)) h.GET("/webapi/saml/sso", httplib.MakeHandler(h.samlSSO)) h.POST("/webapi/saml/login/console", httplib.MakeHandler(h.samlSSOConsole)) // Github connector handlers h.GET("/webapi/github/login/web", httplib.MakeHandler(h.githubLoginWeb)) h.POST("/webapi/github/login/console", httplib.MakeHandler(h.githubLoginConsole)) h.GET("/webapi/github/callback", httplib.MakeHandler(h.githubCallback)) // 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/password/changerequest", h.WithAuth(h.u2fChangePasswordRequest)) 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/context", h.WithAuth(h.getUserContext)) // Issue host credentials. h.POST("/webapi/host/credentials", httplib.MakeHandler(h.hostCredentials)) // if Web UI is enabled, check the assets dir: var ( 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) } h.Handle("GET", "/web/config.js", httplib.MakeHandler(h.getWebConfig)) } routingHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // request is going to the API? if strings.HasPrefix(r.URL.Path, apiPrefix) { http.StripPrefix(apiPrefix, h).ServeHTTP(w, r) return } // request is going to the web UI if cfg.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") { httplib.SetStaticFileHeaders(w.Header()) http.StripPrefix("/web", http.FileServer(staticFS)).ServeHTTP(w, r) } else if strings.HasPrefix(r.URL.Path, "/web/") || r.URL.Path == "/web" { csrfToken, err := csrf.AddCSRFProtection(w, r) if err != nil { log.Errorf("failed to generate CSRF token %v", err) } session := struct { Session string XCSRF string }{ XCSRF: csrfToken, Session: base64.StdEncoding.EncodeToString([]byte("{}")), } ctx, err := h.AuthenticateRequest(w, r, false) if err == nil { re, err := NewSessionResponse(ctx) if err == nil { out, err := json.Marshal(re) if err == nil { session.Session = base64.StdEncoding.EncodeToString(out) } } } httplib.SetIndexHTMLHeaders(w.Header()) 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 }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/apiserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L351-L373
go
train
// getUserContext returns user context // // GET /webapi/user/context //
func (h *Handler) getUserContext(w http.ResponseWriter, r *http.Request, _ httprouter.Params, c *SessionContext) (interface{}, error)
// getUserContext returns user context // // GET /webapi/user/context // func (h *Handler) getUserContext(w http.ResponseWriter, r *http.Request, _ httprouter.Params, c *SessionContext) (interface{}, error)
{ clt, err := c.GetClient() if err != nil { return nil, trace.Wrap(err) } user, err := clt.GetUser(c.GetUser()) if err != nil { return nil, trace.Wrap(err) } userRoleSet, err := services.FetchRoles(user.GetRoles(), clt, user.GetTraits()) if err != nil { return nil, trace.Wrap(err) } userContext, err := ui.NewUserContext(user, userRoleSet) if err != nil { return nil, trace.Wrap(err) } return userContext, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/apiserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L577-L659
go
train
// getWebConfig returns configuration for the web application.
func (h *Handler) getWebConfig(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error)
// getWebConfig returns configuration for the web application. func (h *Handler) getWebConfig(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error)
{ httplib.SetWebConfigHeaders(w.Header()) authProviders := []ui.WebConfigAuthProvider{} secondFactor := teleport.OFF // get all OIDC connectors oidcConnectors, err := h.cfg.ProxyClient.GetOIDCConnectors(false) if err != nil { log.Errorf("Cannot retrieve OIDC connectors: %v.", err) } for _, item := range oidcConnectors { authProviders = append(authProviders, ui.WebConfigAuthProvider{ Type: ui.WebConfigAuthProviderOIDCType, WebAPIURL: ui.WebConfigAuthProviderOIDCURL, Name: item.GetName(), DisplayName: item.GetDisplay(), }) } // get all SAML connectors samlConnectors, err := h.cfg.ProxyClient.GetSAMLConnectors(false) if err != nil { log.Errorf("Cannot retrieve SAML connectors: %v.", err) } for _, item := range samlConnectors { authProviders = append(authProviders, ui.WebConfigAuthProvider{ Type: ui.WebConfigAuthProviderSAMLType, WebAPIURL: ui.WebConfigAuthProviderSAMLURL, Name: item.GetName(), DisplayName: item.GetDisplay(), }) } // get all Github connectors githubConnectors, err := h.cfg.ProxyClient.GetGithubConnectors(false) if err != nil { log.Errorf("Cannot retrieve Github connectors: %v.", err) } for _, item := range githubConnectors { authProviders = append(authProviders, ui.WebConfigAuthProvider{ Type: ui.WebConfigAuthProviderGitHubType, WebAPIURL: ui.WebConfigAuthProviderGitHubURL, Name: item.GetName(), DisplayName: item.GetDisplay(), }) } // get second factor type cap, err := h.cfg.ProxyClient.GetAuthPreference() if err != nil { log.Errorf("Cannot retrieve AuthPreferences: %v.", err) } else { secondFactor = cap.GetSecondFactor() } // disable joining sessions if proxy session recording is enabled var canJoinSessions = true clsCfg, err := h.cfg.ProxyClient.GetClusterConfig() if err != nil { log.Errorf("Cannot retrieve ClusterConfig: %v.", err) } else { canJoinSessions = clsCfg.GetSessionRecording() != services.RecordAtProxy } authSettings := ui.WebConfigAuthSettings{ Providers: authProviders, SecondFactor: secondFactor, } webCfg := ui.WebConfig{ Auth: authSettings, CanJoinSessions: canJoinSessions, } 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 }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/apiserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L901-L967
go
train
// ConstructSSHResponse creates a special SSH response for SSH login method // that encodes everything using the client's secret key
func ConstructSSHResponse(response AuthParams) (*url.URL, error)
// ConstructSSHResponse creates a special SSH response for SSH login method // that encodes everything using the client's secret key func ConstructSSHResponse(response AuthParams) (*url.URL, error)
{ u, err := url.Parse(response.ClientRedirectURL) if err != nil { return nil, trace.Wrap(err) } consoleResponse := auth.SSHLoginResponse{ Username: response.Username, Cert: response.Cert, TLSCert: response.TLSCert, HostSigners: auth.AuthoritiesToTrustedCerts(response.HostSigners), } out, err := json.Marshal(consoleResponse) if err != nil { return nil, trace.Wrap(err) } // Extract secret out of the request. Look for both "secret" which is the // old format and "secret_key" which is the new fomat. If this is not done, // then users would have to update their callback URL in their identity // provider. values := u.Query() secretV1 := values.Get("secret") secretV2 := values.Get("secret_key") values.Set("secret", "") values.Set("secret_key", "") var ciphertext []byte switch { // AES-GCM based symmetric cipher. case secretV2 != "": key, err := secret.ParseKey([]byte(secretV2)) if err != nil { return nil, trace.Wrap(err) } ciphertext, err = key.Seal(out) if err != nil { return nil, trace.Wrap(err) } // NaCl based symmetric cipher (legacy). case secretV1 != "": secretKeyBytes, err := lemma_secret.EncodedStringToKey(secretV1) if err != nil { return nil, trace.BadParameter("bad secret") } encryptor, err := lemma_secret.New(&lemma_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) } ciphertext, err = json.Marshal(sealedBytes) if err != nil { return nil, trace.Wrap(err) } default: return nil, trace.BadParameter("missing secret") } // Place ciphertext into the response body. values.Set("response", string(ciphertext)) u.RawQuery = values.Encode() return u, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/apiserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1041-L1079
go
train
// 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 (h *Handler) createSession(w http.ResponseWriter, r *http.Request, p httprouter.Params) (interface{}, error)
// 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 (h *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 := h.cfg.ProxyClient cap, err := authClient.GetAuthPreference() if err != nil { return nil, trace.Wrap(err) } var webSession services.WebSession switch cap.GetSecondFactor() { case teleport.OFF: webSession, err = h.auth.AuthWithoutOTP(req.User, req.Pass) case teleport.OTP, teleport.HOTP, teleport.TOTP: webSession, err = h.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 := h.auth.ValidateSession(req.User, webSession.GetName()) if err != nil { return nil, trace.AccessDenied("need auth") } return NewSessionResponse(ctx) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/apiserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1089-L1096
go
train
// deleteSession is called to sign out user // // DELETE /v1/webapi/sessions/:sid // // Response: // // {"message": "ok"} //
func (h *Handler) deleteSession(w http.ResponseWriter, r *http.Request, _ httprouter.Params, ctx *SessionContext) (interface{}, error)
// deleteSession is called to sign out user // // DELETE /v1/webapi/sessions/:sid // // Response: // // {"message": "ok"} // func (h *Handler) deleteSession(w http.ResponseWriter, r *http.Request, _ httprouter.Params, ctx *SessionContext) (interface{}, error)
{ err := h.logout(w, ctx) if err != nil { return nil, trace.Wrap(err) } return ok(), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/apiserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/apiserver.go#L1120-L1136
go
train
// 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 (h *Handler) renewSession(w http.ResponseWriter, r *http.Request, _ httprouter.Params, ctx *SessionContext) (interface{}, error)
// 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 (h *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) }