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 { return values[0], nil } return values, nil } return nil, trace.Wrap(err) } values = append(values, val) } }
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 request and then used the // decrypt the response from the server. key, err := secret.NewKey() if err != nil { return nil, trace.Wrap(err) } context, cancel := context.WithCancel(login.Context) rd := &Redirector{ context: context, cancel: cancel, proxyClient: clt.clt, proxyURL: clt.url, SSHLogin: login, mux: http.NewServeMux(), key: key, shortPath: "/" + uuid.New(), responseC: make(chan *auth.SSHLoginResponse, 1), errorC: make(chan error, 1), } // callback is a callback URL communicated to the Teleport proxy, // after SAML/OIDC login, the teleport will redirect user's browser // to this laptop-local URL rd.mux.Handle("/callback", rd.wrapCallback(rd.callback)) // short path is a link-shortener style URL // that will redirect to the Teleport-Proxy supplied address rd.mux.HandleFunc(rd.shortPath, func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, rd.redirectURL.Value(), http.StatusFound) }) return rd, nil }
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.BindAddr) } rd.server = &httptest.Server{ Listener: listener, Config: &http.Server{Handler: rd.mux}, } rd.server.Start() } else { rd.server = httptest.NewServer(rd.mux) } log.Infof("Waiting for response at: %v.", rd.server.URL) // communicate callback redirect URL to the Teleport Proxy u, err := url.Parse(rd.server.URL + "/callback") if err != nil { return trace.Wrap(err) } query := u.Query() query.Set("secret_key", rd.key.String()) u.RawQuery = query.Encode() out, err := rd.proxyClient.PostJSON(rd.Context, rd.proxyClient.Endpoint("webapi", rd.Protocol, "login", "console"), SSOLoginConsoleReq{ RedirectURL: u.String(), PublicKey: rd.PubKey, CertTTL: rd.TTL, ConnectorID: rd.ConnectorID, Compatibility: rd.Compatibility, }) if err != nil { return trace.Wrap(err) } var re *SSOLoginConsoleResponse err = json.Unmarshal(out.Bytes(), &re) if err != nil { return trace.Wrap(err) } // notice late binding of the redirect URL here, it is referenced // in the callback handler, but is known only after the request // is sent to the Teleport Proxy, that's why // redirectURL is a SyncString rd.redirectURL.Set(re.RedirectURL) return nil }
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) } var re *auth.SSHLoginResponse err = json.Unmarshal(plaintext, &re) if err != nil { return nil, trace.BadParameter("failed to decrypt response: in %v, err: %v", r.URL.String(), err) } return re, nil }
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) { http.NotFound(w, r) return } select { case rd.errorC <- err: case <-rd.context.Done(): http.Redirect(w, r, errorURL, http.StatusFound) return } http.Redirect(w, r, errorURL, http.StatusFound) return } select { case rd.responseC <- response: case <-rd.context.Done(): http.Redirect(w, r, errorURL, http.StatusFound) return } http.Redirect(w, r, successURL, http.StatusFound) }) }
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.AWSProductID != "" { features = append(features, fmt.Sprintf("is limited to AWS product ID %q", c.Spec.AWSProductID)) } if c.Spec.AWSAccountID != "" { features = append(features, fmt.Sprintf("is limited to AWS account ID %q", c.Spec.AWSAccountID)) } if len(features) == 0 { return "" } return strings.Join(features, ",") }
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(err.Error()) } if license.Version != V3 { return nil, trace.BadParameter("unsupported version %v, expected version %v", license.Version, V3) } if err := license.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &license, nil }
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 } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", license) } }
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 trace.BadParameter("missing 'HostUUID' parameter") } if cfg.Context == nil { cfg.Context = context.TODO() } if cfg.Clock == nil { cfg.Clock = clockwork.NewRealClock() } return nil }
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 = log.WithFields(log.Fields{ trace.Component: teleport.ComponentReverseTunnelAgent, trace.ComponentFields: log.Fields{ "cluster": cfg.Cluster, }, }) return pool, nil }
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{ agentStateConnecting: 0, agentStateDiscovering: 0, agentStateConnected: 0, agentStateDiscovered: 0, agentStateDisconnected: 0, } for _, a := range agents { countPerState[a.getState()]++ } for state, count := range countPerState { gauge, err := trustedClustersStats.GetMetricWithLabelValues(key.tunnelID, state) if err != nil { m.Warningf("Failed to get gauge: %v.", err) continue } gauge.Set(float64(count)) } if logReport { m.WithFields(log.Fields{"target": key.tunnelID, "stats": countPerState}).Info("Outbound tunnel stats.") } } }
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 len(validAgents) > 0 { m.agents[agentKey] = validAgents } else { delete(m.agents, agentKey) } } }
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 ServerName // from the hostname we're connecting to. if tlsConfig.ServerName == "" { // Make a copy to avoid polluting argument or default. c := tlsConfig.Clone() c.ServerName = hostname tlsConfig = c } conn := tls.Client(plainConn, tlsConfig) errC := make(chan error, 1) go func() { err := conn.Handshake() errC <- err }() select { case err := <-errC: if err != nil { plainConn.Close() return nil, trace.Wrap(err) } case <-ctx.Done(): plainConn.Close() return nil, trace.BadParameter("tls handshake has been cancelled due to timeout") } if tlsConfig.InsecureSkipVerify { return conn, nil } if err := conn.VerifyHostname(tlsConfig.ServerName); err != nil { plainConn.Close() return nil, trace.Wrap(err) } return conn, nil }
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) logins := getLogins(userRoles) acl := userACL{ AuthConnectors: authConnectors, TrustedClusters: trustedClusterAccess, Sessions: sessionAccess, Roles: roleAccess, SSHLogins: logins, } // local user authType := authLocal // check for any SSO identities isSSO := len(user.GetOIDCIdentities()) > 0 || len(user.GetGithubIdentities()) > 0 || len(user.GetSAMLIdentities()) > 0 if isSSO { // SSO user authType = authSSO } return &userContext{ Name: user.GetName(), ACL: acl, AuthType: authType, Version: teleport.Version, }, nil }
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(c.TLS.Certificates) == 0 { return trace.BadParameter("missing parameter TLS.Certificates") } if c.AccessPoint == nil { return trace.BadParameter("missing parameter AccessPoint") } if c.Component == "" { c.Component = teleport.ComponentAuth } return nil }
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 request assuming TLS client authentication // adds authentication information to the context // and passes it to the API server authMiddleware := &AuthMiddleware{ AccessPoint: cfg.AccessPoint, AcceptedUsage: cfg.AcceptedUsage, } authMiddleware.Wrap(NewGRPCServer(cfg.APIConfig)) // Wrap sets the next middleware in chain to the authMiddleware limiter.WrapHandle(authMiddleware) // force client auth if given cfg.TLS.ClientAuth = tls.VerifyClientCertIfGiven cfg.TLS.NextProtos = []string{http2.NextProtoTLS} server := &TLSServer{ TLSServerConfig: cfg, Server: &http.Server{ Handler: limiter, }, Entry: logrus.WithFields(logrus.Fields{ trace.Component: cfg.Component, }), } server.TLS.GetConfigForClient = server.GetConfigForClient return server, nil }
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("access is denied") } } } // update client certificate pool based on currently trusted TLS // certificate authorities. // TODO(klizhentas) drop connections of the TLS cert authorities // that are not trusted pool, err := ClientCertPool(t.AccessPoint, clusterName) if err != nil { var ourClusterName string if clusterName, err := t.AccessPoint.GetClusterName(); err == nil { ourClusterName = clusterName.GetClusterName() } t.Errorf("Failed to retrieve client pool. Client cluster %v, target cluster %v, error: %v.", clusterName, ourClusterName, trace.DebugReport(err)) // this falls back to the default config return nil, nil } tlsCopy := t.TLS.Clone() tlsCopy.ClientCAs = pool for _, cert := range tlsCopy.Certificates { t.Debugf("Server certificate %v.", TLSCertInfo(&cert)) } return tlsCopy, nil }
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") } localClusterName, err := a.AccessPoint.GetClusterName() if err != nil { return nil, trace.Wrap(err) } // with no client authentication in place, middleware // assumes not-privileged Nop role. // it theoretically possible to use bearer token auth even // for connections without auth, but this is not active use-case // therefore it is not allowed to reduce scope if len(peers) == 0 { return BuiltinRole{ GetClusterConfig: a.AccessPoint.GetClusterConfig, Role: teleport.RoleNop, Username: string(teleport.RoleNop), ClusterName: localClusterName.GetClusterName(), }, nil } clientCert := peers[0] certClusterName, err := tlsca.ClusterName(clientCert.Issuer) if err != nil { log.Warnf("Failed to parse client certificate %v.", err) return nil, trace.AccessDenied("access denied: invalid client certificate") } identity, err := tlsca.FromSubject(clientCert.Subject) if err != nil { return nil, trace.Wrap(err) } // If there is any restriction on the certificate usage // reject the API server request. This is done so some classes // of certificates issued for kubernetes usage by proxy, can not be used // against auth server. Later on we can extend more // advanced cert usage, but for now this is the safest option. if len(identity.Usage) != 0 && !utils.StringSlicesEqual(a.AcceptedUsage, identity.Usage) { log.Warningf("Restricted certificate of user %q with usage %v rejected while accessing the auth endpoint with acceptable usage %v.", identity.Username, identity.Usage, a.AcceptedUsage) return nil, trace.AccessDenied("access denied: invalid client certificate") } // this block assumes interactive user from remote cluster // based on the remote certificate authority cluster name encoded in // x509 organization name. This is a safe check because: // 1. Trust and verification is established during TLS handshake // by creating a cert pool constructed of trusted certificate authorities // 2. Remote CAs are not allowed to have the same cluster name // as the local certificate authority if certClusterName != localClusterName.GetClusterName() { // make sure that this user does not have system role // the local auth server can not truste remote servers // to issue certificates with system roles (e.g. Admin), // to get unrestricted access to the local cluster systemRole := findSystemRole(identity.Groups) if systemRole != nil { return RemoteBuiltinRole{ Role: *systemRole, Username: identity.Username, ClusterName: certClusterName, }, nil } return RemoteUser{ ClusterName: certClusterName, Username: identity.Username, Principals: identity.Principals, KubernetesGroups: identity.KubernetesGroups, RemoteRoles: identity.Groups, }, nil } // code below expects user or service from local cluster, to distinguish between // interactive users and services (e.g. proxies), the code below // checks for presence of system roles issued in certificate identity systemRole := findSystemRole(identity.Groups) // in case if the system role is present, assume this is a service // agent, e.g. Proxy, connecting to the cluster if systemRole != nil { return BuiltinRole{ GetClusterConfig: a.AccessPoint.GetClusterConfig, Role: *systemRole, Username: identity.Username, ClusterName: localClusterName.GetClusterName(), }, nil } // otherwise assume that is a local role, no need to pass the roles // as it will be fetched from the local database return LocalUser{ Username: identity.Username, }, nil }
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, user)) a.Handler.ServeHTTP(w, requestWithContext) }
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, services.SkipValidation()) if err != nil { return nil, trace.Wrap(err) } authorities = append(authorities, hostCAs...) authorities = append(authorities, userCAs...) } else { hostCA, err := client.GetCertAuthority( services.CertAuthID{Type: services.HostCA, DomainName: clusterName}, false, services.SkipValidation()) if err != nil { return nil, trace.Wrap(err) } userCA, err := client.GetCertAuthority( services.CertAuthID{Type: services.UserCA, DomainName: clusterName}, false, services.SkipValidation()) if err != nil { return nil, trace.Wrap(err) } authorities = append(authorities, hostCA) authorities = append(authorities, userCA) } for _, auth := range authorities { for _, keyPair := range auth.GetTLSKeyPairs() { cert, err := tlsca.ParseCertificatePEM(keyPair.Cert) if err != nil { return nil, trace.Wrap(err) } log.Debugf("ClientCertPool -> %v", CertInfo(cert)) pool.AddCert(cert) } } return pool, nil }
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 !fileExists(configFilePath) { log.Info("not using a config file") return nil, nil } log.Debug("reading config file: ", configFilePath) return ReadFromFile(configFilePath) }
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.NodeName, &cfg.Hostname) // apply "advertise_ip" setting: advertiseIP := fc.AdvertiseIP if advertiseIP != "" { if _, _, err := utils.ParseAdvertiseAddr(advertiseIP); err != nil { return trace.Wrap(err) } cfg.AdvertiseIP = advertiseIP } cfg.PIDFile = fc.PIDFile // config file has auth servers in there? if len(fc.AuthServers) > 0 { cfg.AuthServers = make([]utils.NetAddr, 0, len(fc.AuthServers)) for _, as := range fc.AuthServers { addr, err := utils.ParseHostPortAddr(as, defaults.AuthListenPort) if err != nil { return trace.Wrap(err) } if err != nil { return trace.Errorf("cannot parse auth server address: '%v'", as) } cfg.AuthServers = append(cfg.AuthServers, *addr) } } cfg.ApplyToken(fc.AuthToken) if fc.Global.DataDir != "" { cfg.DataDir = fc.Global.DataDir cfg.Auth.StorageConfig.Params["path"] = cfg.DataDir } // if a backend is specified, override the defaults if fc.Storage.Type != "" { cfg.Auth.StorageConfig = fc.Storage // backend is specified, but no path is set, set a reasonable default _, pathSet := cfg.Auth.StorageConfig.Params[defaults.BackendPath] if (cfg.Auth.StorageConfig.Type == dir.GetName() || cfg.Auth.StorageConfig.Type == lite.GetName()) && !pathSet { if cfg.Auth.StorageConfig.Params == nil { cfg.Auth.StorageConfig.Params = make(backend.Params) } cfg.Auth.StorageConfig.Params[defaults.BackendPath] = filepath.Join(cfg.DataDir, defaults.BackendDir) } } else { // bolt backend is deprecated, but is picked if it was setup before exists, err := boltbk.Exists(cfg.DataDir) if err != nil { return trace.Wrap(err) } if exists { cfg.Auth.StorageConfig.Type = boltbk.GetName() cfg.Auth.StorageConfig.Params = backend.Params{defaults.BackendPath: cfg.DataDir} } else { cfg.Auth.StorageConfig.Type = dir.GetName() cfg.Auth.StorageConfig.Params = backend.Params{defaults.BackendPath: filepath.Join(cfg.DataDir, defaults.BackendDir)} } } // apply logger settings switch fc.Logger.Output { case "": break // not set case "stderr", "error", "2": log.SetOutput(os.Stderr) case "stdout", "out", "1": log.SetOutput(os.Stdout) case teleport.Syslog: err := utils.SwitchLoggingtoSyslog() if err != nil { // this error will go to stderr log.Errorf("Failed to switch logging to syslog: %v.", err) } default: // assume it's a file path: logFile, err := os.Create(fc.Logger.Output) if err != nil { return trace.Wrap(err, "failed to create the log file") } log.SetOutput(logFile) } switch strings.ToLower(fc.Logger.Severity) { case "": break // not set case "info": log.SetLevel(log.InfoLevel) case "err", "error": log.SetLevel(log.ErrorLevel) case teleport.DebugLevel: log.SetLevel(log.DebugLevel) case "warn", "warning": log.SetLevel(log.WarnLevel) default: return trace.BadParameter("unsupported logger severity: '%v'", fc.Logger.Severity) } // apply cache policy for node and proxy cachePolicy, err := fc.CachePolicy.Parse() if err != nil { return trace.Wrap(err) } cfg.CachePolicy = *cachePolicy // Apply (TLS) cipher suites and (SSH) ciphers, KEX algorithms, and MAC // algorithms. if len(fc.CipherSuites) > 0 { cipherSuites, err := utils.CipherSuiteMapping(fc.CipherSuites) if err != nil { return trace.Wrap(err) } cfg.CipherSuites = cipherSuites } if fc.Ciphers != nil { cfg.Ciphers = fc.Ciphers } if fc.KEXAlgorithms != nil { cfg.KEXAlgorithms = fc.KEXAlgorithms } if fc.MACAlgorithms != nil { cfg.MACAlgorithms = fc.MACAlgorithms } // Read in how nodes will validate the CA. if fc.CAPin != "" { cfg.CAPin = fc.CAPin } // apply connection throttling: limiters := []*limiter.LimiterConfig{ &cfg.SSH.Limiter, &cfg.Auth.Limiter, &cfg.Proxy.Limiter, } for _, l := range limiters { if fc.Limits.MaxConnections > 0 { l.MaxConnections = fc.Limits.MaxConnections } if fc.Limits.MaxUsers > 0 { l.MaxNumberOfUsers = fc.Limits.MaxUsers } for _, rate := range fc.Limits.Rates { l.Rates = append(l.Rates, limiter.Rate{ Period: rate.Period, Average: rate.Average, Burst: rate.Burst, }) } } // Apply configuration for "auth_service", "proxy_service", and // "ssh_service" if it's enabled. if fc.Auth.Enabled() { err = applyAuthConfig(fc, cfg) if err != nil { return trace.Wrap(err) } } if fc.Proxy.Enabled() { err = applyProxyConfig(fc, cfg) if err != nil { return trace.Wrap(err) } } if fc.SSH.Enabled() { err = applySSHConfig(fc, cfg) if err != nil { return trace.Wrap(err) } } return nil }
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.ProxyProtocol, true) if err != nil { return trace.Wrap(err) } if fc.Auth.ListenAddress != "" { addr, err := utils.ParseHostPortAddr(fc.Auth.ListenAddress, int(defaults.AuthListenPort)) if err != nil { return trace.Wrap(err) } cfg.Auth.SSHAddr = *addr cfg.AuthServers = append(cfg.AuthServers, *addr) } // DELETE IN: 2.7.0 // We have converted this warning to error if fc.Auth.DynamicConfig != nil { warningMessage := "Dynamic configuration is no longer supported. Refer to " + "Teleport documentation for more details: " + "http://gravitational.com/teleport/docs/admin-guide" return trace.BadParameter(warningMessage) } // INTERNAL: Authorities (plus Roles) and ReverseTunnels don't follow the // same pattern as the rest of the configuration (they are not configuration // singletons). However, we need to keep them around while Telekube uses them. for _, authority := range fc.Auth.Authorities { ca, role, err := authority.Parse() if err != nil { return trace.Wrap(err) } cfg.Auth.Authorities = append(cfg.Auth.Authorities, ca) cfg.Auth.Roles = append(cfg.Auth.Roles, role) } for _, t := range fc.Auth.ReverseTunnels { tun, err := t.ConvertAndValidate() if err != nil { return trace.Wrap(err) } cfg.ReverseTunnels = append(cfg.ReverseTunnels, tun) } if len(fc.Auth.PublicAddr) != 0 { addrs, err := fc.Auth.PublicAddr.Addrs(defaults.AuthListenPort) if err != nil { return trace.Wrap(err) } cfg.Auth.PublicAddrs = addrs } // DELETE IN: 2.4.0 if len(fc.Auth.TrustedClusters) > 0 { warningMessage := "Configuring Trusted Clusters using file configuration has " + "been deprecated, Trusted Clusters must now be configured using resources. " + "Existing Trusted Cluster relationships will be maintained, but you will " + "not be able to add or remove Trusted Clusters using file configuration " + "anymore. Refer to Teleport documentation for more details: " + "http://gravitational.com/teleport/docs/admin-guide" log.Warnf(warningMessage) } // read in cluster name from file configuration and create services.ClusterName cfg.Auth.ClusterName, err = fc.Auth.ClusterName.Parse() if err != nil { return trace.Wrap(err) } // read in static tokens from file configuration and create services.StaticTokens if fc.Auth.StaticTokens != nil { cfg.Auth.StaticTokens, err = fc.Auth.StaticTokens.Parse() if err != nil { return trace.Wrap(err) } } // read in and set authentication preferences if fc.Auth.Authentication != nil { authPreference, oidcConnector, err := fc.Auth.Authentication.Parse() if err != nil { return trace.Wrap(err) } cfg.Auth.Preference = authPreference // DELETE IN: 2.4.0 if oidcConnector != nil { warningMessage := "Configuring OIDC connectors using file configuration is " + "no longer supported, OIDC connectors must be configured using resources. " + "Existing OIDC connectors will not be removed but you will not be able to " + "add, remove, or update them using file configuration. Refer to Teleport " + "documentation for more details: " + "http://gravitational.com/teleport/docs/admin-guide" log.Warnf(warningMessage) } } auditConfig, err := services.AuditConfigFromObject(fc.Storage.Params) if err != nil { return trace.Wrap(err) } auditConfig.Type = fc.Storage.Type // Set cluster-wide configuration from file configuration. cfg.Auth.ClusterConfig, err = services.NewClusterConfig(services.ClusterConfigSpecV3{ SessionRecording: fc.Auth.SessionRecording, ProxyChecksHostKeys: fc.Auth.ProxyChecksHostKeys, Audit: *auditConfig, ClientIdleTimeout: fc.Auth.ClientIdleTimeout, DisconnectExpiredCert: fc.Auth.DisconnectExpiredCert, KeepAliveInterval: fc.Auth.KeepAliveInterval, KeepAliveCountMax: fc.Auth.KeepAliveCountMax, }) if err != nil { return trace.Wrap(err) } // read in and set the license file path (not used in open-source version) licenseFile := fc.Auth.LicenseFile if licenseFile != "" { if filepath.IsAbs(licenseFile) { cfg.Auth.LicenseFile = licenseFile } else { cfg.Auth.LicenseFile = filepath.Join(cfg.DataDir, licenseFile) } } return nil }
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 { return trace.Wrap(err) } cfg.Proxy.SSHAddr = *addr } if fc.Proxy.WebAddr != "" { addr, err := utils.ParseHostPortAddr(fc.Proxy.WebAddr, int(defaults.HTTPListenPort)) if err != nil { return trace.Wrap(err) } cfg.Proxy.WebAddr = *addr } if fc.Proxy.TunAddr != "" { addr, err := utils.ParseHostPortAddr(fc.Proxy.TunAddr, int(defaults.SSHProxyTunnelListenPort)) if err != nil { return trace.Wrap(err) } cfg.Proxy.ReverseTunnelListenAddr = *addr } if fc.Proxy.KeyFile != "" { if !fileExists(fc.Proxy.KeyFile) { return trace.Errorf("https key does not exist: %s", fc.Proxy.KeyFile) } cfg.Proxy.TLSKey = fc.Proxy.KeyFile } if fc.Proxy.CertFile != "" { if !fileExists(fc.Proxy.CertFile) { return trace.Errorf("https cert does not exist: %s", fc.Proxy.CertFile) } // read in certificate chain from disk certificateChainBytes, err := utils.ReadPath(fc.Proxy.CertFile) if err != nil { return trace.Wrap(err) } // parse certificate chain into []*x509.Certificate certificateChain, err := utils.ReadCertificateChain(certificateChainBytes) if err != nil { return trace.Wrap(err) } // if starting teleport with a self signed certificate, print a warning, and // then take whatever was passed to us. otherwise verify the certificate // chain from leaf to root so browsers don't complain. if utils.IsSelfSigned(certificateChain) { warningMessage := "Starting Teleport with a self-signed TLS certificate, this is " + "not safe for production clusters. Using a self-signed certificate opens " + "Teleport users to Man-in-the-Middle attacks." log.Warnf(warningMessage) } else { if err := utils.VerifyCertificateChain(certificateChain); err != nil { return trace.BadParameter("unable to verify HTTPS certificate chain in %v: %s", fc.Proxy.CertFile, utils.UserMessageFromError(err)) } } cfg.Proxy.TLSCert = fc.Proxy.CertFile } // apply kubernetes proxy config, by default kube proxy is disabled if fc.Proxy.Kube.Configured() { cfg.Proxy.Kube.Enabled = fc.Proxy.Kube.Enabled() } if fc.Proxy.Kube.KubeconfigFile != "" { cfg.Proxy.Kube.KubeconfigPath = fc.Proxy.Kube.KubeconfigFile } if fc.Proxy.Kube.ListenAddress != "" { addr, err := utils.ParseHostPortAddr(fc.Proxy.Kube.ListenAddress, int(defaults.KubeProxyListenPort)) if err != nil { return trace.Wrap(err) } cfg.Proxy.Kube.ListenAddr = *addr } if len(fc.Proxy.Kube.PublicAddr) != 0 { addrs, err := fc.Proxy.Kube.PublicAddr.Addrs(defaults.KubeProxyListenPort) if err != nil { return trace.Wrap(err) } cfg.Proxy.Kube.PublicAddrs = addrs } if len(fc.Proxy.PublicAddr) != 0 { addrs, err := fc.Proxy.PublicAddr.Addrs(defaults.HTTPListenPort) if err != nil { return trace.Wrap(err) } cfg.Proxy.PublicAddrs = addrs } if len(fc.Proxy.SSHPublicAddr) != 0 { addrs, err := fc.Proxy.SSHPublicAddr.Addrs(defaults.SSHProxyListenPort) if err != nil { return trace.Wrap(err) } cfg.Proxy.SSHPublicAddrs = addrs } if len(fc.Proxy.TunnelPublicAddr) != 0 { addrs, err := fc.Proxy.TunnelPublicAddr.Addrs(defaults.SSHProxyTunnelListenPort) if err != nil { return trace.Wrap(err) } cfg.Proxy.TunnelPublicAddrs = addrs } return 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.SSH.Labels[k] = v } } if fc.SSH.Commands != nil { cfg.SSH.CmdLabels = make(services.CommandLabels) for _, cmdLabel := range fc.SSH.Commands { cfg.SSH.CmdLabels[cmdLabel.Name] = &services.CommandLabelV2{ Period: services.NewDuration(cmdLabel.Period), Command: cmdLabel.Command, Result: "", } } } if fc.SSH.Namespace != "" { cfg.SSH.Namespace = fc.SSH.Namespace } if fc.SSH.PermitUserEnvironment { cfg.SSH.PermitUserEnvironment = true } if fc.SSH.PAM != nil { cfg.SSH.PAM = fc.SSH.PAM.Parse() // If PAM is enabled, make sure that Teleport was built with PAM support // and the PAM library was found at runtime. if cfg.SSH.PAM.Enabled { if !pam.BuildHasPAM() { errorMessage := "Unable to start Teleport: PAM was enabled in file configuration but this \n" + "Teleport binary was built without PAM support. To continue either download a \n" + "Teleport binary build with PAM support from https://gravitational.com/teleport \n" + "or disable PAM in file configuration." return trace.BadParameter(errorMessage) } if !pam.SystemHasPAM() { errorMessage := "Unable to start Teleport: PAM was enabled in file configuration but this \n" + "system does not have the needed PAM library installed. To continue either \n" + "install libpam or disable PAM in file configuration." return trace.BadParameter(errorMessage) } } } if len(fc.SSH.PublicAddr) != 0 { addrs, err := fc.SSH.PublicAddr.Addrs(defaults.SSHServerListenPort) if err != nil { return trace.Wrap(err) } cfg.SSH.PublicAddrs = addrs } return nil }
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.BadParameter("no clustername provided") } // create a new certificate authority ca := services.NewCertAuthority( services.UserCA, clusterName, nil, [][]byte{ssh.MarshalAuthorizedKey(pubkey)}, nil) // transform old allowed logins into roles role := services.RoleForCertAuthority(ca) role.SetLogins(services.Allow, allowedLogins) ca.AddRole(role.GetName()) return ca, role, nil }
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.ParseQuery(comment) if err != nil { return nil, nil, trace.BadParameter("invalid key comment: '%s'", comment) } authType := services.CertAuthType(teleportOpts.Get("type")) if authType != services.HostCA && authType != services.UserCA { return nil, nil, trace.BadParameter("unsupported CA type: '%s'", authType) } if len(options) == 0 { return nil, nil, trace.BadParameter("key without cluster_name") } const prefix = "*." domainName := strings.TrimPrefix(options[0], prefix) v1 := &services.CertAuthorityV1{ AllowedLogins: utils.CopyStrings(allowedLogins), DomainName: domainName, Type: authType, CheckingKeys: [][]byte{ssh.MarshalAuthorizedKey(pubKey)}, } ca, role := services.ConvertV1CertAuthority(v1) return ca, role, nil }
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 = append(allowedLogins, login) } } // open the key file for this cluster: log.Debugf("reading trusted cluster key file %s", tc.KeyFile) if tc.KeyFile == "" { return trace.Errorf("key_file is missing for a trusted cluster") } f, err := os.Open(tc.KeyFile) if err != nil { return trace.Errorf("reading trusted cluster keys: %v", err) } defer f.Close() // read the keyfile for this cluster and get trusted CA keys: var authorities []services.CertAuthority var roles []services.Role scanner := bufio.NewScanner(f) for line := 0; scanner.Scan(); { ca, role, err := parseCAKey(scanner.Bytes(), allowedLogins) if err != nil { return trace.BadParameter("%s:L%d. %v", tc.KeyFile, line, err) } if ca.GetType() == services.UserCA && len(allowedLogins) == 0 && len(tc.TunnelAddr) > 0 { return trace.BadParameter("trusted cluster '%s' needs allow_logins parameter", ca.GetClusterName()) } authorities = append(authorities, ca) if role != nil { roles = append(roles, role) } } conf.Auth.Authorities = append(conf.Auth.Authorities, authorities...) conf.Auth.Roles = append(conf.Auth.Roles, roles...) clusterName := authorities[0].GetClusterName() // parse "tunnel_addr" var tunnelAddresses []string for _, ta := range strings.Split(tc.TunnelAddr, ",") { ta := strings.TrimSpace(ta) if ta == "" { continue } addr, err := utils.ParseHostPortAddr(ta, defaults.SSHProxyTunnelListenPort) if err != nil { return trace.Wrap(err, "Invalid tunnel address '%s' for cluster '%s'. Expect host:port format", ta, clusterName) } tunnelAddresses = append(tunnelAddresses, addr.FullAddress()) } if len(tunnelAddresses) > 0 { conf.ReverseTunnels = append(conf.ReverseTunnels, services.NewReverseTunnel(clusterName, tunnelAddresses)) } } return nil }
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 it and override the config file if clf.ConfigString != "" { fileConf, err = ReadFromString(clf.ConfigString) if err != nil { return trace.Wrap(err) } } // apply command line --debug flag to override logger severity if fileConf != nil && clf.Debug { fileConf.Logger.Severity = teleport.DebugLevel } if err = ApplyFileConfig(fileConf, cfg); err != nil { return trace.Wrap(err) } // Apply diagnostic address flag. if clf.DiagnosticAddr != "" { addr, err := utils.ParseAddr(clf.DiagnosticAddr) if err != nil { return trace.Wrap(err, "failed to parse diag-addr") } cfg.DiagnosticAddr = *addr } // apply --insecure-no-tls flag: if clf.DisableTLS { cfg.Proxy.DisableTLS = clf.DisableTLS } // apply --debug flag to config: if clf.Debug { cfg.Console = ioutil.Discard cfg.Debug = clf.Debug } // apply --roles flag: if clf.Roles != "" { if err := validateRoles(clf.Roles); err != nil { return trace.Wrap(err) } cfg.SSH.Enabled = strings.Index(clf.Roles, defaults.RoleNode) != -1 cfg.Auth.Enabled = strings.Index(clf.Roles, defaults.RoleAuthService) != -1 cfg.Proxy.Enabled = strings.Index(clf.Roles, defaults.RoleProxy) != -1 } // apply --auth-server flag: if clf.AuthServerAddr != "" { if cfg.Auth.Enabled { log.Warnf("not starting the local auth service. --auth-server flag tells to connect to another auth server") cfg.Auth.Enabled = false } addr, err := utils.ParseHostPortAddr(clf.AuthServerAddr, int(defaults.AuthListenPort)) if err != nil { return trace.Wrap(err) } log.Infof("Using auth server: %v", addr.FullAddress()) cfg.AuthServers = []utils.NetAddr{*addr} } // apply --name flag: if clf.NodeName != "" { cfg.Hostname = clf.NodeName } // apply --pid-file flag if clf.PIDFile != "" { cfg.PIDFile = clf.PIDFile } // apply --token flag: cfg.ApplyToken(clf.AuthToken) // Apply flags used for the node to validate the Auth Server. if clf.CAPin != "" { cfg.CAPin = clf.CAPin } // apply --listen-ip flag: if clf.ListenIP != nil { applyListenIP(clf.ListenIP, cfg) } // --advertise-ip flag if clf.AdvertiseIP != "" { if _, _, err := utils.ParseAdvertiseAddr(clf.AdvertiseIP); err != nil { return trace.Wrap(err) } cfg.AdvertiseIP = clf.AdvertiseIP } // apply --labels flag if err = parseLabels(clf.Labels, &cfg.SSH); err != nil { return trace.Wrap(err) } // --pid-file: if clf.PIDFile != "" { cfg.PIDFile = clf.PIDFile } // auth_servers not configured, but the 'auth' is enabled (auth is on localhost)? if len(cfg.AuthServers) == 0 && cfg.Auth.Enabled { cfg.AuthServers = append(cfg.AuthServers, cfg.Auth.SSHAddr) } // add data_dir to the backend config: if cfg.Auth.StorageConfig.Params == nil { cfg.Auth.StorageConfig.Params = backend.Params{} } cfg.Auth.StorageConfig.Params["data_dir"] = cfg.DataDir // command line flag takes precedence over file config if clf.PermitUserEnvironment { cfg.SSH.PermitUserEnvironment = true } return nil }
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]string, 0) } // see which labels are actually command labels: for key, value := range lmap { cmdLabel, err := isCmdLabelSpec(value) if err != nil { return trace.Wrap(err) } if cmdLabel != nil { sshConf.CmdLabels[key] = cmdLabel } else { sshConf.Labels[key] = value } } return nil }
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(invalidSpecError) } periodSpec := spec[:idx] period, err := time.ParseDuration(periodSpec) if err != nil { return nil, trace.Wrap(invalidSpecError) } cmdSpec := spec[idx+1:] if len(cmdSpec) < 1 { return nil, trace.Wrap(invalidSpecError) } var openQuote bool = false return &services.CommandLabelV2{ Period: services.NewDuration(period), Command: strings.FieldsFunc(cmdSpec, func(c rune) bool { if c == '"' { openQuote = !openQuote } return unicode.IsSpace(c) && !openQuote }), }, nil } // not a valid spec return nil, nil }
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 for _, id := range user.GetOIDCIdentities() { if err := id.Check(); err != nil { return "", trace.Wrap(err) } if _, err := s.GetOIDCConnector(id.ConnectorID, false); err != nil { return "", trace.Wrap(err) } } for _, id := range user.GetSAMLIdentities() { if err := id.Check(); err != nil { return "", trace.Wrap(err) } if _, err := s.GetSAMLConnector(id.ConnectorID, false); err != nil { return "", trace.Wrap(err) } } // TODO(rjones): TOCTOU, instead try to create signup token for user and fail // when unable to. _, err := s.GetPasswordHash(user.GetName()) if err == nil { return "", trace.BadParameter("user '%s' already exists", user.GetName()) } token, err := utils.CryptoRandomHex(TokenLenBytes) if err != nil { return "", trace.Wrap(err) } // This OTP secret and QR code are never actually used. The OTP secret and // QR code are rotated every time the signup link is show to the user, see // the "GetSignupTokenData" function for details on why this is done. We // generate a OTP token because it causes no harm and makes tests easier to // write. accountName := user.GetName() + "@" + s.AuthServiceName otpKey, otpQRCode, err := s.initializeTOTP(accountName) if err != nil { return "", trace.Wrap(err) } // create and upsert signup token tokenData := services.SignupToken{ Token: token, User: userv1, OTPKey: otpKey, OTPQRCode: otpQRCode, } if ttl == 0 || ttl > defaults.MaxSignupTokenTTL { ttl = defaults.SignupTokenTTL } err = s.UpsertSignupToken(token, tokenData, ttl) if err != nil { return "", trace.Wrap(err) } log.Infof("[AUTH API] created the signup token for %q", user) return token, nil }
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(err) } png.Encode(&otpQRBuf, otpImage) return otpKey.Secret(), otpQRBuf.Bytes(), nil }
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) (*services.SignupToken, error)
{ 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.initializeTOTP(accountName) if err != nil { return nil, trace.Wrap(err) } // Upsert token into backend. err = s.UpsertSignupToken(token, *st, st.Expires.Sub(s.clock.Now())) if err != nil { return nil, trace.Wrap(err) } return st, nil }
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, err := s.rotateAndFetchSignupToken(token) if err != nil { return "", nil, trace.Wrap(err) } // TODO(rjones): Remove this check and use compare and swap in the Create* // functions below. It's a TOCTOU bug in the making: // https://en.wikipedia.org/wiki/Time_of_check_to_time_of_use _, err = s.GetPasswordHash(st.User.Name) if err == nil { return "", nil, trace.Errorf("user %q already exists", st.User.Name) } return st.User.Name, st.OTPQRCode, nil }
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(tokenData.User.Name, otpToken) if err != nil { log.Debugf("failed to validate a token: %v", err) return nil, trace.AccessDenied("failed to validate a token") } err = s.UpsertPassword(tokenData.User.Name, []byte(password)) if err != nil { return nil, trace.Wrap(err) } // create services.User and services.WebSession webSession, err := s.createUserAndSession(tokenData) if err != nil { return nil, trace.Wrap(err) } return webSession, nil }
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: %v", err) return nil, trace.AccessDenied("expired or incorrect signup token") } err = s.UpsertPassword(tokenData.User.Name, []byte(password)) if err != nil { return nil, trace.Wrap(err) } // create services.User and services.WebSession webSession, err := s.createUserAndSession(tokenData) if err != nil { return nil, trace.Wrap(err) } return webSession, nil }
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, error)
{ // 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.AdminRoleName}) } // upsert user into the backend err := a.UpsertUser(user) if err != nil { return nil, trace.Wrap(err) } log.Infof("[AUTH] Created user: %v", user) // remove the token once the user has been created err = a.DeleteSignupToken(stoken.Token) if err != nil { return nil, trace.Wrap(err) } // create and upsert a new web session into the backend sess, err := a.NewWebSession(user.GetName()) if err != nil { return nil, trace.Wrap(err) } err = a.UpsertWebSession(user.GetName(), sess) if err != nil { return nil, trace.Wrap(err) } return sess, nil }
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, DefaultDefinitions) }
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.BadParameter(err.Error()) } } else { err = utils.UnmarshalWithSchema(GetStaticTokensSchema(""), &staticTokens, bytes) if err != nil { return nil, trace.BadParameter(err.Error()) } } err = staticTokens.CheckAndSetDefaults() if err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { staticTokens.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { staticTokens.SetExpiry(cfg.Expires) } return &staticTokens, nil }
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 } return utils.FastMarshal(resource) default: return nil, trace.BadParameter("unrecognized resource version %T", c) } }
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: ca.Expiry(), } _, err = s.Create(context.TODO(), item) if err != nil { if trace.IsAlreadyExists(err) { return trace.AlreadyExists("cluster %q already exists", ca.GetName()) } return trace.Wrap(err) } return nil }
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: ca.Expiry(), ID: ca.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
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, Expires: new.Expiry(), } existingValue, err := services.GetCertAuthorityMarshaler().MarshalCertAuthority(existing) if err != nil { return trace.Wrap(err) } existingItem := backend.Item{ Key: backend.Key(authoritiesPrefix, string(existing.GetType()), existing.GetName()), Value: existingValue, Expires: existing.Expiry(), } _, err = s.CompareAndSwap(context.TODO(), existingItem, newItem) if err != nil { if trace.IsCompareFailed(err) { return trace.CompareFailed("cluster %v settings have been updated, try again", new.GetName()) } return trace.Wrap(err) } return nil }
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 { if !trace.IsNotFound(err) { return trace.Wrap(err) } } err = s.Delete(context.TODO(), backend.Key(authoritiesPrefix, string(id.Type), id.DomainName)) if err != nil { return trace.Wrap(err) } return 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) } certAuthority, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority( item.Value, services.WithResourceID(item.ID), services.WithExpires(item.Expires)) if err != nil { return trace.Wrap(err) } err = s.UpsertCertAuthority(certAuthority) if err != nil { return trace.Wrap(err) } err = s.Delete(context.TODO(), backend.Key(authoritiesPrefix, deactivatedPrefix, string(id.Type), id.DomainName)) if err != nil { return trace.Wrap(err) } return nil }
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, err := services.GetCertAuthorityMarshaler().MarshalCertAuthority(certAuthority) if err != nil { return trace.Wrap(err) } item := backend.Item{ Key: backend.Key(authoritiesPrefix, deactivatedPrefix, string(id.Type), id.DomainName), Value: value, Expires: certAuthority.Expiry(), ID: certAuthority.GetResourceID(), } _, err = s.Put(context.TODO(), item) if err != nil { return trace.Wrap(err) } return nil }
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.AddOptions(opts, services.WithResourceID(item.ID), services.WithExpires(item.Expires))...) if err != nil { return nil, trace.Wrap(err) } if err := ca.Check(); err != nil { return nil, trace.Wrap(err) } setSigningKeys(ca, loadSigningKeys) return ca, nil }
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) } // Marshal values into a []services.CertAuthority slice. cas := make([]services.CertAuthority, len(result.Items)) for i, item := range result.Items { ca, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority( item.Value, services.AddOptions(opts, services.WithResourceID(item.ID), services.WithExpires(item.Expires))...) if err != nil { return nil, trace.Wrap(err) } if err := ca.Check(); err != nil { return nil, trace.Wrap(err) } setSigningKeys(ca, loadSigningKeys) cas[i] = ca } return cas, nil }
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) (*NodeSession, error)
{ 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: stderr, namespace: client.Namespace, closer: utils.NewCloseBroadcaster(), } // if we're joining an existing session, we need to assume that session's // existing/current terminal size: if joinSession != nil { ns.id = joinSession.ID ns.namespace = joinSession.Namespace tsize := joinSession.TerminalParams.Winsize() if ns.isTerminalAttached() { err = term.SetWinsize(0, tsize) if err != nil { log.Error(err) } os.Stdout.Write([]byte(fmt.Sprintf("\x1b[8;%d;%dt", tsize.Height, tsize.Width))) } // new session! } else { sid, ok := ns.env[sshutils.SessionEnvVar] if !ok { sid = string(session.NewID()) } ns.id = session.ID(sid) } ns.env[sshutils.SessionEnvVar] = string(ns.id) return ns, nil }
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 := ns.allocateTerminal(termType, sess) if err != nil { return trace.Wrap(err) } defer remoteTerm.Close() // call the passed callback and give them the established // ssh session: if err := callback(sess, remoteTerm); err != nil { return trace.Wrap(err) } // Catch term signals, but only if we're attached to a real terminal if ns.isTerminalAttached() { ns.watchSignals(remoteTerm) } // start piping input into the remote shell and pipe the output from // the remote shell into stdout: ns.pipeInOut(remoteTerm) // switch the terminal to raw mode (and switch back on exit!) if ns.isTerminalAttached() { ts, err := term.SetRawTerminal(0) if err != nil { log.Warn(err) } else { defer term.RestoreTerminal(0, ts) } } // wait for the session to end <-ns.closer.C return nil }
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 of the same size: err = s.RequestPty(termType, int(tsize.Height), int(tsize.Width), ssh.TerminalModes{}) if err != nil { return nil, trace.Wrap(err) } writer, err := s.StdinPipe() if err != nil { return nil, trace.Wrap(err) } reader, err := s.StdoutPipe() if err != nil { return nil, trace.Wrap(err) } stderr, err := s.StderrPipe() if err != nil { return nil, trace.Wrap(err) } if ns.isTerminalAttached() { go ns.updateTerminalSize(s) } go func() { io.Copy(os.Stderr, stderr) }() return utils.NewPipeNetConn( reader, writer, utils.MultiCloser(writer, s, ns.closer), &net.IPAddr{}, &net.IPAddr{}, ), nil }
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 exit { return trace.Wrap(err) } } return nil }) }
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") } // Start a interactive session ("exec" request with a TTY). // // Note that because a TTY was allocated, the terminal is in raw mode and any // keyboard based signals will be propogated to the TTY on the server which is // where all signal handling will occur. if interactive { return ns.interactiveSession(func(s *ssh.Session, term io.ReadWriteCloser) error { err := s.Start(strings.Join(cmd, " ")) if err != nil { return trace.Wrap(err) } if callback != nil { exit, err := callback(s, ns.NodeClient().Client, term) if exit { return trace.Wrap(err) } } return nil }) } // Start a non-interactive session ("exec" request without TTY). // // Note that for non-interactive sessions upon receipt of SIGINT the client // should send a SSH_MSG_DISCONNECT and shut itself down as gracefully as // possible. This is what the RFC recommends and what OpenSSH does: // // * https://tools.ietf.org/html/rfc4253#section-11.1 // * https://github.com/openssh/openssh-portable/blob/05046d907c211cb9b4cd21b8eff9e7a46cd6c5ab/clientloop.c#L1195-L1444 // // Unfortunately at the moment the Go SSH library Teleport uses does not // support sending SSH_MSG_DISCONNECT. Instead we close the SSH channel and // SSH client, and try and exit as gracefully as possible. return ns.regularSession(func(s *ssh.Session) error { var err error runContext, cancel := context.WithCancel(context.Background()) go func() { defer cancel() err = s.Run(strings.Join(cmd, " ")) }() select { // Run returned a result, return that back to the caller. case <-runContext.Done(): return trace.Wrap(err) // The passed in context timed out. This is often due to the user hitting // Ctrl-C. case <-ctx.Done(): err = s.Close() if err != nil { log.Debugf("Unable to close SSH channel: %v", err) } err = ns.NodeClient().Client.Close() if err != nil { log.Debugf("Unable to close SSH client: %v", err) } return trace.ConnectionProblem(ctx.Err(), "connection canceled") } }) }
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 _, err := shell.Write([]byte{3}) if err != nil { log.Errorf(err.Error()) } } }() // Catch Ctrl-Z signal ctrlZSignal := make(chan os.Signal, 1) signal.Notify(ctrlZSignal, syscall.SIGTSTP) go func() { for { <-ctrlZSignal _, err := shell.Write([]byte{26}) if err != nil { log.Errorf(err.Error()) } } }() }
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 := ns.stdin.Read(buf) if err != nil { fmt.Fprintln(ns.stderr, trace.Wrap(err)) return } if n > 0 { _, err = shell.Write(buf[:n]) if err != nil { ns.ExitMsg = err.Error() return } } } }() }
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: cfg, context: ctx, cancel: cancel, sshListener: newListener(ctx, cfg.Listener.Addr()), tlsListener: newListener(ctx, cfg.Listener.Addr()), waitContext: waitContext, waitCancel: waitCancel, }, nil }
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(conn) continue } if m.isClosed() { return nil } select { case <-backoffTimer.C: m.Debugf("backoff on accept error: %v", trace.DebugReport(err)) case <-m.context.Done(): return nil } } }
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 } if err != nil { g.Debugf("Failed to receive heartbeat: %v", err) return trail.ToGRPC(err) } err = auth.KeepAliveNode(stream.Context(), *keepAlive) if err != nil { return trail.ToGRPC(err) } } }
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.Kind, LoadSecrets: kind.LoadSecrets, }) } watcher, err := auth.NewWatcher(stream.Context(), servicesWatch) if err != nil { return trail.ToGRPC(err) } defer watcher.Close() for { select { case <-stream.Context().Done(): return nil case <-watcher.Done(): return trail.ToGRPC(watcher.Error()) case event := <-watcher.Events(): out, err := eventToGRPC(event) if err != nil { return trail.ToGRPC(err) } if err := stream.Send(out); err != nil { return trail.ToGRPC(err) } } } }
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.ConnectionProblem(err, "[10] failed to connect to the database") } else if trace.IsAccessDenied(err) { // don't print stack trace, just log the warning log.Warn(err) } else { log.Warn(trace.DebugReport(err)) } return nil, trace.AccessDenied("[10] access denied") } return &grpcContext{ AuthContext: authContext, AuthWithRoles: &AuthWithRoles{ authServer: g.AuthServer, user: authContext.User, checker: authContext.Checker, sessions: g.SessionService, alog: g.AuthServer.IAuditLog, }, }, nil }
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, authServer) return authServer }
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.GetStatus(), LastConnected: s.GetLastConnected(), }) } // serialize them into JSON and write back: data, err := json.Marshal(retval) if err != nil { return trace.Wrap(err) } if _, err := ch.Write(data); err != nil { return trace.Wrap(err) } return nil }
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 session.ID, offsetBytes, maxBytes int) (data []byte, err error)
{ 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 string, sid session.ID, after int, fetchPrintEvents bool) (events []EventFields, err error)
{ for _, log := range m.loggers { events, err = log.GetSessionEvents(namespace, sid, after, fetchPrintEvents) if !trace.IsNotImplemented(err) { return events, err } } return events, err }