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/utils/jsontools.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/jsontools.go#L122-L133
go
train
// isDoc detects whether value constitues a document
func isDoc(val reflect.Value) bool
// isDoc detects whether value constitues a document func isDoc(val reflect.Value) bool
{ iterations := 0 for val.Kind() == reflect.Interface || val.Kind() == reflect.Ptr { val = val.Elem() // preventing cycles iterations++ if iterations > 10 { return false } } return val.Kind() == reflect.Struct || val.Kind() == reflect.Map }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/jsontools.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/jsontools.go#L136-L143
go
train
// writeYAML writes marshaled YAML to writer
func writeYAML(w io.Writer, values interface{}) error
// writeYAML writes marshaled YAML to writer func writeYAML(w io.Writer, values interface{}) error
{ data, err := yaml.Marshal(values) if err != nil { return trace.Wrap(err) } _, err = w.Write(data) return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/jsontools.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/jsontools.go#L146-L166
go
train
// ReadYAML can unmarshal a stream of documents, used in tests.
func ReadYAML(reader io.Reader) (interface{}, error)
// ReadYAML can unmarshal a stream of documents, used in tests. func ReadYAML(reader io.Reader) (interface{}, error)
{ decoder := kyaml.NewYAMLOrJSONDecoder(reader, 32*1024) var values []interface{} for { var val interface{} err := decoder.Decode(&val) if err != nil { if err == io.EOF { if len(values) == 0 { return nil, trace.BadParameter("no resources found, empty input?") } if len(values) == 1 { r...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/redirect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/redirect.go#L69-L111
go
train
// NewRedirector returns new local web server redirector
func NewRedirector(login SSHLogin) (*Redirector, error)
// NewRedirector returns new local web server redirector func NewRedirector(login SSHLogin) (*Redirector, error)
{ //clt, proxyURL, err := initClient(login.ProxyAddr, login.Insecure, login.Pool) //if err != nil { // return nil, trace.Wrap(err) //} clt, err := NewCredentialsClient(login.ProxyAddr, login.Insecure, login.Pool) if err != nil { return nil, trace.Wrap(err) } // Create secret key that will be sent with the ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/redirect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/redirect.go#L115-L163
go
train
// Start launches local http server on the machine, // initiates SSO login request sequence with the Teleport Proxy
func (rd *Redirector) Start() error
// Start launches local http server on the machine, // initiates SSO login request sequence with the Teleport Proxy func (rd *Redirector) Start() error
{ if rd.BindAddr != "" { log.Debugf("Binding to %v.", rd.BindAddr) listener, err := net.Listen("tcp", rd.BindAddr) if err != nil { return trace.Wrap(err, "%v: could not bind to %v, make sure the address is host:port format for ipv4 and [ipv6]:port format for ipv6, and the address is not in use", err, rd.Bind...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/redirect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/redirect.go#L172-L177
go
train
// ClickableURL returns a short clickable redirect URL
func (rd *Redirector) ClickableURL() string
// ClickableURL returns a short clickable redirect URL func (rd *Redirector) ClickableURL() string
{ if rd.server == nil { return "<undefined - server is not started>" } return utils.ClickableURL(rd.server.URL + rd.shortPath) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/redirect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/redirect.go#L191-L209
go
train
// callback is used by Teleport proxy to send back credentials // issued by Teleport proxy
func (rd *Redirector) callback(w http.ResponseWriter, r *http.Request) (*auth.SSHLoginResponse, error)
// callback is used by Teleport proxy to send back credentials // issued by Teleport proxy func (rd *Redirector) callback(w http.ResponseWriter, r *http.Request) (*auth.SSHLoginResponse, error)
{ if r.URL.Path != "/callback" { return nil, trace.NotFound("path not found") } // Decrypt ciphertext to get login response. plaintext, err := rd.key.Open([]byte(r.URL.Query().Get("response"))) if err != nil { return nil, trace.BadParameter("failed to decrypt response: in %v, err: %v", r.URL.String(), err) ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/redirect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/redirect.go#L212-L218
go
train
// Close closes redirector and releases all resources
func (rd *Redirector) Close() error
// Close closes redirector and releases all resources func (rd *Redirector) Close() error
{ rd.cancel() if rd.server != nil { rd.server.Close() } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/redirect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/redirect.go#L222-L253
go
train
// wrapCallback is a helper wrapper method that wraps callback HTTP handler // and sends a result to the channel and redirect users to error page
func (rd *Redirector) wrapCallback(fn func(http.ResponseWriter, *http.Request) (*auth.SSHLoginResponse, error)) http.Handler
// wrapCallback is a helper wrapper method that wraps callback HTTP handler // and sends a result to the channel and redirect users to error page func (rd *Redirector) wrapCallback(fn func(http.ResponseWriter, *http.Request) (*auth.SSHLoginResponse, error)) http.Handler
{ clone := *rd.proxyURL clone.Path = "/web/msg/error/login_failed" errorURL := clone.String() clone.Path = "/web/msg/info/login_success" successURL := clone.String() return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { response, err := fn(w, r) if err != nil { if trace.IsNotFound(err) {...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/license.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/license.go#L73-L83
go
train
// NewLicense is a convenience method to to create LicenseV3.
func NewLicense(name string, spec LicenseSpecV3) (License, error)
// NewLicense is a convenience method to to create LicenseV3. func NewLicense(name string, spec LicenseSpecV3) (License, error)
{ return &LicenseV3{ Kind: KindLicense, Version: V3, Metadata: Metadata{ Name: name, Namespace: defaults.Namespace, }, Spec: spec, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/license.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/license.go#L139-L141
go
train
// SetLabels sets metadata labels
func (c *LicenseV3) SetLabels(labels map[string]string)
// SetLabels sets metadata labels func (c *LicenseV3) SetLabels(labels map[string]string)
{ c.Metadata.Labels = labels }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/license.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/license.go#L159-L161
go
train
// SetExpiry sets object expiry
func (c *LicenseV3) SetExpiry(t time.Time)
// SetExpiry sets object expiry func (c *LicenseV3) SetExpiry(t time.Time)
{ c.Metadata.SetExpiry(t) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/license.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/license.go#L227-L248
go
train
// String represents a human readable version of license enabled features
func (c *LicenseV3) String() string
// String represents a human readable version of license enabled features func (c *LicenseV3) String() string
{ var features []string if !c.Expiry().IsZero() { features = append(features, fmt.Sprintf("expires at %v", c.Expiry())) } if c.Spec.ReportsUsage.Value() { features = append(features, "reports usage") } if c.Spec.SupportsKubernetes.Value() { features = append(features, "supports kubernetes") } if c.Spec.A...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/license.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/license.go#L292-L314
go
train
// UnmarshalLicense unmarshals License from JSON or YAML // and validates schema
func UnmarshalLicense(bytes []byte) (License, error)
// UnmarshalLicense unmarshals License from JSON or YAML // and validates schema func UnmarshalLicense(bytes []byte) (License, error)
{ if len(bytes) == 0 { return nil, trace.BadParameter("missing resource data") } schema := fmt.Sprintf(V2SchemaTemplate, MetadataSchema, LicenseSpecV3Template, DefaultDefinitions) var license LicenseV3 err := utils.UnmarshalWithSchema(schema, &license, bytes) if err != nil { return nil, trace.BadParameter(...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/license.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/license.go#L317-L335
go
train
// MarshalLicense marshals role to JSON or YAML.
func MarshalLicense(license License, opts ...MarshalOption) ([]byte, error)
// MarshalLicense marshals role to JSON or YAML. func MarshalLicense(license License, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := license.(type) { case *LicenseV3: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/ssh_to_http.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/ssh_to_http.go#L88-L95
go
train
// Accept waits for new connections to arrive (via CreateBridge) and returns them to // the blocked http.Serve()
func (socket *fakeSocket) Accept() (c net.Conn, err error)
// Accept waits for new connections to arrive (via CreateBridge) and returns them to // the blocked http.Serve() func (socket *fakeSocket) Accept() (c net.Conn, err error)
{ select { case newConnection := <-socket.connections: return newConnection, nil case <-socket.closed: return nil, io.EOF } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/ssh_to_http.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/ssh_to_http.go#L99-L105
go
train
// Close closes the listener. // Any blocked Accept operations will be unblocked and return errors.
func (socket *fakeSocket) Close() error
// Close closes the listener. // Any blocked Accept operations will be unblocked and return errors. func (socket *fakeSocket) Close() error
{ socket.closeOnce.Do(func() { // broadcast that listener has closed to all listening parties close(socket.closed) }) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agentpool.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agentpool.go#L91-L111
go
train
// CheckAndSetDefaults checks and sets defaults
func (cfg *AgentPoolConfig) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets defaults func (cfg *AgentPoolConfig) CheckAndSetDefaults() error
{ if cfg.Client == nil { return trace.BadParameter("missing 'Client' parameter") } if cfg.AccessPoint == nil { return trace.BadParameter("missing 'AccessPoint' parameter") } if len(cfg.HostSigners) == 0 { return trace.BadParameter("missing 'HostSigners' parameter") } if len(cfg.HostUUID) == 0 { return t...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agentpool.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agentpool.go#L114-L133
go
train
// NewAgentPool returns new isntance of the agent pool
func NewAgentPool(cfg AgentPoolConfig) (*AgentPool, error)
// NewAgentPool returns new isntance of the agent pool func NewAgentPool(cfg AgentPoolConfig) (*AgentPool, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(cfg.Context) pool := &AgentPool{ agents: make(map[agentKey][]*Agent), cfg: cfg, ctx: ctx, cancel: cancel, discoveryC: make(chan *discoveryRequest), } pool.Entry = ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agentpool.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agentpool.go#L227-L236
go
train
// FetchAndSyncAgents executes one time fetch and sync request // (used in tests instead of polling)
func (m *AgentPool) FetchAndSyncAgents() error
// FetchAndSyncAgents executes one time fetch and sync request // (used in tests instead of polling) func (m *AgentPool) FetchAndSyncAgents() error
{ tunnels, err := m.cfg.AccessPoint.GetReverseTunnels() if err != nil { return trace.Wrap(err) } if err := m.syncAgents(tunnels); err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agentpool.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agentpool.go#L344-L352
go
train
// Counts returns a count of the number of proxies a outbound tunnel is // connected to. Used in tests to determine if a proxy has been found and/or // removed.
func (m *AgentPool) Counts() map[string]int
// Counts returns a count of the number of proxies a outbound tunnel is // connected to. Used in tests to determine if a proxy has been found and/or // removed. func (m *AgentPool) Counts() map[string]int
{ out := make(map[string]int) for key, agents := range m.agents { out[key.tunnelID] += len(agents) } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agentpool.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agentpool.go#L356-L388
go
train
// reportStats submits report about agents state once in a while at info // level. Always logs more detailed information at debug level.
func (m *AgentPool) reportStats()
// reportStats submits report about agents state once in a while at info // level. Always logs more detailed information at debug level. func (m *AgentPool) reportStats()
{ var logReport bool if m.cfg.Clock.Now().Sub(m.lastReport) > defaults.ReportingPeriod { m.lastReport = m.cfg.Clock.Now() logReport = true } for key, agents := range m.agents { m.Debugf("Outbound tunnel for %v connected to %v proxies.", key.tunnelID, len(agents)) countPerState := map[string]int{ agent...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/agentpool.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agentpool.go#L447-L464
go
train
// removeDisconnected removes disconnected agents from the list of agents. // This function should be called under a lock.
func (m *AgentPool) removeDisconnected()
// removeDisconnected removes disconnected agents from the list of agents. // This function should be called under a lock. func (m *AgentPool) removeDisconnected()
{ for agentKey, agentSlice := range m.agents { // Filter and close all disconnected agents. validAgents := filterAndClose(agentSlice, func(agent *Agent) bool { if agent.getState() == agentStateDisconnected { return true } return false }) // Update (or delete) agent key with filter applied. if ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/storage.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/storage.go#L43-L54
go
train
// SetAddresses updates storage with new address list
func (fs *FileAddrStorage) SetAddresses(addrs []NetAddr) error
// SetAddresses updates storage with new address list func (fs *FileAddrStorage) SetAddresses(addrs []NetAddr) error
{ bytes, err := json.Marshal(addrs) if err != nil { return trace.Wrap(err) } err = ioutil.WriteFile(fs.filePath, bytes, 0666) if err != nil { log.Error(err) return trace.ConvertSystemError(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/storage.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/storage.go#L57-L70
go
train
// GetAddresses returns saved address list
func (fs *FileAddrStorage) GetAddresses() ([]NetAddr, error)
// GetAddresses returns saved address list func (fs *FileAddrStorage) GetAddresses() ([]NetAddr, error)
{ bytes, err := ioutil.ReadFile(fs.filePath) if err != nil { return nil, trace.ConvertSystemError(err) } var addrs []NetAddr if len(bytes) > 0 { err = json.Unmarshal(bytes, &addrs) if err != nil { return nil, trace.Wrap(err) } } return addrs, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/tlsdial.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tlsdial.go#L22-L75
go
train
// TLSDial dials and establishes TLS connection using custom dialer // is similar to tls.DialWithDialer
func TLSDial(ctx context.Context, dial DialWithContextFunc, network, addr string, tlsConfig *tls.Config) (*tls.Conn, error)
// TLSDial dials and establishes TLS connection using custom dialer // is similar to tls.DialWithDialer func TLSDial(ctx context.Context, dial DialWithContextFunc, network, addr string, tlsConfig *tls.Config) (*tls.Conn, error)
{ if tlsConfig == nil { tlsConfig = &tls.Config{} } plainConn, err := dial(ctx, network, addr) if err != nil { return nil, trace.Wrap(err) } colonPos := strings.LastIndex(addr, ":") if colonPos == -1 { colonPos = len(addr) } hostname := addr[:colonPos] // If no ServerName is set, infer the ServerNam...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/web/ui/usercontext.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/ui/usercontext.go#L110-L145
go
train
// NewUserContext constructs user context from roles assigned to user
func NewUserContext(user services.User, userRoles services.RoleSet) (*userContext, error)
// NewUserContext constructs user context from roles assigned to user func NewUserContext(user services.User, userRoles services.RoleSet) (*userContext, error)
{ ctx := &services.Context{User: user} sessionAccess := newAccess(userRoles, ctx, services.KindSession) roleAccess := newAccess(userRoles, ctx, services.KindRole) authConnectors := newAccess(userRoles, ctx, services.KindAuthConnector) trustedClusterAccess := newAccess(userRoles, ctx, services.KindTrustedCluster) ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/middleware.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/middleware.go#L55-L76
go
train
// CheckAndSetDefaults checks and sets default values
func (c *TLSServerConfig) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets default values func (c *TLSServerConfig) CheckAndSetDefaults() error
{ if c.TLS == nil { return trace.BadParameter("missing parameter TLS") } c.TLS.ClientAuth = tls.VerifyClientCertIfGiven if c.TLS.ClientCAs == nil { return trace.BadParameter("missing parameter TLS.ClientCAs") } if c.TLS.RootCAs == nil { return trace.BadParameter("missing parameter TLS.RootCAs") } if len(...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/middleware.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/middleware.go#L88-L123
go
train
// NewTLSServer returns new unstarted TLS server
func NewTLSServer(cfg TLSServerConfig) (*TLSServer, error)
// NewTLSServer returns new unstarted TLS server func NewTLSServer(cfg TLSServerConfig) (*TLSServer, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } // limiter limits requests by frequency and amount of simultaneous // connections per client limiter, err := limiter.NewLimiter(cfg.LimiterConfig) if err != nil { return nil, trace.Wrap(err) } // authMiddleware authenticates ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/middleware.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/middleware.go#L126-L128
go
train
// Serve takes TCP listener, upgrades to TLS using config and starts serving
func (t *TLSServer) Serve(listener net.Listener) error
// Serve takes TCP listener, upgrades to TLS using config and starts serving func (t *TLSServer) Serve(listener net.Listener) error
{ return t.Server.Serve(tls.NewListener(listener, t.TLS)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/middleware.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/middleware.go#L133-L166
go
train
// GetConfigForClient is getting called on every connection // and server's GetConfigForClient reloads the list of trusted // local and remote certificate authorities
func (t *TLSServer) GetConfigForClient(info *tls.ClientHelloInfo) (*tls.Config, error)
// GetConfigForClient is getting called on every connection // and server's GetConfigForClient reloads the list of trusted // local and remote certificate authorities func (t *TLSServer) GetConfigForClient(info *tls.ClientHelloInfo) (*tls.Config, error)
{ var clusterName string var err error if info.ServerName != "" { clusterName, err = DecodeClusterName(info.ServerName) if err != nil { if !trace.IsNotFound(err) { t.Warningf("Client sent unsupported cluster name %q, what resulted in error %v.", info.ServerName, err) return nil, trace.AccessDenied("a...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/middleware.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/middleware.go#L189-L282
go
train
// GetUser returns authenticated user based on request metadata set by HTTP server
func (a *AuthMiddleware) GetUser(r *http.Request) (interface{}, error)
// GetUser returns authenticated user based on request metadata set by HTTP server func (a *AuthMiddleware) GetUser(r *http.Request) (interface{}, error)
{ peers := r.TLS.PeerCertificates if len(peers) > 1 { // when turning intermediaries on, don't forget to verify // https://github.com/kubernetes/kubernetes/pull/34524/files#diff-2b283dde198c92424df5355f39544aa4R59 return nil, trace.AccessDenied("access denied: intermediaries are not supported") } localCluste...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/middleware.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/middleware.go#L296-L310
go
train
// ServeHTTP serves HTTP requests
func (a *AuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request)
// ServeHTTP serves HTTP requests func (a *AuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request)
{ baseContext := r.Context() if baseContext == nil { baseContext = context.TODO() } user, err := a.GetUser(r) if err != nil { trace.WriteError(w, err) return } // determine authenticated user based on the request parameters requestWithContext := r.WithContext(context.WithValue(baseContext, ContextUser, ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/middleware.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/middleware.go#L313-L355
go
train
// ClientCertPool returns trusted x509 cerificate authority pool
func ClientCertPool(client AccessCache, clusterName string) (*x509.CertPool, error)
// ClientCertPool returns trusted x509 cerificate authority pool func ClientCertPool(client AccessCache, clusterName string) (*x509.CertPool, error)
{ pool := x509.NewCertPool() var authorities []services.CertAuthority if clusterName == "" { hostCAs, err := client.GetCertAuthorities(services.HostCA, false, services.SkipValidation()) if err != nil { return nil, trace.Wrap(err) } userCAs, err := client.GetCertAuthorities(services.UserCA, false, service...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L101-L117
go
train
// readConfigFile reads /etc/teleport.yaml (or whatever is passed via --config flag) // and overrides values in 'cfg' structure
func ReadConfigFile(cliConfigPath string) (*FileConfig, error)
// readConfigFile reads /etc/teleport.yaml (or whatever is passed via --config flag) // and overrides values in 'cfg' structure func ReadConfigFile(cliConfigPath string) (*FileConfig, error)
{ configFilePath := defaults.ConfigFilePath // --config tells us to use a specific conf. file: if cliConfigPath != "" { configFilePath = cliConfigPath if !fileExists(configFilePath) { return nil, trace.Errorf("file not found: %s", configFilePath) } } // default config doesn't exist? quietly return: if !...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L121-L309
go
train
// ApplyFileConfig applies configuration from a YAML file to Teleport // runtime config
func ApplyFileConfig(fc *FileConfig, cfg *service.Config) error
// ApplyFileConfig applies configuration from a YAML file to Teleport // runtime config func ApplyFileConfig(fc *FileConfig, cfg *service.Config) error
{ var err error // no config file? no problem if fc == nil { return nil } // merge file-based config with defaults in 'cfg' if fc.Auth.Disabled() { cfg.Auth.Enabled = false } if fc.SSH.Disabled() { cfg.SSH.Enabled = false } if fc.Proxy.Disabled() { cfg.Proxy.Enabled = false } applyString(fc.NodeNa...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L312-L439
go
train
// applyAuthConfig applies file configuration for the "auth_service" section.
func applyAuthConfig(fc *FileConfig, cfg *service.Config) error
// applyAuthConfig applies file configuration for the "auth_service" section. func applyAuthConfig(fc *FileConfig, cfg *service.Config) error
{ var err error if fc.Auth.KubeconfigFile != "" { warningMessage := "The auth_service no longer needs kubeconfig_file. It has " + "been moved to proxy_service section. This setting is ignored." log.Warning(warningMessage) } cfg.Auth.EnableProxyProtocol, err = utils.ParseOnOff("proxy_protocol", fc.Auth.Prox...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L442-L557
go
train
// applyProxyConfig applies file configuration for the "proxy_service" section.
func applyProxyConfig(fc *FileConfig, cfg *service.Config) error
// applyProxyConfig applies file configuration for the "proxy_service" section. func applyProxyConfig(fc *FileConfig, cfg *service.Config) error
{ var err error cfg.Proxy.EnableProxyProtocol, err = utils.ParseOnOff("proxy_protocol", fc.Proxy.ProxyProtocol, true) if err != nil { return trace.Wrap(err) } if fc.Proxy.ListenAddress != "" { addr, err := utils.ParseHostPortAddr(fc.Proxy.ListenAddress, int(defaults.SSHProxyListenPort)) if err != nil { ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L560-L620
go
train
// applySSHConfig applies file configuration for the "ssh_service" section.
func applySSHConfig(fc *FileConfig, cfg *service.Config) error
// applySSHConfig applies file configuration for the "ssh_service" section. func applySSHConfig(fc *FileConfig, cfg *service.Config) error
{ if fc.SSH.ListenAddress != "" { addr, err := utils.ParseHostPortAddr(fc.SSH.ListenAddress, int(defaults.SSHServerListenPort)) if err != nil { return trace.Wrap(err) } cfg.SSH.Addr = *addr } if fc.SSH.Labels != nil { cfg.SSH.Labels = make(map[string]string) for k, v := range fc.SSH.Labels { cfg.S...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L624-L653
go
train
// parseAuthorizedKeys parses keys in the authorized_keys format and // returns a services.CertAuthority.
func parseAuthorizedKeys(bytes []byte, allowedLogins []string) (services.CertAuthority, services.Role, error)
// parseAuthorizedKeys parses keys in the authorized_keys format and // returns a services.CertAuthority. func parseAuthorizedKeys(bytes []byte, allowedLogins []string) (services.CertAuthority, services.Role, error)
{ pubkey, comment, _, _, err := ssh.ParseAuthorizedKey(bytes) if err != nil { return nil, nil, trace.Wrap(err) } comments, err := url.ParseQuery(comment) if err != nil { return nil, nil, trace.Wrap(err) } clusterName := comments.Get("clustername") if clusterName == "" { return nil, nil, trace.BadParamet...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L657-L687
go
train
// parseKnownHosts parses keys in known_hosts format and returns a // services.CertAuthority.
func parseKnownHosts(bytes []byte, allowedLogins []string) (services.CertAuthority, services.Role, error)
// parseKnownHosts parses keys in known_hosts format and returns a // services.CertAuthority. func parseKnownHosts(bytes []byte, allowedLogins []string) (services.CertAuthority, services.Role, error)
{ marker, options, pubKey, comment, _, err := ssh.ParseKnownHosts(bytes) if marker != "cert-authority" { return nil, nil, trace.BadParameter("invalid file format. expected '@cert-authority` marker") } if err != nil { return nil, nil, trace.BadParameter("invalid public key") } teleportOpts, err := url.ParseQu...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L691-L701
go
train
// certificateAuthorityFormat parses bytes and determines if they are in // known_hosts format or authorized_keys format.
func certificateAuthorityFormat(bytes []byte) (string, error)
// certificateAuthorityFormat parses bytes and determines if they are in // known_hosts format or authorized_keys format. func certificateAuthorityFormat(bytes []byte) (string, error)
{ _, _, _, _, err := ssh.ParseAuthorizedKey(bytes) if err != nil { _, _, _, _, _, err := ssh.ParseKnownHosts(bytes) if err != nil { return "", trace.BadParameter("unknown ca format") } return teleport.KnownHosts, nil } return teleport.AuthorizedKeys, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L705-L715
go
train
// parseCAKey parses bytes either in known_hosts or authorized_keys format // and returns a services.CertAuthority.
func parseCAKey(bytes []byte, allowedLogins []string) (services.CertAuthority, services.Role, error)
// parseCAKey parses bytes either in known_hosts or authorized_keys format // and returns a services.CertAuthority. func parseCAKey(bytes []byte, allowedLogins []string) (services.CertAuthority, services.Role, error)
{ caFormat, err := certificateAuthorityFormat(bytes) if err != nil { return nil, nil, trace.Wrap(err) } if caFormat == teleport.AuthorizedKeys { return parseAuthorizedKeys(bytes, allowedLogins) } return parseKnownHosts(bytes, allowedLogins) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L720-L786
go
train
// readTrustedClusters parses the content of "trusted_clusters" YAML structure // and modifies Teleport 'conf' by adding "authorities" and "reverse tunnels" // to it
func readTrustedClusters(clusters []TrustedCluster, conf *service.Config) error
// readTrustedClusters parses the content of "trusted_clusters" YAML structure // and modifies Teleport 'conf' by adding "authorities" and "reverse tunnels" // to it func readTrustedClusters(clusters []TrustedCluster, conf *service.Config) error
{ if len(clusters) == 0 { return nil } // go over all trusted clusters: for i := range clusters { tc := &clusters[i] // parse "allow_logins" var allowedLogins []string for _, login := range strings.Split(tc.AllowedLogins, ",") { login = strings.TrimSpace(login) if login != "" { allowedLogins = ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L790-L796
go
train
// applyString takes 'src' and overwrites target with it, unless 'src' is empty // returns 'True' if 'src' was not empty
func applyString(src string, target *string) bool
// applyString takes 'src' and overwrites target with it, unless 'src' is empty // returns 'True' if 'src' was not empty func applyString(src string, target *string) bool
{ if src != "" { *target = src return true } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L800-L928
go
train
// Configure merges command line arguments with what's in a configuration file // with CLI commands taking precedence
func Configure(clf *CommandLineFlags, cfg *service.Config) error
// Configure merges command line arguments with what's in a configuration file // with CLI commands taking precedence func Configure(clf *CommandLineFlags, cfg *service.Config) error
{ // pass the value of --insecure flag to the runtime lib.SetInsecureDevMode(clf.InsecureMode) // load /etc/teleport.yaml and apply it's values: fileConf, err := ReadConfigFile(clf.ConfigFile) if err != nil { return trace.Wrap(err) } // if configuration is passed as an environment variable, // try to decode...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L932-L958
go
train
// parseLabels takes the value of --labels flag and tries to correctly populate // sshConf.Labels and sshConf.CmdLabels
func parseLabels(spec string, sshConf *service.SSHConfig) error
// parseLabels takes the value of --labels flag and tries to correctly populate // sshConf.Labels and sshConf.CmdLabels func parseLabels(spec string, sshConf *service.SSHConfig) error
{ if spec == "" { return nil } // base syntax parsing, the spec must be in the form of 'key=value,more="better"` lmap, err := client.ParseLabelSpec(spec) if err != nil { return trace.Wrap(err) } if len(lmap) > 0 { sshConf.CmdLabels = make(services.CommandLabels, 0) sshConf.Labels = make(map[string]strin...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L965-L997
go
train
// isCmdLabelSpec tries to interpret a given string as a "command label" spec. // A command label spec looks like [time_duration:command param1 param2 ...] where // time_duration is in "1h2m1s" form. // // Example of a valid spec: "[1h:/bin/uname -m]"
func isCmdLabelSpec(spec string) (services.CommandLabel, error)
// isCmdLabelSpec tries to interpret a given string as a "command label" spec. // A command label spec looks like [time_duration:command param1 param2 ...] where // time_duration is in "1h2m1s" form. // // Example of a valid spec: "[1h:/bin/uname -m]" func isCmdLabelSpec(spec string) (services.CommandLabel, error)
{ // command spec? (surrounded by brackets?) if len(spec) > 5 && spec[0] == '[' && spec[len(spec)-1] == ']' { invalidSpecError := trace.BadParameter( "invalid command label spec: '%s'", spec) spec = strings.Trim(spec, "[]") idx := strings.IndexRune(spec, ':') if idx < 0 { return nil, trace.Wrap(invalid...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L1001-L1013
go
train
// applyListenIP replaces all 'listen addr' settings for all services with // a given IP
func applyListenIP(ip net.IP, cfg *service.Config)
// applyListenIP replaces all 'listen addr' settings for all services with // a given IP func applyListenIP(ip net.IP, cfg *service.Config)
{ listeningAddresses := []*utils.NetAddr{ &cfg.Auth.SSHAddr, &cfg.Auth.SSHAddr, &cfg.Proxy.SSHAddr, &cfg.Proxy.WebAddr, &cfg.SSH.Addr, &cfg.Proxy.ReverseTunnelListenAddr, } for _, addr := range listeningAddresses { replaceHost(addr, ip.String()) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L1017-L1023
go
train
// replaceHost takes utils.NetAddr and replaces the hostname in it, preserving // the original port
func replaceHost(addr *utils.NetAddr, newHost string)
// replaceHost takes utils.NetAddr and replaces the hostname in it, preserving // the original port func replaceHost(addr *utils.NetAddr, newHost string)
{ _, port, err := net.SplitHostPort(addr.Addr) if err != nil { log.Errorf("failed parsing address: '%v'", addr.Addr) } addr.Addr = net.JoinHostPort(newHost, port) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/configuration.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/configuration.go#L1034-L1046
go
train
// validateRoles makes sure that value upassed to --roles flag is valid
func validateRoles(roles string) error
// validateRoles makes sure that value upassed to --roles flag is valid func validateRoles(roles string) error
{ for _, role := range strings.Split(roles, ",") { switch role { case defaults.RoleAuthService, defaults.RoleNode, defaults.RoleProxy: break default: return trace.Errorf("unknown role: '%s'", role) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/legacy/metadata.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/legacy/metadata.go#L54-L56
go
train
// MarshalJSON marshals Duration to string
func (d Duration) MarshalJSON() ([]byte, error)
// MarshalJSON marshals Duration to string func (d Duration) MarshalJSON() ([]byte, error)
{ return json.Marshal(fmt.Sprintf("%v", d.Duration)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/new_web_user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/new_web_user.go#L45-L116
go
train
// CreateSignupToken creates one time token for creating account for the user // For each token it creates username and otp generator
func (s *AuthServer) CreateSignupToken(userv1 services.UserV1, ttl time.Duration) (string, error)
// CreateSignupToken creates one time token for creating account for the user // For each token it creates username and otp generator func (s *AuthServer) CreateSignupToken(userv1 services.UserV1, ttl time.Duration) (string, error)
{ user := userv1.V2() if err := user.Check(); err != nil { return "", trace.Wrap(err) } if ttl > defaults.MaxSignupTokenTTL { return "", trace.BadParameter("failed to invite user: maximum signup token TTL is %v hours", int(defaults.MaxSignupTokenTTL/time.Hour)) } // make sure that connectors actually exist...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/new_web_user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/new_web_user.go#L119-L138
go
train
// initializeTOTP creates TOTP algorithm and returns the key and QR code.
func (s *AuthServer) initializeTOTP(accountName string) (key string, qr []byte, err error)
// initializeTOTP creates TOTP algorithm and returns the key and QR code. func (s *AuthServer) initializeTOTP(accountName string) (key string, qr []byte, err error)
{ // create totp key otpKey, err := totp.Generate(totp.GenerateOpts{ Issuer: "Teleport", AccountName: accountName, }) if err != nil { return "", nil, trace.Wrap(err) } // create QR code var otpQRBuf bytes.Buffer otpImage, err := otpKey.Image(456, 456) if err != nil { return "", nil, trace.Wrap(e...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/new_web_user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/new_web_user.go#L144-L167
go
train
// rotateAndFetchSignupToken rotates the signup token everytime it's fetched. // This ensures that an attacker that gains the signup link can not view it, // extract the OTP key from the QR code, then allow the user to signup with // the same OTP token.
func (s *AuthServer) rotateAndFetchSignupToken(token string) (*services.SignupToken, error)
// rotateAndFetchSignupToken rotates the signup token everytime it's fetched. // This ensures that an attacker that gains the signup link can not view it, // extract the OTP key from the QR code, then allow the user to signup with // the same OTP token. func (s *AuthServer) rotateAndFetchSignupToken(token string) (*ser...
{ var err error // Fetch original signup token. st, err := s.GetSignupToken(token) if err != nil { return nil, trace.Wrap(err) } // Generate and set new OTP code for user in *services.SignupToken. accountName := st.User.V2().GetName() + "@" + s.AuthServiceName st.OTPKey, st.OTPQRCode, err = s.initializeTOT...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/new_web_user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/new_web_user.go#L171-L191
go
train
// GetSignupTokenData returns token data (username and QR code bytes) for a // valid signup token.
func (s *AuthServer) GetSignupTokenData(token string) (user string, qrCode []byte, err error)
// GetSignupTokenData returns token data (username and QR code bytes) for a // valid signup token. func (s *AuthServer) GetSignupTokenData(token string) (user string, qrCode []byte, err error)
{ // Rotate OTP secret before the signup data is fetched (signup page is // rendered). This mitigates attacks where an attacker just views the signup // link, extracts the OTP secret from the QR code, then closes the window. // Then when the user signs up later, the attacker has access to the OTP // secret. st, ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/new_web_user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/new_web_user.go#L232-L262
go
train
// CreateUserWithOTP creates account with provided token and password. // Account username and hotp generator are taken from token data. // Deletes token after account creation.
func (s *AuthServer) CreateUserWithOTP(token string, password string, otpToken string) (services.WebSession, error)
// CreateUserWithOTP creates account with provided token and password. // Account username and hotp generator are taken from token data. // Deletes token after account creation. func (s *AuthServer) CreateUserWithOTP(token string, password string, otpToken string) (services.WebSession, error)
{ tokenData, err := s.GetSignupToken(token) if err != nil { log.Debugf("failed to get signup token: %v", err) return nil, trace.AccessDenied("expired or incorrect signup token") } err = s.UpsertTOTP(tokenData.User.Name, tokenData.OTPKey) if err != nil { return nil, trace.Wrap(err) } err = s.CheckOTP(tok...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/new_web_user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/new_web_user.go#L265-L291
go
train
// CreateUserWithoutOTP creates an account with the provided password and deletes the token afterwards.
func (s *AuthServer) CreateUserWithoutOTP(token string, password string) (services.WebSession, error)
// CreateUserWithoutOTP creates an account with the provided password and deletes the token afterwards. func (s *AuthServer) CreateUserWithoutOTP(token string, password string) (services.WebSession, error)
{ authPreference, err := s.GetAuthPreference() if err != nil { return nil, trace.Wrap(err) } if authPreference.GetSecondFactor() != teleport.OFF { return nil, trace.AccessDenied("missing second factor") } tokenData, err := s.GetSignupToken(token) if err != nil { log.Warningf("failed to get signup token: %...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/new_web_user.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/new_web_user.go#L347-L380
go
train
// createUserAndSession takes a signup token and creates services.User (either // with the passed in roles, or if no role, the default role) and // services.WebSession in the backend and returns the new services.WebSession.
func (a *AuthServer) createUserAndSession(stoken *services.SignupToken) (services.WebSession, error)
// createUserAndSession takes a signup token and creates services.User (either // with the passed in roles, or if no role, the default role) and // services.WebSession in the backend and returns the new services.WebSession. func (a *AuthServer) createUserAndSession(stoken *services.SignupToken) (services.WebSession, er...
{ // extract user from signup token. if no roles have been passed along, create // user with default role. note: during the conversion from services.UserV1 // to services.UserV2 we convert allowed logins to traits. user := stoken.User.V2() if len(user.GetRoles()) == 0 { user.SetRoles([]string{teleport.AdminRole...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/statictokens.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/statictokens.go#L47-L62
go
train
// NewStaticTokens is a convenience wrapper to create a StaticTokens resource.
func NewStaticTokens(spec StaticTokensSpecV2) (StaticTokens, error)
// NewStaticTokens is a convenience wrapper to create a StaticTokens resource. func NewStaticTokens(spec StaticTokensSpecV2) (StaticTokens, error)
{ st := StaticTokensV2{ Kind: KindStaticTokens, Version: V2, Metadata: Metadata{ Name: MetaNameStaticTokens, Namespace: defaults.Namespace, }, Spec: spec, } if err := st.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &st, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/statictokens.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/statictokens.go#L66-L78
go
train
// DefaultStaticTokens is used to get the default static tokens (empty list) // when nothing is specified in file configuration.
func DefaultStaticTokens() StaticTokens
// DefaultStaticTokens is used to get the default static tokens (empty list) // when nothing is specified in file configuration. func DefaultStaticTokens() StaticTokens
{ return &StaticTokensV2{ Kind: KindStaticTokens, Version: V2, Metadata: Metadata{ Name: MetaNameStaticTokens, Namespace: defaults.Namespace, }, Spec: StaticTokensSpecV2{ StaticTokens: []ProvisionTokenV1{}, }, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/statictokens.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/statictokens.go#L126-L128
go
train
// SetExpiry sets expiry time for the object
func (c *StaticTokensV2) SetExpiry(expires time.Time)
// SetExpiry sets expiry time for the object func (c *StaticTokensV2) SetExpiry(expires time.Time)
{ c.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/statictokens.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/statictokens.go#L141-L143
go
train
// SetStaticTokens sets the list of static tokens used to provision nodes.
func (c *StaticTokensV2) SetStaticTokens(s []ProvisionToken)
// SetStaticTokens sets the list of static tokens used to provision nodes. func (c *StaticTokensV2) SetStaticTokens(s []ProvisionToken)
{ c.Spec.StaticTokens = ProvisionTokensToV1(s) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/statictokens.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/statictokens.go#L151-L159
go
train
// CheckAndSetDefaults checks validity of all parameters and sets defaults.
func (c *StaticTokensV2) CheckAndSetDefaults() error
// CheckAndSetDefaults checks validity of all parameters and sets defaults. func (c *StaticTokensV2) CheckAndSetDefaults() error
{ // make sure we have defaults for all metadata fields err := c.Metadata.CheckAndSetDefaults() if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/statictokens.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/statictokens.go#L197-L205
go
train
// GetStaticTokensSchema returns the schema with optionally injected // schema for extensions.
func GetStaticTokensSchema(extensionSchema string) string
// GetStaticTokensSchema returns the schema with optionally injected // schema for extensions. func GetStaticTokensSchema(extensionSchema string) string
{ var staticTokensSchema string if staticTokensSchema == "" { staticTokensSchema = fmt.Sprintf(StaticTokensSpecSchemaTemplate, "") } else { staticTokensSchema = fmt.Sprintf(StaticTokensSpecSchemaTemplate, ","+extensionSchema) } return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, staticTokensSchema, DefaultDe...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/statictokens.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/statictokens.go#L234-L269
go
train
// Unmarshal unmarshals StaticTokens from JSON.
func (t *TeleportStaticTokensMarshaler) Unmarshal(bytes []byte, opts ...MarshalOption) (StaticTokens, error)
// Unmarshal unmarshals StaticTokens from JSON. func (t *TeleportStaticTokensMarshaler) Unmarshal(bytes []byte, opts ...MarshalOption) (StaticTokens, error)
{ var staticTokens StaticTokensV2 if len(bytes) == 0 { return nil, trace.BadParameter("missing resource data") } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } if cfg.SkipValidation { if err := utils.FastUnmarshal(bytes, &staticTokens); err != nil { return nil, trace....
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/statictokens.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/statictokens.go#L272-L290
go
train
// Marshal marshals StaticTokens to JSON.
func (t *TeleportStaticTokensMarshaler) Marshal(c StaticTokens, opts ...MarshalOption) ([]byte, error)
// Marshal marshals StaticTokens to JSON. func (t *TeleportStaticTokensMarshaler) Marshal(c StaticTokens, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch resource := c.(type) { case *StaticTokensV2: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *resource copy.SetResourceID(0) resource = &copy ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/trust.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/trust.go#L26-L29
go
train
// DeleteAllCertAuthorities deletes all certificate authorities of a certain type
func (s *CA) DeleteAllCertAuthorities(caType services.CertAuthType) error
// DeleteAllCertAuthorities deletes all certificate authorities of a certain type func (s *CA) DeleteAllCertAuthorities(caType services.CertAuthType) error
{ startKey := backend.Key(authoritiesPrefix, string(caType)) return s.DeleteRange(context.TODO(), startKey, backend.RangeEnd(startKey)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/trust.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/trust.go#L32-L54
go
train
// CreateCertAuthority updates or inserts a new certificate authority
func (s *CA) CreateCertAuthority(ca services.CertAuthority) error
// CreateCertAuthority updates or inserts a new certificate authority func (s *CA) CreateCertAuthority(ca services.CertAuthority) error
{ if err := ca.Check(); err != nil { return trace.Wrap(err) } value, err := services.GetCertAuthorityMarshaler().MarshalCertAuthority(ca) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(authoritiesPrefix, string(ca.GetType()), ca.GetName()), Value: value, Expires: ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/trust.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/trust.go#L57-L77
go
train
// UpsertCertAuthority updates or inserts a new certificate authority
func (s *CA) UpsertCertAuthority(ca services.CertAuthority) error
// UpsertCertAuthority updates or inserts a new certificate authority func (s *CA) UpsertCertAuthority(ca services.CertAuthority) error
{ if err := ca.Check(); err != nil { return trace.Wrap(err) } value, err := services.GetCertAuthorityMarshaler().MarshalCertAuthority(ca) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(authoritiesPrefix, string(ca.GetType()), ca.GetName()), Value: value, Expires: ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/trust.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/trust.go#L82-L114
go
train
// CompareAndSwapCertAuthority updates the cert authority value // if the existing value matches existing parameter, returns nil if succeeds, // trace.CompareFailed otherwise.
func (s *CA) CompareAndSwapCertAuthority(new, existing services.CertAuthority) error
// CompareAndSwapCertAuthority updates the cert authority value // if the existing value matches existing parameter, returns nil if succeeds, // trace.CompareFailed otherwise. func (s *CA) CompareAndSwapCertAuthority(new, existing services.CertAuthority) error
{ if err := new.Check(); err != nil { return trace.Wrap(err) } newValue, err := services.GetCertAuthorityMarshaler().MarshalCertAuthority(new) if err != nil { return trace.Wrap(err) } newItem := backend.Item{ Key: backend.Key(authoritiesPrefix, string(new.GetType()), new.GetName()), Value: newValue...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/trust.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/trust.go#L117-L134
go
train
// DeleteCertAuthority deletes particular certificate authority
func (s *CA) DeleteCertAuthority(id services.CertAuthID) error
// DeleteCertAuthority deletes particular certificate authority func (s *CA) DeleteCertAuthority(id services.CertAuthID) error
{ if err := id.Check(); err != nil { return trace.Wrap(err) } // when removing a services.CertAuthority also remove any deactivated // services.CertAuthority as well if they exist. err := s.Delete(context.TODO(), backend.Key(authoritiesPrefix, deactivatedPrefix, string(id.Type), id.DomainName)) if err != nil {...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/trust.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/trust.go#L138-L164
go
train
// ActivateCertAuthority moves a CertAuthority from the deactivated list to // the normal list.
func (s *CA) ActivateCertAuthority(id services.CertAuthID) error
// ActivateCertAuthority moves a CertAuthority from the deactivated list to // the normal list. func (s *CA) ActivateCertAuthority(id services.CertAuthID) error
{ item, err := s.Get(context.TODO(), backend.Key(authoritiesPrefix, deactivatedPrefix, string(id.Type), id.DomainName)) if err != nil { if trace.IsNotFound(err) { return trace.BadParameter("can not activate cert authority %q which has not been deactivated", id.DomainName) } return trace.Wrap(err) } certA...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/trust.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/trust.go#L168-L199
go
train
// DeactivateCertAuthority moves a CertAuthority from the normal list to // the deactivated list.
func (s *CA) DeactivateCertAuthority(id services.CertAuthID) error
// DeactivateCertAuthority moves a CertAuthority from the normal list to // the deactivated list. func (s *CA) DeactivateCertAuthority(id services.CertAuthID) error
{ certAuthority, err := s.GetCertAuthority(id, true) if err != nil { if trace.IsNotFound(err) { return trace.NotFound("can not deactivate cert authority %q which does not exist", id.DomainName) } return trace.Wrap(err) } err = s.DeleteCertAuthority(id) if err != nil { return trace.Wrap(err) } value...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/trust.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/trust.go#L203-L221
go
train
// GetCertAuthority returns certificate authority by given id. Parameter loadSigningKeys // controls if signing keys are loaded
func (s *CA) GetCertAuthority(id services.CertAuthID, loadSigningKeys bool, opts ...services.MarshalOption) (services.CertAuthority, error)
// GetCertAuthority returns certificate authority by given id. Parameter loadSigningKeys // controls if signing keys are loaded func (s *CA) GetCertAuthority(id services.CertAuthID, loadSigningKeys bool, opts ...services.MarshalOption) (services.CertAuthority, error)
{ if err := id.Check(); err != nil { return nil, trace.Wrap(err) } item, err := s.Get(context.TODO(), backend.Key(authoritiesPrefix, string(id.Type), id.DomainName)) if err != nil { return nil, trace.Wrap(err) } ca, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority( item.Value, services.Ad...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/local/trust.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/trust.go#L232-L262
go
train
// GetCertAuthorities returns a list of authorities of a given type // loadSigningKeys controls whether signing keys should be loaded or not
func (s *CA) GetCertAuthorities(caType services.CertAuthType, loadSigningKeys bool, opts ...services.MarshalOption) ([]services.CertAuthority, error)
// GetCertAuthorities returns a list of authorities of a given type // loadSigningKeys controls whether signing keys should be loaded or not func (s *CA) GetCertAuthorities(caType services.CertAuthType, loadSigningKeys bool, opts ...services.MarshalOption) ([]services.CertAuthority, error)
{ if err := caType.Check(); err != nil { return nil, trace.Wrap(err) } // Get all items in the bucket. startKey := backend.Key(authoritiesPrefix, string(caType)) result, err := s.GetRange(context.TODO(), startKey, backend.RangeEnd(startKey), backend.NoLimit) if err != nil { return nil, trace.Wrap(err) } ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/session.go#L75-L128
go
train
// newSession creates a new Teleport session with the given remote node // if 'joinSessin' is given, the session will join the existing session // of another user
func newSession(client *NodeClient, joinSession *session.Session, env map[string]string, stdin io.Reader, stdout io.Writer, stderr io.Writer) (*NodeSession, error)
// newSession creates a new Teleport session with the given remote node // if 'joinSessin' is given, the session will join the existing session // of another user func newSession(client *NodeClient, joinSession *session.Session, env map[string]string, stdin io.Reader, stdout io.Writer, stderr io.Writer) (*NodeSess...
{ if stdin == nil { stdin = os.Stdin } if stdout == nil { stdout = os.Stdout } if stderr == nil { stderr = os.Stderr } if env == nil { env = make(map[string]string) } var err error ns := &NodeSession{ env: env, nodeClient: client, stdin: stdin, stdout: stdout, stderr: ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/session.go#L189-L234
go
train
// interactiveSession creates an interactive session on the remote node, executes // the given callback on it, and waits for the session to end
func (ns *NodeSession) interactiveSession(callback interactiveCallback) error
// interactiveSession creates an interactive session on the remote node, executes // the given callback on it, and waits for the session to end func (ns *NodeSession) interactiveSession(callback interactiveCallback) error
{ // determine what kind of a terminal we need termType := os.Getenv("TERM") if termType == "" { termType = teleport.SafeTerminalType } // create the server-side session: sess, err := ns.createServerSession() if err != nil { return trace.Wrap(err) } // allocate terminal on the server: remoteTerm, err := ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/session.go#L237-L283
go
train
// allocateTerminal creates (allocates) a server-side terminal for this session.
func (ns *NodeSession) allocateTerminal(termType string, s *ssh.Session) (io.ReadWriteCloser, error)
// allocateTerminal creates (allocates) a server-side terminal for this session. func (ns *NodeSession) allocateTerminal(termType string, s *ssh.Session) (io.ReadWriteCloser, error)
{ var err error // read the size of the terminal window: tsize := &term.Winsize{ Width: teleport.DefaultTerminalWidth, Height: teleport.DefaultTerminalHeight, } if ns.isTerminalAttached() { tsize, err = term.GetWinsize(0) if err != nil { log.Error(err) } } // ... and request a server-side terminal...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/session.go#L392-L394
go
train
// isTerminalAttached returns true when this session is be controlled by // a real terminal. // It will return False for sessions initiated by the Web client or // for non-interactive sessions (commands)
func (ns *NodeSession) isTerminalAttached() bool
// isTerminalAttached returns true when this session is be controlled by // a real terminal. // It will return False for sessions initiated by the Web client or // for non-interactive sessions (commands) func (ns *NodeSession) isTerminalAttached() bool
{ return ns.stdin == os.Stdin && term.IsTerminal(os.Stdin.Fd()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/session.go#L397-L412
go
train
// runShell executes user's shell on the remote node under an interactive session
func (ns *NodeSession) runShell(callback ShellCreatedCallback) error
// runShell executes user's shell on the remote node under an interactive session func (ns *NodeSession) runShell(callback ShellCreatedCallback) error
{ return ns.interactiveSession(func(s *ssh.Session, shell io.ReadWriteCloser) error { // start the shell on the server: if err := s.Shell(); err != nil { return trace.Wrap(err) } // call the client-supplied callback if callback != nil { exit, err := callback(s, ns.NodeClient().Client, shell) if exi...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/session.go#L416-L484
go
train
// runCommand executes a "exec" request either in interactive mode (with a // TTY attached) or non-intractive mode (no TTY).
func (ns *NodeSession) runCommand(ctx context.Context, cmd []string, callback ShellCreatedCallback, interactive bool) error
// runCommand executes a "exec" request either in interactive mode (with a // TTY attached) or non-intractive mode (no TTY). func (ns *NodeSession) runCommand(ctx context.Context, cmd []string, callback ShellCreatedCallback, interactive bool) error
{ // If stdin is not a terminal, refuse to allocate terminal on the server and // fallback to non-interactive mode if interactive && ns.stdin == os.Stdin && !term.IsTerminal(os.Stdin.Fd()) { interactive = false fmt.Fprintf(os.Stderr, "TTY will not be allocated on the server because stdin is not a terminal\n") ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/session.go#L488-L520
go
train
// watchSignals register UNIX signal handlers and properly terminates a remote shell session // must be called as a goroutine right after a remote shell is created
func (ns *NodeSession) watchSignals(shell io.Writer)
// watchSignals register UNIX signal handlers and properly terminates a remote shell session // must be called as a goroutine right after a remote shell is created func (ns *NodeSession) watchSignals(shell io.Writer)
{ exitSignals := make(chan os.Signal, 1) // catch SIGTERM signal.Notify(exitSignals, syscall.SIGTERM) go func() { defer ns.closer.Close() <-exitSignals }() // Catch Ctrl-C signal ctrlCSignal := make(chan os.Signal, 1) signal.Notify(ctrlCSignal, syscall.SIGINT) go func() { for { <-ctrlCSignal _, er...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/session.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/session.go#L524-L552
go
train
// pipeInOut launches two goroutines: one to pipe the local input into the remote shell, // and another to pipe the output of the remote shell into the local output
func (ns *NodeSession) pipeInOut(shell io.ReadWriteCloser)
// pipeInOut launches two goroutines: one to pipe the local input into the remote shell, // and another to pipe the output of the remote shell into the local output func (ns *NodeSession) pipeInOut(shell io.ReadWriteCloser)
{ // copy from the remote shell to the local output go func() { defer ns.closer.Close() _, err := io.Copy(ns.stdout, shell) if err != nil { log.Errorf(err.Error()) } }() // copy from the local input to the remote shell: go func() { defer ns.closer.Close() buf := make([]byte, 128) for { n, err ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/multiplexer/multiplexer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/multiplexer.go#L66-L80
go
train
// CheckAndSetDefaults verifies configuration and sets defaults
func (c *Config) CheckAndSetDefaults() error
// CheckAndSetDefaults verifies configuration and sets defaults func (c *Config) CheckAndSetDefaults() error
{ if c.Listener == nil { return trace.BadParameter("missing parameter Listener") } if c.Context == nil { c.Context = context.TODO() } if c.ReadDeadline == 0 { c.ReadDeadline = defaults.ReadHeadersTimeout } if c.Clock == nil { c.Clock = clockwork.NewRealClock() } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/multiplexer/multiplexer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/multiplexer.go#L83-L102
go
train
// New returns a new instance of multiplexer
func New(cfg Config) (*Mux, error)
// New returns a new instance of multiplexer func New(cfg Config) (*Mux, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } ctx, cancel := context.WithCancel(cfg.Context) waitContext, waitCancel := context.WithCancel(context.TODO()) return &Mux{ Entry: log.WithFields(log.Fields{ trace.Component: teleport.Component("mx", cfg.ID), }), Config: ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/multiplexer/multiplexer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/multiplexer.go#L164-L188
go
train
// Serve is a blocking function that serves on the listening socket // and accepts requests. Every request is served in a separate goroutine
func (m *Mux) Serve() error
// Serve is a blocking function that serves on the listening socket // and accepts requests. Every request is served in a separate goroutine func (m *Mux) Serve() error
{ defer m.waitCancel() backoffTimer := time.NewTicker(5 * time.Second) defer backoffTimer.Stop() for { conn, err := m.Listener.Accept() if err == nil { if tcpConn, ok := conn.(*net.TCPConn); ok { tcpConn.SetKeepAlive(true) tcpConn.SetKeepAlivePeriod(3 * time.Minute) } go m.detectAndForward(con...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpcserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpcserver.go#L48-L70
go
train
// SendKeepAlives allows node to send a stream of keep alive requests
func (g *GRPCServer) SendKeepAlives(stream proto.AuthService_SendKeepAlivesServer) error
// SendKeepAlives allows node to send a stream of keep alive requests func (g *GRPCServer) SendKeepAlives(stream proto.AuthService_SendKeepAlivesServer) error
{ defer stream.SendAndClose(&empty.Empty{}) auth, err := g.authenticate(stream.Context()) if err != nil { return trail.ToGRPC(err) } g.Debugf("Got heartbeat connection from %v.", auth.User.GetName()) for { keepAlive, err := stream.Recv() if err == io.EOF { g.Debugf("Connection closed.") return nil ...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpcserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpcserver.go#L73-L110
go
train
// WatchEvents returns a new stream of cluster events
func (g *GRPCServer) WatchEvents(watch *proto.Watch, stream proto.AuthService_WatchEventsServer) error
// WatchEvents returns a new stream of cluster events func (g *GRPCServer) WatchEvents(watch *proto.Watch, stream proto.AuthService_WatchEventsServer) error
{ auth, err := g.authenticate(stream.Context()) if err != nil { return trail.ToGRPC(err) } servicesWatch := services.Watch{ Name: auth.User.GetName(), } for _, kind := range watch.Kinds { servicesWatch.Kinds = append(servicesWatch.Kinds, services.WatchKind{ Name: kind.Name, Kind: kind.K...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpcserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpcserver.go#L113-L123
go
train
// UpsertNode upserts node
func (g *GRPCServer) UpsertNode(ctx context.Context, server *services.ServerV2) (*services.KeepAlive, error)
// UpsertNode upserts node func (g *GRPCServer) UpsertNode(ctx context.Context, server *services.ServerV2) (*services.KeepAlive, error)
{ auth, err := g.authenticate(ctx) if err != nil { return nil, trail.ToGRPC(err) } keepAlive, err := auth.UpsertNode(server) if err != nil { return nil, trail.ToGRPC(err) } return keepAlive, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpcserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpcserver.go#L131-L157
go
train
// authenticate extracts authentication context and returns initialized auth server
func (g *GRPCServer) authenticate(ctx context.Context) (*grpcContext, error)
// authenticate extracts authentication context and returns initialized auth server func (g *GRPCServer) authenticate(ctx context.Context) (*grpcContext, error)
{ // HTTPS server expects auth context to be set by the auth middleware authContext, err := g.Authorizer.Authorize(ctx) if err != nil { // propagate connection problem error so we can differentiate // between connection failed and access denied if trace.IsConnectionProblem(err) { return nil, trace.Connect...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpcserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpcserver.go#L160-L171
go
train
// NewGRPCServer returns a new instance of GRPC server
func NewGRPCServer(cfg APIConfig) http.Handler
// NewGRPCServer returns a new instance of GRPC server func NewGRPCServer(cfg APIConfig) http.Handler
{ authServer := &GRPCServer{ APIConfig: cfg, Entry: logrus.WithFields(logrus.Fields{ trace.Component: teleport.Component(teleport.ComponentAuth, teleport.ComponentGRPC), }), httpHandler: NewAPIServer(&cfg), grpcHandler: grpc.NewServer(), } proto.RegisterAuthServiceServer(authServer.grpcHandler, authSer...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpcserver.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpcserver.go#L174-L182
go
train
// ServeHTTP dispatches requests based on the request type
func (g *GRPCServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
// ServeHTTP dispatches requests based on the request type func (g *GRPCServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
{ // magic combo match signifying GRPC request // https://grpc.io/blog/coreos if r.ProtoMajor == 2 && strings.Contains(r.Header.Get("Content-Type"), "application/grpc") { g.grpcHandler.ServeHTTP(w, r) } else { g.httpHandler.ServeHTTP(w, r) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/regular/sites.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/sites.go#L53-L75
go
train
// Start serves a request for "proxysites" custom SSH subsystem. It builds an array of // service.Site structures, and writes it serialized as JSON back to the SSH client
func (t *proxySitesSubsys) Start(sconn *ssh.ServerConn, ch ssh.Channel, req *ssh.Request, ctx *srv.ServerContext) error
// Start serves a request for "proxysites" custom SSH subsystem. It builds an array of // service.Site structures, and writes it serialized as JSON back to the SSH client func (t *proxySitesSubsys) Start(sconn *ssh.ServerConn, ch ssh.Channel, req *ssh.Request, ctx *srv.ServerContext) error
{ log.Debugf("proxysites.start(%v)", ctx) remoteSites := t.srv.proxyTun.GetSites() // build an arary of services.Site structures: retval := make([]services.Site, 0, len(remoteSites)) for _, s := range remoteSites { retval = append(retval, services.Site{ Name: s.GetName(), Status: s.GetSta...
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/multilog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/multilog.go#L49-L55
go
train
// Closer releases connections and resources associated with logs if any
func (m *MultiLog) Close() error
// Closer releases connections and resources associated with logs if any func (m *MultiLog) Close() error
{ var errors []error for _, log := range m.loggers { errors = append(errors, log.Close()) } return trace.NewAggregate(errors...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/multilog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/multilog.go#L58-L64
go
train
// EmitAuditEvent emits audit event
func (m *MultiLog) EmitAuditEvent(event Event, fields EventFields) error
// EmitAuditEvent emits audit event func (m *MultiLog) EmitAuditEvent(event Event, fields EventFields) error
{ var errors []error for _, log := range m.loggers { errors = append(errors, log.EmitAuditEvent(event, fields)) } return trace.NewAggregate(errors...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/multilog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/multilog.go#L67-L73
go
train
// UploadSessionRecording uploads session recording to the audit server
func (m *MultiLog) UploadSessionRecording(rec SessionRecording) error
// UploadSessionRecording uploads session recording to the audit server func (m *MultiLog) UploadSessionRecording(rec SessionRecording) error
{ var errors []error for _, log := range m.loggers { errors = append(errors, log.UploadSessionRecording(rec)) } return trace.NewAggregate(errors...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/multilog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/multilog.go#L79-L85
go
train
// DELETE IN: 2.7.0 // This method is no longer necessary as nodes and proxies >= 2.7.0 // use UploadSessionRecording method. // PostSessionSlice sends chunks of recorded session to the event log
func (m *MultiLog) PostSessionSlice(slice SessionSlice) error
// DELETE IN: 2.7.0 // This method is no longer necessary as nodes and proxies >= 2.7.0 // use UploadSessionRecording method. // PostSessionSlice sends chunks of recorded session to the event log func (m *MultiLog) PostSessionSlice(slice SessionSlice) error
{ var errors []error for _, log := range m.loggers { errors = append(errors, log.PostSessionSlice(slice)) } return trace.NewAggregate(errors...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/multilog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/multilog.go#L92-L100
go
train
// GetSessionChunk returns a reader which can be used to read a byte stream // of a recorded session starting from 'offsetBytes' (pass 0 to start from the // beginning) up to maxBytes bytes. // // If maxBytes > MaxChunkBytes, it gets rounded down to MaxChunkBytes
func (m *MultiLog) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) (data []byte, err error)
// GetSessionChunk returns a reader which can be used to read a byte stream // of a recorded session starting from 'offsetBytes' (pass 0 to start from the // beginning) up to maxBytes bytes. // // If maxBytes > MaxChunkBytes, it gets rounded down to MaxChunkBytes func (m *MultiLog) GetSessionChunk(namespace string, sid...
{ for _, log := range m.loggers { data, err = log.GetSessionChunk(namespace, sid, offsetBytes, maxBytes) if !trace.IsNotImplemented(err) { return data, err } } return data, err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/events/multilog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/multilog.go#L109-L117
go
train
// Returns all events that happen during a session sorted by time // (oldest first). // // after tells to use only return events after a specified cursor Id // // This function is usually used in conjunction with GetSessionReader to // replay recorded session streams.
func (m *MultiLog) GetSessionEvents(namespace string, sid session.ID, after int, fetchPrintEvents bool) (events []EventFields, err error)
// Returns all events that happen during a session sorted by time // (oldest first). // // after tells to use only return events after a specified cursor Id // // This function is usually used in conjunction with GetSessionReader to // replay recorded session streams. func (m *MultiLog) GetSessionEvents(namespace strin...
{ for _, log := range m.loggers { events, err = log.GetSessionEvents(namespace, sid, after, fetchPrintEvents) if !trace.IsNotImplemented(err) { return events, err } } return events, err }