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/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1322-L1334
go
train
// FetchRoles fetches roles by their names, applies the traits to role // variables, and returns the RoleSet.
func FetchRoles(roleNames []string, access RoleGetter, traits map[string][]string) (RoleSet, error)
// FetchRoles fetches roles by their names, applies the traits to role // variables, and returns the RoleSet. func FetchRoles(roleNames []string, access RoleGetter, traits map[string][]string) (RoleSet, error)
{ var roles []Role for _, roleName := range roleNames { role, err := access.GetRole(roleName) if err != nil { return nil, trace.Wrap(err) } roles = append(roles, role.ApplyTraits(traits)) } return NewRoleSet(roles...), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1337-L1344
go
train
// NewRoleSet returns new RoleSet based on the roles
func NewRoleSet(roles ...Role) RoleSet
// NewRoleSet returns new RoleSet based on the roles func NewRoleSet(roles ...Role) RoleSet
{ // unauthenticated Nop role should not have any privileges // by default, otherwise it is too permissive if len(roles) == 1 && roles[0].GetName() == string(teleport.RoleNop) { return roles } return append(roles, NewImplicitRole()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1351-L1358
go
train
// MatchNamespace returns true if given list of namespace matches // target namespace, wildcard matches everything.
func MatchNamespace(selectors []string, namespace string) (bool, string)
// MatchNamespace returns true if given list of namespace matches // target namespace, wildcard matches everything. func MatchNamespace(selectors []string, namespace string) (bool, string)
{ for _, n := range selectors { if n == namespace || n == Wildcard { return true, "matched" } } return false, fmt.Sprintf("no match, role selectors %v, server namespace: %v", selectors, namespace) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1361-L1368
go
train
// MatchLogin returns true if attempted login matches any of the logins.
func MatchLogin(selectors []string, login string) (bool, string)
// MatchLogin returns true if attempted login matches any of the logins. func MatchLogin(selectors []string, login string) (bool, string)
{ for _, l := range selectors { if l == login { return true, "matched" } } return false, fmt.Sprintf("no match, role selectors %v, login: %v", selectors, login) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1372-L1403
go
train
// MatchLabels matches selector against target. Empty selector matches // nothing, wildcard matches everything.
func MatchLabels(selector Labels, target map[string]string) (bool, string, error)
// MatchLabels matches selector against target. Empty selector matches // nothing, wildcard matches everything. func MatchLabels(selector Labels, target map[string]string) (bool, string, error)
{ // Empty selector matches nothing. if len(selector) == 0 { return false, "no match, empty selector", nil } // *: * matches everything even empty target set. selectorValues := selector[Wildcard] if len(selectorValues) == 1 && selectorValues[0] == Wildcard { return true, "matched", nil } // Perform full match. for key, selectorValues := range selector { targetVal, hasKey := target[key] if !hasKey { return false, fmt.Sprintf("no key match: '%v'", key), nil } if !utils.SliceContainsStr(selectorValues, Wildcard) { result, err := utils.SliceMatchesRegex(targetVal, selectorValues) if err != nil { return false, "", trace.Wrap(err) } else if !result { return false, fmt.Sprintf("no value match: got '%v' want: '%v'", targetVal, selectorValues), nil } } } return true, "matched", nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1406-L1412
go
train
// RoleNames returns a slice with role names
func (set RoleSet) RoleNames() []string
// RoleNames returns a slice with role names func (set RoleSet) RoleNames() []string
{ out := make([]string, len(set)) for i, r := range set { out[i] = r.GetName() } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1415-L1422
go
train
// HasRole checks if the role set has the role
func (set RoleSet) HasRole(role string) bool
// HasRole checks if the role set has the role func (set RoleSet) HasRole(role string) bool
{ for _, r := range set { if r.GetName() == role { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1426-L1434
go
train
// AdjustSessionTTL will reduce the requested ttl to lowest max allowed TTL // for this role set, otherwise it returns ttl unchanged
func (set RoleSet) AdjustSessionTTL(ttl time.Duration) time.Duration
// AdjustSessionTTL will reduce the requested ttl to lowest max allowed TTL // for this role set, otherwise it returns ttl unchanged func (set RoleSet) AdjustSessionTTL(ttl time.Duration) time.Duration
{ for _, role := range set { maxSessionTTL := role.GetOptions().MaxSessionTTL.Value() if maxSessionTTL != 0 && ttl > maxSessionTTL { ttl = maxSessionTTL } } return ttl }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1439-L1460
go
train
// AdjustClientIdleTimeout adjusts requested idle timeout // to the lowest max allowed timeout, the most restrictive // option will be picked, negative values will be assumed as 0
func (set RoleSet) AdjustClientIdleTimeout(timeout time.Duration) time.Duration
// AdjustClientIdleTimeout adjusts requested idle timeout // to the lowest max allowed timeout, the most restrictive // option will be picked, negative values will be assumed as 0 func (set RoleSet) AdjustClientIdleTimeout(timeout time.Duration) time.Duration
{ if timeout < 0 { timeout = 0 } for _, role := range set { roleTimeout := role.GetOptions().ClientIdleTimeout // 0 means not set, so it can't be most restrictive, disregard it too if roleTimeout.Duration() <= 0 { continue } switch { // in case if timeout is 0, means that incoming value // does not restrict the idle timeout, pick any other value // set by the role case timeout == 0: timeout = roleTimeout.Duration() case roleTimeout.Duration() < timeout: timeout = roleTimeout.Duration() } } return timeout }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1464-L1471
go
train
// AdjustDisconnectExpiredCert adjusts the value based on the role set // the most restrictive option will be picked
func (set RoleSet) AdjustDisconnectExpiredCert(disconnect bool) bool
// AdjustDisconnectExpiredCert adjusts the value based on the role set // the most restrictive option will be picked func (set RoleSet) AdjustDisconnectExpiredCert(disconnect bool) bool
{ for _, role := range set { if role.GetOptions().DisconnectExpiredCert.Value() { disconnect = true } } return disconnect }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1475-L1498
go
train
// CheckKubeGroups check if role can login into kubernetes // and returns a combined list of allowed groups
func (set RoleSet) CheckKubeGroups(ttl time.Duration) ([]string, error)
// CheckKubeGroups check if role can login into kubernetes // and returns a combined list of allowed groups func (set RoleSet) CheckKubeGroups(ttl time.Duration) ([]string, error)
{ groups := make(map[string]bool) var matchedTTL bool for _, role := range set { maxSessionTTL := role.GetOptions().MaxSessionTTL.Value() if ttl <= maxSessionTTL && maxSessionTTL != 0 { matchedTTL = true for _, group := range role.GetKubeGroups(Allow) { groups[group] = true } } } if !matchedTTL { return nil, trace.AccessDenied("this user cannot request kubernetes access for %v", ttl) } if len(groups) == 0 { return nil, trace.AccessDenied("this user cannot request kubernetes access, has no assigned groups") } out := make([]string, 0, len(groups)) for group := range groups { out = append(out, group) } return out, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1502-L1526
go
train
// CheckLoginDuration checks if role set can login up to given duration and // returns a combined list of allowed logins.
func (set RoleSet) CheckLoginDuration(ttl time.Duration) ([]string, error)
// CheckLoginDuration checks if role set can login up to given duration and // returns a combined list of allowed logins. func (set RoleSet) CheckLoginDuration(ttl time.Duration) ([]string, error)
{ logins := make(map[string]bool) var matchedTTL bool for _, role := range set { maxSessionTTL := role.GetOptions().MaxSessionTTL.Value() if ttl <= maxSessionTTL && maxSessionTTL != 0 { matchedTTL = true for _, login := range role.GetLogins(Allow) { logins[login] = true } } } if !matchedTTL { return nil, trace.AccessDenied("this user cannot request a certificate for %v", ttl) } if len(logins) == 0 { return nil, trace.AccessDenied("this user cannot create SSH sessions, has no allowed logins") } out := make([]string, 0, len(logins)) for login := range logins { out = append(out, login) } return out, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1535-L1583
go
train
// CheckAccessToServer checks if a role has access to a node. Deny rules are // checked first then allow rules. Access to a node is determined by // namespaces, labels, and logins. // // Note, logging in this function only happens in debug mode, this is because // adding logging to this function (which is called on every server returned // by GetNodes) can slow down this function by 50x for large clusters!
func (set RoleSet) CheckAccessToServer(login string, s Server) error
// CheckAccessToServer checks if a role has access to a node. Deny rules are // checked first then allow rules. Access to a node is determined by // namespaces, labels, and logins. // // Note, logging in this function only happens in debug mode, this is because // adding logging to this function (which is called on every server returned // by GetNodes) can slow down this function by 50x for large clusters! func (set RoleSet) CheckAccessToServer(login string, s Server) error
{ var errs []error // Check deny rules first: a single matching namespace, label, or login from // the deny role set prohibits access. for _, role := range set { matchNamespace, namespaceMessage := MatchNamespace(role.GetNamespaces(Deny), s.GetNamespace()) matchLabels, labelsMessage, err := MatchLabels(role.GetNodeLabels(Deny), s.GetAllLabels()) if err != nil { return trace.Wrap(err) } matchLogin, loginMessage := MatchLogin(role.GetLogins(Deny), login) if matchNamespace && (matchLabels || matchLogin) { if log.GetLevel() == log.DebugLevel { log.WithFields(log.Fields{ trace.Component: teleport.ComponentRBAC, }).Debugf("Access to node %v denied, deny rule in %v matched; match(namespace=%v, label=%v, login=%v)", s.GetHostname(), role.GetName(), namespaceMessage, labelsMessage, loginMessage) } return trace.AccessDenied("access to server denied") } } // Check allow rules: namespace, label, and login have to all match in // one role in the role set to be granted access. for _, role := range set { matchNamespace, namespaceMessage := MatchNamespace(role.GetNamespaces(Allow), s.GetNamespace()) matchLabels, labelsMessage, err := MatchLabels(role.GetNodeLabels(Allow), s.GetAllLabels()) if err != nil { return trace.Wrap(err) } matchLogin, loginMessage := MatchLogin(role.GetLogins(Allow), login) if matchNamespace && matchLabels && matchLogin { return nil } if log.GetLevel() == log.DebugLevel { deniedError := trace.AccessDenied("role=%v, match(namespace=%v, label=%v, login=%v)", role.GetName(), namespaceMessage, labelsMessage, loginMessage) errs = append(errs, deniedError) } } if log.GetLevel() == log.DebugLevel { log.WithFields(log.Fields{ trace.Component: teleport.ComponentRBAC, }).Debugf("Access to node %v denied, no allow rule matched; %v", s.GetHostname(), errs) } return trace.AccessDenied("access to server denied") }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1586-L1593
go
train
// CanForwardAgents returns true if role set allows forwarding agents.
func (set RoleSet) CanForwardAgents() bool
// CanForwardAgents returns true if role set allows forwarding agents. func (set RoleSet) CanForwardAgents() bool
{ for _, role := range set { if role.GetOptions().ForwardAgent.Value() { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1596-L1603
go
train
// CanPortForward returns true if a role in the RoleSet allows port forwarding.
func (set RoleSet) CanPortForward() bool
// CanPortForward returns true if a role in the RoleSet allows port forwarding. func (set RoleSet) CanPortForward() bool
{ for _, role := range set { if BoolDefaultTrue(role.GetOptions().PortForwarding) { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1607-L1632
go
train
// CertificateFormat returns the most permissive certificate format in a // RoleSet.
func (set RoleSet) CertificateFormat() string
// CertificateFormat returns the most permissive certificate format in a // RoleSet. func (set RoleSet) CertificateFormat() string
{ var formats []string for _, role := range set { // get the certificate format for each individual role. if a role does not // have a certificate format (like implicit roles) skip over it certificateFormat := role.GetOptions().CertificateFormat if certificateFormat == "" { continue } formats = append(formats, certificateFormat) } // if no formats were found, return standard if len(formats) == 0 { return teleport.CertificateFormatStandard } // sort the slice so the most permissive is the first element sort.Slice(formats, func(i, j int) bool { return certificatePriority(formats[i]) < certificatePriority(formats[j]) }) return formats[0] }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1649-L1661
go
train
// CheckAgentForward checks if the role can request to forward the SSH agent // for this user.
func (set RoleSet) CheckAgentForward(login string) error
// CheckAgentForward checks if the role can request to forward the SSH agent // for this user. func (set RoleSet) CheckAgentForward(login string) error
{ // check if we have permission to login and forward agent. we don't check // for deny rules because if you can't forward an agent if you can't login // in the first place. for _, role := range set { for _, l := range role.GetLogins(Allow) { if role.GetOptions().ForwardAgent.Value() && l == login { return nil } } } return trace.AccessDenied("%v can not forward agent for %v", set, login) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1789-L1791
go
train
// MarshalTo marshals value to the array
func (l Labels) MarshalTo(data []byte) (int, error)
// MarshalTo marshals value to the array func (l Labels) MarshalTo(data []byte) (int, error)
{ return l.protoType().MarshalTo(data) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1794-L1808
go
train
// Unmarshal unmarshals value from protobuf
func (l *Labels) Unmarshal(data []byte) error
// Unmarshal unmarshals value from protobuf func (l *Labels) Unmarshal(data []byte) error
{ protoValues := &LabelValues{} err := proto.Unmarshal(data, protoValues) if err != nil { return err } if protoValues.Values == nil { return nil } *l = make(map[string]utils.Strings, len(protoValues.Values)) for key := range protoValues.Values { (*l)[key] = protoValues.Values[key].Values } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1816-L1827
go
train
// Clone returns non-shallow copy of the labels set
func (l Labels) Clone() Labels
// Clone returns non-shallow copy of the labels set func (l Labels) Clone() Labels
{ if l == nil { return nil } out := make(Labels, len(l)) for key, vals := range l { cvals := make([]string, len(vals)) copy(cvals, vals) out[key] = cvals } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1830-L1840
go
train
// Equals returns true if two label sets are equal
func (l Labels) Equals(o Labels) bool
// Equals returns true if two label sets are equal func (l Labels) Equals(o Labels) bool
{ if len(l) != len(o) { return false } for key := range l { if !utils.StringSlicesEqual(l[key], o[key]) { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1869-L1891
go
train
// UnmarshalJSON unmarshals JSON from string or bool, // in case if value is missing or not recognized, defaults to false
func (b *Bool) UnmarshalJSON(data []byte) error
// UnmarshalJSON unmarshals JSON from string or bool, // in case if value is missing or not recognized, defaults to false func (b *Bool) UnmarshalJSON(data []byte) error
{ if len(data) == 0 { return nil } var boolVal bool // check if it's a bool variable if err := json.Unmarshal(data, &boolVal); err == nil { *b = Bool(boolVal) return nil } // also support string variables var stringVar string if err := json.Unmarshal(data, &stringVar); err != nil { return trace.Wrap(err) } v, err := utils.ParseBool(stringVar) if err != nil { *b = false return nil } *b = Bool(v) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1933-L1935
go
train
// MarshalTo marshals value to the slice
func (b BoolOption) MarshalTo(data []byte) (int, error)
// MarshalTo marshals value to the slice func (b BoolOption) MarshalTo(data []byte) (int, error)
{ return b.protoType().MarshalTo(data) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1943-L1951
go
train
// Unmarshal unmarshals value from protobuf
func (b *BoolOption) Unmarshal(data []byte) error
// Unmarshal unmarshals value from protobuf func (b *BoolOption) Unmarshal(data []byte) error
{ protoValue := &BoolValue{} err := proto.Unmarshal(data, protoValue) if err != nil { return err } b.Value = protoValue.Value return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1965-L1972
go
train
// UnmarshalJSON unmarshals JSON from string or bool, // in case if value is missing or not recognized, defaults to false
func (b *BoolOption) UnmarshalJSON(data []byte) error
// UnmarshalJSON unmarshals JSON from string or bool, // in case if value is missing or not recognized, defaults to false func (b *BoolOption) UnmarshalJSON(data []byte) error
{ var val Bool if err := val.UnmarshalJSON(data); err != nil { return err } b.Value = val.Value() return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2007-L2025
go
train
// UnmarshalJSON marshals Duration to string
func (d *Duration) UnmarshalJSON(data []byte) error
// UnmarshalJSON marshals Duration to string func (d *Duration) UnmarshalJSON(data []byte) error
{ if len(data) == 0 { return nil } var stringVar string if err := json.Unmarshal(data, &stringVar); err != nil { return trace.Wrap(err) } if stringVar == teleport.DurationNever { *d = Duration(0) } else { out, err := time.ParseDuration(stringVar) if err != nil { return trace.BadParameter(err.Error()) } *d = Duration(out) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2158-L2175
go
train
// GetRoleSchema returns role schema for the version requested with optionally // injected schema for extensions.
func GetRoleSchema(version string, extensionSchema string) string
// GetRoleSchema returns role schema for the version requested with optionally // injected schema for extensions. func GetRoleSchema(version string, extensionSchema string) string
{ schemaDefinitions := "," + RoleSpecV3SchemaDefinitions if version == V2 { schemaDefinitions = DefaultDefinitions } schemaTemplate := RoleSpecV3SchemaTemplate if version == V2 { schemaTemplate = RoleSpecV2SchemaTemplate } schema := fmt.Sprintf(schemaTemplate, ``) if extensionSchema != "" { schema = fmt.Sprintf(schemaTemplate, ","+extensionSchema) } return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, schema, schemaDefinitions) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2178-L2230
go
train
// UnmarshalRole unmarshals role from JSON, sets defaults, and checks schema.
func UnmarshalRole(data []byte, opts ...MarshalOption) (*RoleV3, error)
// UnmarshalRole unmarshals role from JSON, sets defaults, and checks schema. func UnmarshalRole(data []byte, opts ...MarshalOption) (*RoleV3, error)
{ var h ResourceHeader err := json.Unmarshal(data, &h) if err != nil { h.Version = V2 } cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch h.Version { case V2: var role RoleV2 if err := utils.UnmarshalWithSchema(GetRoleSchema(V2, ""), &role, data); err != nil { return nil, trace.BadParameter(err.Error()) } if err := role.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } roleV3 := role.V3() roleV3.SetResourceID(cfg.ID) return roleV3, nil case V3: var role RoleV3 if cfg.SkipValidation { if err := utils.FastUnmarshal(data, &role); err != nil { return nil, trace.BadParameter(err.Error()) } } else { if err := utils.UnmarshalWithSchema(GetRoleSchema(V3, ""), &role, data); err != nil { return nil, trace.BadParameter(err.Error()) } } if err := role.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } if cfg.ID != 0 { role.SetResourceID(cfg.ID) } if !cfg.Expires.IsZero() { role.SetExpiry(cfg.Expires) } return &role, nil } return nil, trace.BadParameter("role version %q is not supported", h.Version) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2258-L2260
go
train
// UnmarshalRole unmarshals role from JSON.
func (*TeleportRoleMarshaler) UnmarshalRole(bytes []byte, opts ...MarshalOption) (Role, error)
// UnmarshalRole unmarshals role from JSON. func (*TeleportRoleMarshaler) UnmarshalRole(bytes []byte, opts ...MarshalOption) (Role, error)
{ return UnmarshalRole(bytes, opts...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2263-L2281
go
train
// MarshalRole marshalls role into JSON.
func (*TeleportRoleMarshaler) MarshalRole(r Role, opts ...MarshalOption) ([]byte, error)
// MarshalRole marshalls role into JSON. func (*TeleportRoleMarshaler) MarshalRole(r Role, opts ...MarshalOption) ([]byte, error)
{ cfg, err := collectOptions(opts) if err != nil { return nil, trace.Wrap(err) } switch role := r.(type) { case *RoleV3: if !cfg.PreserveResourceID { // avoid modifying the original object // to prevent unexpected data races copy := *role copy.SetResourceID(0) role = &copy } return utils.FastMarshal(role) default: return nil, trace.BadParameter("unrecognized role version %T", r) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2292-L2294
go
train
// Less compares roles by name
func (s SortedRoles) Less(i, j int) bool
// Less compares roles by name func (s SortedRoles) Less(i, j int) bool
{ return s[i].GetName() < s[j].GetName() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L2297-L2299
go
train
// Swap swaps two roles in a list
func (s SortedRoles) Swap(i, j int)
// Swap swaps two roles in a list func (s SortedRoles) Swap(i, j int)
{ s[i], s[j] = s[j], s[i] }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/migrate.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/migrate.go#L33-L116
go
train
// DELETE IN: 2.8.0 // migrate old directory backend to the new flat keyspace.
func migrate(rootDir string, b *Backend) error
// DELETE IN: 2.8.0 // migrate old directory backend to the new flat keyspace. func migrate(rootDir string, b *Backend) error
{ // Check if the directory structure is the old bucket format. ok, err := isOld(rootDir) if err != nil { return trace.Wrap(err) } // Found the new flat keyspace directory backend, nothing to do. if !ok { b.log.Debugf("Found new flat keyspace, skipping migration.") return nil } // The old directory backend was found, make a backup in-case is needs to // be restored. backupDir := rootDir + ".backup-" + time.Now().Format(time.RFC3339) err = os.Rename(rootDir, backupDir) if err != nil { return trace.Wrap(err) } err = os.MkdirAll(rootDir, defaultDirMode) if err != nil { return trace.ConvertSystemError(err) } b.log.Infof("Migrating directory backend to new flat keyspace. Backup in %v.", backupDir) // Go over every file in the backend. If the key is not expired upsert // into the new backend. err = filepath.Walk(backupDir, func(path string, info os.FileInfo, err error) error { if err != nil { return trace.ConvertSystemError(err) } // Skip the locks directory completely. if info.IsDir() && info.Name() == ".locks" { return filepath.SkipDir } // Skip over directories themselves, but not their content. if info.IsDir() { return nil } // Skip over TTL files (they are handled by readTTL function). if strings.HasPrefix(info.Name(), ".") { return nil } // Construct key and flat bucket. key := info.Name() flatbucket := strings.TrimPrefix(path, backupDir) flatbucket = strings.TrimSuffix(flatbucket, string(filepath.Separator)+key) // Read in TTL for key. If the key is expired, skip over it. ttl, expired, err := readTTL(backupDir, flatbucket, key) if err != nil { return trace.Wrap(err) } if expired { b.log.Infof("Skipping migration of expired bucket %q and key %q.", flatbucket, info.Name()) return nil } // Read in the value of the key. value, err := ioutil.ReadFile(path) if err != nil { return trace.Wrap(err) } // Upsert key and value (with TTL) into new flat keyspace backend. bucket := strings.Split(flatbucket, string(filepath.Separator)) err = b.UpsertVal(bucket, key, value, ttl) if err != nil { return trace.Wrap(err) } b.log.Infof("Migrated bucket %q and key %q with TTL %v.", flatbucket, key, ttl) return nil }) if err != nil { return trace.Wrap(err) } b.log.Infof("Migration successful.") return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/migrate.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/migrate.go#L121-L145
go
train
// DELETE IN: 2.8.0 // readTTL reads in TTL for the given key. If no TTL key is found, // legacy.Forever is returned.
func readTTL(rootDir string, bucket string, key string) (time.Duration, bool, error)
// DELETE IN: 2.8.0 // readTTL reads in TTL for the given key. If no TTL key is found, // legacy.Forever is returned. func readTTL(rootDir string, bucket string, key string) (time.Duration, bool, error)
{ filename := filepath.Join(rootDir, bucket, "."+key+".ttl") bytes, err := ioutil.ReadFile(filename) if err != nil { if os.IsNotExist(err) { return legacy.Forever, false, nil } return legacy.Forever, false, trace.Wrap(err) } if len(bytes) == 0 { return legacy.Forever, false, nil } var expiryTime time.Time if err = expiryTime.UnmarshalText(bytes); err != nil { return legacy.Forever, false, trace.Wrap(err) } ttl := expiryTime.Sub(time.Now()) if ttl < 0 { return legacy.Forever, true, nil } return ttl, false, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/backend/legacy/dir/migrate.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/dir/migrate.go#L149-L168
go
train
// DELETE IN: 2.8.0 // isOld checks if the directory backend is in the old format or not.
func isOld(rootDir string) (bool, error)
// DELETE IN: 2.8.0 // isOld checks if the directory backend is in the old format or not. func isOld(rootDir string) (bool, error)
{ d, err := os.Open(rootDir) if err != nil { return false, trace.ConvertSystemError(err) } defer d.Close() files, err := d.Readdir(0) if err != nil { return false, trace.ConvertSystemError(err) } for _, fi := range files { if fi.IsDir() { return true, nil } } return false, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L71-L94
go
train
// Initialize allows ResourceCommand to plug itself into the CLI parser
func (g *ResourceCommand) Initialize(app *kingpin.Application, config *service.Config)
// Initialize allows ResourceCommand to plug itself into the CLI parser func (g *ResourceCommand) Initialize(app *kingpin.Application, config *service.Config)
{ g.CreateHandlers = map[ResourceKind]ResourceCreateHandler{ services.KindUser: g.createUser, services.KindTrustedCluster: g.createTrustedCluster, services.KindGithubConnector: g.createGithubConnector, services.KindCertAuthority: g.createCertAuthority, } g.config = config g.createCmd = app.Command("create", "Create or update a Teleport resource from a YAML file") g.createCmd.Arg("filename", "resource definition file").Required().StringVar(&g.filename) g.createCmd.Flag("force", "Overwrite the resource if already exists").Short('f').BoolVar(&g.force) g.deleteCmd = app.Command("rm", "Delete a resource").Alias("del") g.deleteCmd.Arg("resource", "Resource to delete").SetValue(&g.ref) g.getCmd = app.Command("get", "Print a YAML declaration of various Teleport resources") g.getCmd.Arg("resource", "Resource spec: 'type/[name]'").SetValue(&g.ref) g.getCmd.Flag("format", "Output format: 'yaml', 'json' or 'text'").Default(formatYAML).StringVar(&g.format) g.getCmd.Flag("namespace", "Namespace of the resources").Hidden().Default(defaults.Namespace).StringVar(&g.namespace) g.getCmd.Flag("with-secrets", "Include secrets in resources like certificate authorities or OIDC connectors").Default("false").BoolVar(&g.withSecrets) g.getCmd.Alias(getHelp) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L98-L113
go
train
// TryRun takes the CLI command as an argument (like "auth gen") and executes it // or returns match=false if 'cmd' does not belong to it
func (g *ResourceCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
// TryRun takes the CLI command as an argument (like "auth gen") and executes it // or returns match=false if 'cmd' does not belong to it func (g *ResourceCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
{ switch cmd { // tctl get case g.getCmd.FullCommand(): err = g.Get(client) // tctl create case g.createCmd.FullCommand(): err = g.Create(client) // tctl rm case g.deleteCmd.FullCommand(): err = g.Delete(client) default: return false, nil } return true, trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L116-L118
go
train
// IsDeleteSubcommand returns 'true' if the given command is `tctl rm`
func (g *ResourceCommand) IsDeleteSubcommand(cmd string) bool
// IsDeleteSubcommand returns 'true' if the given command is `tctl rm` func (g *ResourceCommand) IsDeleteSubcommand(cmd string) bool
{ return cmd == g.deleteCmd.FullCommand() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L127-L144
go
train
// Get prints one or many resources of a certain type
func (g *ResourceCommand) Get(client auth.ClientI) error
// Get prints one or many resources of a certain type func (g *ResourceCommand) Get(client auth.ClientI) error
{ collection, err := g.getCollection(client) if err != nil { return trace.Wrap(err) } // Note that only YAML is officially supported. Support for text and JSON // is experimental. switch g.format { case teleport.YAML: return collection.writeYAML(os.Stdout) case teleport.Text: return collection.writeText(os.Stdout) case teleport.JSON: return collection.writeJSON(os.Stdout) } return trace.BadParameter("unsupported format") }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L147-L179
go
train
// Create updates or insterts one or many resources
func (u *ResourceCommand) Create(client auth.ClientI) error
// Create updates or insterts one or many resources func (u *ResourceCommand) Create(client auth.ClientI) error
{ reader, err := utils.OpenFile(u.filename) if err != nil { return trace.Wrap(err) } decoder := kyaml.NewYAMLOrJSONDecoder(reader, 32*1024) count := 0 for { var raw services.UnknownResource err := decoder.Decode(&raw) if err != nil { if err == io.EOF { if count == 0 { return trace.BadParameter("no resources found, empty input?") } return nil } return trace.Wrap(err) } count++ // locate the creator function for a given resource kind: creator, found := u.CreateHandlers[ResourceKind(raw.Kind)] if !found { return trace.BadParameter("creating resources of type %q is not supported", raw.Kind) } // only return in case of error, to create multiple resources // in case if yaml spec is a list if err := creator(client, raw); err != nil { return trace.Wrap(err) } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L182-L216
go
train
// createTrustedCluster implements `tctl create cluster.yaml` command
func (u *ResourceCommand) createTrustedCluster(client auth.ClientI, raw services.UnknownResource) error
// createTrustedCluster implements `tctl create cluster.yaml` command func (u *ResourceCommand) createTrustedCluster(client auth.ClientI, raw services.UnknownResource) error
{ tc, err := services.GetTrustedClusterMarshaler().Unmarshal(raw.Raw) if err != nil { return trace.Wrap(err) } // check if such cluster already exists: name := tc.GetName() _, err = client.GetTrustedCluster(name) if err != nil && !trace.IsNotFound(err) { return trace.Wrap(err) } exists := (err == nil) if u.force == false && exists { return trace.AlreadyExists("trusted cluster '%s' already exists", name) } out, err := client.UpsertTrustedCluster(tc) if err != nil { // If force is used and UpsertTrustedCluster returns trace.AlreadyExists, // this means the user tried to upsert a cluster whose exact match already // exists in the backend, nothing needs to occur other than happy message // that the trusted cluster has been created. if u.force && trace.IsAlreadyExists(err) { out = tc } else { return trace.Wrap(err) } } if out.GetName() != tc.GetName() { fmt.Printf("WARNING: trusted cluster %q resource has been renamed to match remote cluster name %q\n", name, out.GetName()) } fmt.Printf("trusted cluster %q has been %v\n", out.GetName(), UpsertVerb(exists, u.force)) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L219-L229
go
train
// createCertAuthority creates certificate authority
func (u *ResourceCommand) createCertAuthority(client auth.ClientI, raw services.UnknownResource) error
// createCertAuthority creates certificate authority func (u *ResourceCommand) createCertAuthority(client auth.ClientI, raw services.UnknownResource) error
{ certAuthority, err := services.GetCertAuthorityMarshaler().UnmarshalCertAuthority(raw.Raw) if err != nil { return trace.Wrap(err) } if err := client.UpsertCertAuthority(certAuthority); err != nil { return trace.Wrap(err) } fmt.Printf("certificate authority '%s' has been updated\n", certAuthority.GetName()) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L255-L266
go
train
// createUser implements 'tctl create user.yaml' command
func (u *ResourceCommand) createUser(client auth.ClientI, raw services.UnknownResource) error
// createUser implements 'tctl create user.yaml' command func (u *ResourceCommand) createUser(client auth.ClientI, raw services.UnknownResource) error
{ user, err := services.GetUserMarshaler().UnmarshalUser(raw.Raw) if err != nil { return trace.Wrap(err) } userName := user.GetName() if err := client.UpsertUser(user); err != nil { return trace.Wrap(err) } fmt.Printf("user '%s' has been updated\n", userName) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/resource_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/resource_command.go#L269-L319
go
train
// Delete deletes resource by name
func (d *ResourceCommand) Delete(client auth.ClientI) (err error)
// Delete deletes resource by name func (d *ResourceCommand) Delete(client auth.ClientI) (err error)
{ if d.ref.Kind == "" || d.ref.Name == "" { return trace.BadParameter("provide a full resource name to delete, for example:\n$ tctl rm cluster/east\n") } switch d.ref.Kind { case services.KindNode: if err = client.DeleteNode(defaults.Namespace, d.ref.Name); err != nil { return trace.Wrap(err) } fmt.Printf("node %v has been deleted\n", d.ref.Name) case services.KindUser: if err = client.DeleteUser(d.ref.Name); err != nil { return trace.Wrap(err) } fmt.Printf("user %v has been deleted\n", d.ref.Name) case services.KindSAMLConnector: if err = client.DeleteSAMLConnector(d.ref.Name); err != nil { return trace.Wrap(err) } fmt.Printf("SAML Connector %v has been deleted\n", d.ref.Name) case services.KindOIDCConnector: if err = client.DeleteOIDCConnector(d.ref.Name); err != nil { return trace.Wrap(err) } fmt.Printf("OIDC Connector %v has been deleted\n", d.ref.Name) case services.KindGithubConnector: if err = client.DeleteGithubConnector(d.ref.Name); err != nil { return trace.Wrap(err) } fmt.Printf("github connector %q has been deleted\n", d.ref.Name) case services.KindReverseTunnel: if err := client.DeleteReverseTunnel(d.ref.Name); err != nil { return trace.Wrap(err) } fmt.Printf("reverse tunnel %v has been deleted\n", d.ref.Name) case services.KindTrustedCluster: if err = client.DeleteTrustedCluster(d.ref.Name); err != nil { return trace.Wrap(err) } fmt.Printf("trusted cluster %q has been deleted\n", d.ref.Name) case services.KindRemoteCluster: if err = client.DeleteRemoteCluster(d.ref.Name); err != nil { return trace.Wrap(err) } fmt.Printf("remote cluster %q has been deleted\n", d.ref.Name) default: return trace.BadParameter("deleting resources of type %q is not supported", d.ref.Kind) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/cache.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/cache.go#L45-L56
go
train
// NewHostCertificateCache creates a shared host certificate cache that is // used by the forwarding server.
func NewHostCertificateCache(keygen sshca.Authority, authClient auth.ClientI) (*certificateCache, error)
// NewHostCertificateCache creates a shared host certificate cache that is // used by the forwarding server. func NewHostCertificateCache(keygen sshca.Authority, authClient auth.ClientI) (*certificateCache, error)
{ cache, err := ttlmap.New(defaults.HostCertCacheSize) if err != nil { return nil, trace.Wrap(err) } return &certificateCache{ keygen: keygen, cache: cache, authClient: authClient, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/cache.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/cache.go#L63-L86
go
train
// GetHostCertificate will fetch a certificate from the cache. If the certificate // is not in the cache, it will be generated, put in the cache, and returned. Mul // Multiple callers can arrive and generate a host certificate at the same time. // This is a tradeoff to prevent long delays here due to the expensive // certificate generation call.
func (c *certificateCache) GetHostCertificate(addr string, additionalPrincipals []string) (ssh.Signer, error)
// GetHostCertificate will fetch a certificate from the cache. If the certificate // is not in the cache, it will be generated, put in the cache, and returned. Mul // Multiple callers can arrive and generate a host certificate at the same time. // This is a tradeoff to prevent long delays here due to the expensive // certificate generation call. func (c *certificateCache) GetHostCertificate(addr string, additionalPrincipals []string) (ssh.Signer, error)
{ var certificate ssh.Signer var err error var ok bool var principals []string principals = append(principals, addr) principals = append(principals, additionalPrincipals...) certificate, ok = c.get(strings.Join(principals, ".")) if !ok { certificate, err = c.generateHostCert(principals) if err != nil { return nil, trace.Wrap(err) } err = c.set(addr, certificate, defaults.HostCertCacheTime) if err != nil { return nil, trace.Wrap(err) } } return certificate, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/cache.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/cache.go#L90-L105
go
train
// get is goroutine safe and will return a ssh.Signer for a principal from // the cache.
func (c *certificateCache) get(addr string) (ssh.Signer, bool)
// get is goroutine safe and will return a ssh.Signer for a principal from // the cache. func (c *certificateCache) get(addr string) (ssh.Signer, bool)
{ c.mu.Lock() defer c.mu.Unlock() certificate, ok := c.cache.Get(addr) if !ok { return nil, false } certificateSigner, ok := certificate.(ssh.Signer) if !ok { return nil, false } return certificateSigner, true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/cache.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/cache.go#L109-L119
go
train
// set is goroutine safe and will set a ssh.Signer for a principal in // the cache.
func (c *certificateCache) set(addr string, certificate ssh.Signer, ttl time.Duration) error
// set is goroutine safe and will set a ssh.Signer for a principal in // the cache. func (c *certificateCache) set(addr string, certificate ssh.Signer, ttl time.Duration) error
{ c.mu.Lock() defer c.mu.Unlock() err := c.cache.Set(addr, certificate, ttl) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/reversetunnel/cache.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/cache.go#L123-L173
go
train
// generateHostCert will generate a SSH host certificate for a given // principal.
func (c *certificateCache) generateHostCert(principals []string) (ssh.Signer, error)
// generateHostCert will generate a SSH host certificate for a given // principal. func (c *certificateCache) generateHostCert(principals []string) (ssh.Signer, error)
{ if len(principals) == 0 { return nil, trace.BadParameter("at least one principal must be provided") } // Generate public/private keypair. privBytes, pubBytes, err := c.keygen.GetNewKeyPairFromPool() if err != nil { return nil, trace.Wrap(err) } // Generate a SSH host certificate. clusterName, err := c.authClient.GetDomainName() if err != nil { return nil, trace.Wrap(err) } certBytes, err := c.authClient.GenerateHostCert( pubBytes, principals[0], principals[0], principals, clusterName, teleport.Roles{teleport.RoleNode}, 0) if err != nil { return nil, trace.Wrap(err) } // create a *ssh.Certificate privateKey, err := ssh.ParsePrivateKey(privBytes) if err != nil { return nil, trace.Wrap(err) } publicKey, _, _, _, err := ssh.ParseAuthorizedKey(certBytes) if err != nil { return nil, err } cert, ok := publicKey.(*ssh.Certificate) if !ok { return nil, trace.BadParameter("not a certificate") } // return a ssh.Signer s, err := ssh.NewCertSigner(cert, privateKey) if err != nil { return nil, trace.Wrap(err) } return s, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/monitor.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/monitor.go#L81-L104
go
train
// CheckAndSetDefaults checks values and sets defaults
func (m *MonitorConfig) CheckAndSetDefaults() error
// CheckAndSetDefaults checks values and sets defaults func (m *MonitorConfig) CheckAndSetDefaults() error
{ if m.Context == nil { return trace.BadParameter("missing parameter Context") } if m.DisconnectExpiredCert.IsZero() && m.ClientIdleTimeout == 0 { return trace.BadParameter("either DisconnectExpiredCert or ClientIdleTimeout should be set") } if m.Conn == nil { return trace.BadParameter("missing parameter Conn") } if m.Entry == nil { return trace.BadParameter("missing parameter Entry") } if m.Tracker == nil { return trace.BadParameter("missing parameter Tracker") } if m.Audit == nil { return trace.BadParameter("missing parameter Audit") } if m.Clock == nil { m.Clock = clockwork.NewRealClock() } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/monitor.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/monitor.go#L107-L114
go
train
// NewMonitor returns a new monitor
func NewMonitor(cfg MonitorConfig) (*Monitor, error)
// NewMonitor returns a new monitor func NewMonitor(cfg MonitorConfig) (*Monitor, error)
{ if err := cfg.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &Monitor{ MonitorConfig: cfg, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/monitor.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/monitor.go#L125-L187
go
train
// Start starts monitoring connection
func (w *Monitor) Start()
// Start starts monitoring connection func (w *Monitor) Start()
{ var certTime <-chan time.Time if !w.DisconnectExpiredCert.IsZero() { t := time.NewTimer(w.DisconnectExpiredCert.Sub(w.Clock.Now().UTC())) defer t.Stop() certTime = t.C } var idleTimer *time.Timer var idleTime <-chan time.Time if w.ClientIdleTimeout != 0 { idleTimer = time.NewTimer(w.ClientIdleTimeout) idleTime = idleTimer.C } for { select { // certificate has expired, disconnect case <-certTime: event := events.EventFields{ events.EventType: events.ClientDisconnectEvent, events.EventLogin: w.Login, events.EventUser: w.TeleportUser, events.LocalAddr: w.Conn.LocalAddr().String(), events.RemoteAddr: w.Conn.RemoteAddr().String(), events.SessionServerID: w.ServerID, events.Reason: fmt.Sprintf("client certificate expired at %v", w.Clock.Now().UTC()), } w.Audit.EmitAuditEvent(events.ClientDisconnect, event) w.Entry.Debugf("Disconnecting client: %v", event[events.Reason]) w.Conn.Close() return case <-idleTime: now := w.Clock.Now().UTC() clientLastActive := w.Tracker.GetClientLastActive() if now.Sub(clientLastActive) >= w.ClientIdleTimeout { event := events.EventFields{ events.EventLogin: w.Login, events.EventUser: w.TeleportUser, events.LocalAddr: w.Conn.LocalAddr().String(), events.RemoteAddr: w.Conn.RemoteAddr().String(), events.SessionServerID: w.ServerID, } if clientLastActive.IsZero() { event[events.Reason] = "client reported no activity" } else { event[events.Reason] = fmt.Sprintf("client is idle for %v, exceeded idle timeout of %v", now.Sub(clientLastActive), w.ClientIdleTimeout) } w.Entry.Debugf("Disconnecting client: %v", event[events.Reason]) w.Audit.EmitAuditEvent(events.ClientDisconnect, event) w.Conn.Close() return } w.Entry.Debugf("Next check in %v", w.ClientIdleTimeout-now.Sub(clientLastActive)) idleTimer = time.NewTimer(w.ClientIdleTimeout - now.Sub(clientLastActive)) idleTime = idleTimer.C case <-w.Context.Done(): w.Entry.Debugf("Releasing associated resources - context has been closed.") return } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/teleport/common/teleport.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/teleport/common/teleport.go#L50-L166
go
train
// Run inits/starts the process according to the provided options
func Run(options Options) (executedCommand string, conf *service.Config)
// Run inits/starts the process according to the provided options func Run(options Options) (executedCommand string, conf *service.Config)
{ var err error // configure trace's errors to produce full stack traces isDebug, _ := strconv.ParseBool(os.Getenv(teleport.VerboseLogsEnvVar)) if isDebug { trace.SetDebug(true) } // configure logger for a typical CLI scenario until configuration file is // parsed utils.InitLogger(utils.LoggingForDaemon, log.ErrorLevel) app := utils.InitCLIParser("teleport", "Clustered SSH service. Learn more at https://gravitational.com/teleport") // define global flags: var ccf config.CommandLineFlags var scpFlags scp.Flags // define commands: start := app.Command("start", "Starts the Teleport service.") status := app.Command("status", "Print the status of the current SSH session.") dump := app.Command("configure", "Print the sample config file into stdout.") ver := app.Command("version", "Print the version.") scpc := app.Command("scp", "server-side implementation of scp").Hidden() app.HelpFlag.Short('h') // define start flags: start.Flag("debug", "Enable verbose logging to stderr"). Short('d'). BoolVar(&ccf.Debug) start.Flag("insecure-no-tls", "Disable TLS for the web socket"). BoolVar(&ccf.DisableTLS) start.Flag("roles", fmt.Sprintf("Comma-separated list of roles to start with [%s]", strings.Join(defaults.StartRoles, ","))). Short('r'). StringVar(&ccf.Roles) start.Flag("pid-file", "Full path to the PID file. By default no PID file will be created").StringVar(&ccf.PIDFile) start.Flag("advertise-ip", "IP to advertise to clients if running behind NAT"). StringVar(&ccf.AdvertiseIP) start.Flag("listen-ip", fmt.Sprintf("IP address to bind to [%s]", defaults.BindIP)). Short('l'). IPVar(&ccf.ListenIP) start.Flag("auth-server", fmt.Sprintf("Address of the auth server [%s]", defaults.AuthConnectAddr().Addr)). StringVar(&ccf.AuthServerAddr) start.Flag("token", "Invitation token to register with an auth server [none]"). StringVar(&ccf.AuthToken) start.Flag("ca-pin", "CA pin to validate the Auth Server"). StringVar(&ccf.CAPin) start.Flag("nodename", "Name of this node, defaults to hostname"). StringVar(&ccf.NodeName) start.Flag("config", fmt.Sprintf("Path to a configuration file [%v]", defaults.ConfigFilePath)). Short('c').ExistingFileVar(&ccf.ConfigFile) start.Flag("config-string", "Base64 encoded configuration string").Hidden().Envar(defaults.ConfigEnvar). StringVar(&ccf.ConfigString) start.Flag("labels", "List of labels for this node").StringVar(&ccf.Labels) start.Flag("diag-addr", "Start diangonstic prometheus and healthz endpoint.").Hidden().StringVar(&ccf.DiagnosticAddr) start.Flag("permit-user-env", "Enables reading of ~/.tsh/environment when creating a session").Hidden().BoolVar(&ccf.PermitUserEnvironment) start.Flag("insecure", "Insecure mode disables certificate validation").BoolVar(&ccf.InsecureMode) // define start's usage info (we use kingpin's "alias" field for this) start.Alias(usageNotes + usageExamples) // define a hidden 'scp' command (it implements server-side implementation of handling // 'scp' requests) scpc.Flag("t", "sink mode (data consumer)").Short('t').Default("false").BoolVar(&scpFlags.Sink) scpc.Flag("f", "source mode (data producer)").Short('f').Default("false").BoolVar(&scpFlags.Source) scpc.Flag("v", "verbose mode").Default("false").Short('v').BoolVar(&scpFlags.Verbose) scpc.Flag("r", "recursive mode").Default("false").Short('r').BoolVar(&scpFlags.Recursive) scpc.Flag("d", "directory mode").Short('d').Hidden().BoolVar(&scpFlags.DirectoryMode) scpc.Flag("remote-addr", "address of the remote client").StringVar(&scpFlags.RemoteAddr) scpc.Flag("local-addr", "local address which accepted the request").StringVar(&scpFlags.LocalAddr) scpc.Arg("target", "").StringsVar(&scpFlags.Target) // parse CLI commands+flags: command, err := app.Parse(options.Args) if err != nil { utils.FatalError(err) } // create the default configuration: conf = service.MakeDefaultConfig() // execute the selected command unless we're running tests switch command { case start.FullCommand(): // configuration merge: defaults -> file-based conf -> CLI conf if err = config.Configure(&ccf, conf); err != nil { utils.FatalError(err) } if !options.InitOnly { err = OnStart(conf) } case scpc.FullCommand(): err = onSCP(&scpFlags) case status.FullCommand(): err = onStatus() case dump.FullCommand(): onConfigDump() case ver.FullCommand(): utils.PrintVersion() } if err != nil { utils.FatalError(err) } return command, conf }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/teleport/common/teleport.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/teleport/common/teleport.go#L169-L171
go
train
// OnStart is the handler for "start" CLI command
func OnStart(config *service.Config) error
// OnStart is the handler for "start" CLI command func OnStart(config *service.Config) error
{ return service.Run(context.TODO(), *config, nil) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/teleport/common/teleport.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/teleport/common/teleport.go#L174-L195
go
train
// onStatus is the handler for "status" CLI command
func onStatus() error
// onStatus is the handler for "status" CLI command func onStatus() error
{ sshClient := os.Getenv("SSH_CLIENT") systemUser := os.Getenv("USER") teleportUser := os.Getenv(teleport.SSHTeleportUser) proxyHost := os.Getenv(teleport.SSHSessionWebproxyAddr) clusterName := os.Getenv(teleport.SSHTeleportClusterName) hostUUID := os.Getenv(teleport.SSHTeleportHostUUID) sid := os.Getenv(teleport.SSHSessionID) if sid == "" || proxyHost == "" { fmt.Println("You are not inside of a Teleport SSH session") return nil } fmt.Printf("User ID : %s, logged in as %s from %s\n", teleportUser, systemUser, sshClient) fmt.Printf("Cluster Name: %s\n", clusterName) fmt.Printf("Host UUID : %s\n", hostUUID) fmt.Printf("Session ID : %s\n", sid) fmt.Printf("Session URL : https://%s/web/cluster/%v/node/%v/%v/%v\n", proxyHost, clusterName, hostUUID, systemUser, sid) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/teleport/common/teleport.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/teleport/common/teleport.go#L208-L248
go
train
// onSCP implements handling of 'scp' requests on the server side. When the teleport SSH daemon // receives an SSH "scp" request, it launches itself with 'scp' flag under the requested // user's privileges // // This is the entry point of "teleport scp" call (the parent process is the teleport daemon)
func onSCP(scpFlags *scp.Flags) (err error)
// onSCP implements handling of 'scp' requests on the server side. When the teleport SSH daemon // receives an SSH "scp" request, it launches itself with 'scp' flag under the requested // user's privileges // // This is the entry point of "teleport scp" call (the parent process is the teleport daemon) func onSCP(scpFlags *scp.Flags) (err error)
{ // when 'teleport scp' is executed, it cannot write logs to stderr (because // they're automatically replayed by the scp client) utils.SwitchLoggingtoSyslog() if len(scpFlags.Target) == 0 { return trace.BadParameter("teleport scp: missing an argument") } // get user's home dir (it serves as a default destination) user, err := user.Current() if err != nil { return trace.Wrap(err) } // see if the target is absolute. if not, use user's homedir to make // it absolute (and if the user doesn't have a homedir, use "/") target := scpFlags.Target[0] if !filepath.IsAbs(target) { if !utils.IsDir(user.HomeDir) { slash := string(filepath.Separator) scpFlags.Target[0] = slash + target } else { scpFlags.Target[0] = filepath.Join(user.HomeDir, target) } } if !scpFlags.Source && !scpFlags.Sink { return trace.Errorf("remote mode is not supported") } scpCfg := scp.Config{ Flags: *scpFlags, User: user.Username, RunOnServer: true, } cmd, err := scp.CreateCommand(scpCfg) if err != nil { return trace.Wrap(err) } return trace.Wrap(cmd.Execute(&StdReadWriter{})) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L20-L27
go
train
// CopyByteSlice returns a copy of the byte slice.
func CopyByteSlice(in []byte) []byte
// CopyByteSlice returns a copy of the byte slice. func CopyByteSlice(in []byte) []byte
{ if in == nil { return nil } out := make([]byte, len(in)) copy(out, in) return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L30-L39
go
train
// CopyByteSlices returns a copy of the byte slices.
func CopyByteSlices(in [][]byte) [][]byte
// CopyByteSlices returns a copy of the byte slices. func CopyByteSlices(in [][]byte) [][]byte
{ if in == nil { return nil } out := make([][]byte, len(in)) for i := range in { out[i] = CopyByteSlice(in[i]) } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L42-L50
go
train
// JoinStringSlices joins two string slices and returns a resulting slice
func JoinStringSlices(a []string, b []string) []string
// JoinStringSlices joins two string slices and returns a resulting slice func JoinStringSlices(a []string, b []string) []string
{ if len(a)+len(b) == 0 { return nil } out := make([]string, 0, len(a)+len(b)) out = append(out, a...) out = append(out, b...) return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L54-L63
go
train
// CopyStrings makes a deep copy of the passed in string slice and returns // the copy.
func CopyStrings(in []string) []string
// CopyStrings makes a deep copy of the passed in string slice and returns // the copy. func CopyStrings(in []string) []string
{ if in == nil { return nil } out := make([]string, len(in)) copy(out, in) return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L67-L80
go
train
// CopyStringMapSlices makes a deep copy of the passed in map[string][]string // and returns the copy.
func CopyStringMapSlices(a map[string][]string) map[string][]string
// CopyStringMapSlices makes a deep copy of the passed in map[string][]string // and returns the copy. func CopyStringMapSlices(a map[string][]string) map[string][]string
{ if a == nil { return nil } out := make(map[string][]string) for key, values := range a { vout := make([]string, len(values)) copy(vout, values) out[key] = vout } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L83-L94
go
train
// CopyStringMap makes a deep copy of a map[string]string and returns the copy.
func CopyStringMap(a map[string]string) map[string]string
// CopyStringMap makes a deep copy of a map[string]string and returns the copy. func CopyStringMap(a map[string]string) map[string]string
{ if a == nil { return nil } out := make(map[string]string) for key, value := range a { out[key] = value } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L98-L109
go
train
// CopyStringMapInterface makes a deep copy of the passed in map[string]interface{} // and returns the copy.
func CopyStringMapInterface(a map[string]interface{}) map[string]interface{}
// CopyStringMapInterface makes a deep copy of the passed in map[string]interface{} // and returns the copy. func CopyStringMapInterface(a map[string]interface{}) map[string]interface{}
{ if a == nil { return nil } out := make(map[string]interface{}) for key, value := range a { out[key] = value } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/copy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/copy.go#L112-L124
go
train
// ReplaceInSlice replaces element old with new and returns a new slice.
func ReplaceInSlice(s []string, old string, new string) []string
// ReplaceInSlice replaces element old with new and returns a new slice. func ReplaceInSlice(s []string, old string, new string) []string
{ out := make([]string, 0, len(s)) for _, x := range s { if x == old { out = append(out, new) } else { out = append(out, x) } } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L41-L68
go
train
// reconnectToAuthService continuously attempts to reconnect to the auth // service until succeeds or process gets shut down
func (process *TeleportProcess) reconnectToAuthService(role teleport.Role) (*Connector, error)
// reconnectToAuthService continuously attempts to reconnect to the auth // service until succeeds or process gets shut down func (process *TeleportProcess) reconnectToAuthService(role teleport.Role) (*Connector, error)
{ retryTime := defaults.HighResPollingPeriod for { connector, err := process.connectToAuthService(role) if err == nil { // if connected and client is present, make sure the connector's // client works, by using call that should succeed at all times if connector.Client != nil { _, err = connector.Client.GetNamespace(defaults.Namespace) if err == nil { return connector, nil } process.Debugf("Connected client %v failed to execute test call: %v. Node or proxy credentials are out of sync.", role, err) if err := connector.Client.Close(); err != nil { process.Debugf("Failed to close the client: %v.", err) } } } process.Infof("%v failed attempt connecting to auth server: %v.", role, err) // Wait in between attempts, but return if teleport is shutting down select { case <-time.After(retryTime): case <-process.ExitContext().Done(): process.Infof("%v stopping connection attempts, teleport is shutting down.", role) return nil, ErrTeleportExited } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L72-L82
go
train
// connectToAuthService attempts to login into the auth servers specified in the // configuration and receive credentials.
func (process *TeleportProcess) connectToAuthService(role teleport.Role) (*Connector, error)
// connectToAuthService attempts to login into the auth servers specified in the // configuration and receive credentials. func (process *TeleportProcess) connectToAuthService(role teleport.Role) (*Connector, error)
{ connector, err := process.connect(role) if err != nil { return nil, trace.Wrap(err) } process.Debugf("Connected client: %v", connector.ClientIdentity) process.Debugf("Connected server: %v", connector.ServerIdentity) process.addConnector(connector) return connector, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L279-L284
go
train
// newWatcher returns a new watcher, // either using local auth server connection or remote client
func (process *TeleportProcess) newWatcher(conn *Connector, watch services.Watch) (services.Watcher, error)
// newWatcher returns a new watcher, // either using local auth server connection or remote client func (process *TeleportProcess) newWatcher(conn *Connector, watch services.Watch) (services.Watcher, error)
{ if conn.ClientIdentity.ID.Role == teleport.RoleAdmin || conn.ClientIdentity.ID.Role == teleport.RoleAuth { return process.localAuth.NewWatcher(process.ExitContext(), watch) } return conn.Client.NewWatcher(process.ExitContext(), watch) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L289-L294
go
train
// getCertAuthority returns cert authority by ID. // In case if auth servers, the role is 'TeleportAdmin' and instead of using // TLS client this method uses the local auth server.
func (process *TeleportProcess) getCertAuthority(conn *Connector, id services.CertAuthID, loadPrivateKeys bool) (services.CertAuthority, error)
// getCertAuthority returns cert authority by ID. // In case if auth servers, the role is 'TeleportAdmin' and instead of using // TLS client this method uses the local auth server. func (process *TeleportProcess) getCertAuthority(conn *Connector, id services.CertAuthID, loadPrivateKeys bool) (services.CertAuthority, error)
{ if conn.ClientIdentity.ID.Role == teleport.RoleAdmin || conn.ClientIdentity.ID.Role == teleport.RoleAuth { return process.localAuth.GetCertAuthority(id, loadPrivateKeys) } return conn.Client.GetCertAuthority(id, loadPrivateKeys) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L299-L323
go
train
// reRegister receives new identity credentials for proxy, node and auth. // In case if auth servers, the role is 'TeleportAdmin' and instead of using // TLS client this method uses the local auth server.
func (process *TeleportProcess) reRegister(conn *Connector, additionalPrincipals []string, dnsNames []string, rotation services.Rotation) (*auth.Identity, error)
// reRegister receives new identity credentials for proxy, node and auth. // In case if auth servers, the role is 'TeleportAdmin' and instead of using // TLS client this method uses the local auth server. func (process *TeleportProcess) reRegister(conn *Connector, additionalPrincipals []string, dnsNames []string, rotation services.Rotation) (*auth.Identity, error)
{ if conn.ClientIdentity.ID.Role == teleport.RoleAdmin || conn.ClientIdentity.ID.Role == teleport.RoleAuth { return auth.GenerateIdentity(process.localAuth, conn.ClientIdentity.ID, additionalPrincipals, dnsNames) } const reason = "re-register" keyPair, err := process.generateKeyPair(conn.ClientIdentity.ID.Role, reason) if err != nil { return nil, trace.Wrap(err) } identity, err := auth.ReRegister(auth.ReRegisterParams{ Client: conn.Client, ID: conn.ClientIdentity.ID, AdditionalPrincipals: additionalPrincipals, PrivateKey: keyPair.PrivateKey, PublicTLSKey: keyPair.PublicTLSKey, PublicSSHKey: keyPair.PublicSSHKey, DNSNames: dnsNames, Rotation: rotation, }) if err != nil { return nil, trace.Wrap(err) } process.deleteKeyPair(conn.ClientIdentity.ID.Role, reason) return identity, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L441-L466
go
train
// periodicSyncRotationState checks rotation state periodically and // takes action if necessary
func (process *TeleportProcess) periodicSyncRotationState() error
// periodicSyncRotationState checks rotation state periodically and // takes action if necessary func (process *TeleportProcess) periodicSyncRotationState() error
{ // start rotation only after teleport process has started eventC := make(chan Event, 1) process.WaitForEvent(process.ExitContext(), TeleportReadyEvent, eventC) select { case <-eventC: process.Infof("The new service has started successfully. Starting syncing rotation status with period %v.", process.Config.PollingPeriod) case <-process.ExitContext().Done(): return nil } retryTicker := time.NewTicker(defaults.HighResPollingPeriod) defer retryTicker.Stop() for { err := process.syncRotationStateCycle() if err == nil { return nil } process.Warningf("Sync rotation state cycle failed: %v, going to retry after %v.", err, defaults.HighResPollingPeriod) select { case <-retryTicker.C: case <-process.ExitContext().Done(): return nil } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L475-L542
go
train
// syncRotationCycle executes a rotation cycle that returns: // // * nil whenever rotation state leads to teleport reload event // * error whenever rotation sycle has to be restarted // // the function accepts extra delay timer extraDelay in case if parent // function needs a
func (process *TeleportProcess) syncRotationStateCycle() error
// syncRotationCycle executes a rotation cycle that returns: // // * nil whenever rotation state leads to teleport reload event // * error whenever rotation sycle has to be restarted // // the function accepts extra delay timer extraDelay in case if parent // function needs a func (process *TeleportProcess) syncRotationStateCycle() error
{ connectors := process.getConnectors() if len(connectors) == 0 { return trace.BadParameter("no connectors found") } // it is important to use the same view of the certificate authority // for all internal services at the same time, so that the same // procedure will be applied at the same time for multiple service process // and no internal services is left behind. conn := connectors[0] status, err := process.syncRotationStateAndBroadcast(conn) if err != nil { return trace.Wrap(err) } if status.needsReload { return nil } watcher, err := process.newWatcher(conn, services.Watch{Kinds: []services.WatchKind{{Kind: services.KindCertAuthority}}}) if err != nil { return trace.Wrap(err) } defer watcher.Close() t := time.NewTicker(process.Config.PollingPeriod) defer t.Stop() for { select { case event := <-watcher.Events(): if event.Type == backend.OpInit || event.Type == backend.OpDelete { continue } ca, ok := event.Resource.(services.CertAuthority) if !ok { process.Debugf("Skipping event %v for %v", event.Type, event.Resource.GetName()) continue } if ca.GetType() != services.HostCA && ca.GetClusterName() != conn.ClientIdentity.ClusterName { process.Debugf("Skipping event for %v %v", ca.GetType(), ca.GetClusterName()) continue } if status.ca.GetResourceID() > ca.GetResourceID() { process.Debugf("Skipping stale event %v, latest object version is %v.", ca.GetResourceID(), status.ca.GetResourceID()) continue } status, err := process.syncRotationStateAndBroadcast(conn) if err != nil { return trace.Wrap(err) } if status.needsReload { return nil } case <-watcher.Done(): return trace.ConnectionProblem(watcher.Error(), "watcher has disconnected") case <-t.C: status, err := process.syncRotationStateAndBroadcast(conn) if err != nil { return trace.Wrap(err) } if status.needsReload { return nil } case <-process.ExitContext().Done(): return nil } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L546-L570
go
train
// syncRotationStateAndBroadcast syncs rotation state and broadcasts events // when phase has been changed or reload happened
func (process *TeleportProcess) syncRotationStateAndBroadcast(conn *Connector) (*rotationStatus, error)
// syncRotationStateAndBroadcast syncs rotation state and broadcasts events // when phase has been changed or reload happened func (process *TeleportProcess) syncRotationStateAndBroadcast(conn *Connector) (*rotationStatus, error)
{ status, err := process.syncRotationState(conn) if err != nil { process.BroadcastEvent(Event{Name: TeleportDegradedEvent, Payload: nil}) if trace.IsConnectionProblem(err) { process.Warningf("Connection problem: sync rotation state: %v.", err) } else { process.Warningf("Failed to sync rotation state: %v.", err) } return nil, trace.Wrap(err) } process.BroadcastEvent(Event{Name: TeleportOKEvent, Payload: nil}) if status.phaseChanged || status.needsReload { process.Debugf("Sync rotation state detected cert authority reload phase update.") } if status.phaseChanged { process.BroadcastEvent(Event{Name: TeleportPhaseChangeEvent}) } if status.needsReload { process.Debugf("Triggering reload process.") process.BroadcastEvent(Event{Name: TeleportReloadEvent}) } return status, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L574-L598
go
train
// syncRotationState compares cluster rotation state with the state of // internal services and performs the rotation if necessary.
func (process *TeleportProcess) syncRotationState(conn *Connector) (*rotationStatus, error)
// syncRotationState compares cluster rotation state with the state of // internal services and performs the rotation if necessary. func (process *TeleportProcess) syncRotationState(conn *Connector) (*rotationStatus, error)
{ connectors := process.getConnectors() ca, err := process.getCertAuthority(conn, services.CertAuthID{ DomainName: conn.ClientIdentity.ClusterName, Type: services.HostCA, }, false) if err != nil { return nil, trace.Wrap(err) } var status rotationStatus status.ca = ca for _, conn := range connectors { serviceStatus, err := process.syncServiceRotationState(ca, conn) if err != nil { return nil, trace.Wrap(err) } if serviceStatus.needsReload { status.needsReload = true } if serviceStatus.phaseChanged { status.phaseChanged = true } } return &status, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L602-L608
go
train
// syncServiceRotationState syncs up rotation state for internal services (Auth, Proxy, Node) and // if necessary, updates credentials. Returns true if the service will need to reload.
func (process *TeleportProcess) syncServiceRotationState(ca services.CertAuthority, conn *Connector) (*rotationStatus, error)
// syncServiceRotationState syncs up rotation state for internal services (Auth, Proxy, Node) and // if necessary, updates credentials. Returns true if the service will need to reload. func (process *TeleportProcess) syncServiceRotationState(ca services.CertAuthority, conn *Connector) (*rotationStatus, error)
{ state, err := process.storage.GetState(conn.ClientIdentity.ID.Role) if err != nil { return nil, trace.Wrap(err) } return process.rotate(conn, *state, ca.GetRotation()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L623-L774
go
train
// rotate is called to check if rotation should be triggered.
func (process *TeleportProcess) rotate(conn *Connector, localState auth.StateV2, remote services.Rotation) (*rotationStatus, error)
// rotate is called to check if rotation should be triggered. func (process *TeleportProcess) rotate(conn *Connector, localState auth.StateV2, remote services.Rotation) (*rotationStatus, error)
{ id := conn.ClientIdentity.ID local := localState.Spec.Rotation additionalPrincipals, dnsNames, err := process.getAdditionalPrincipals(id.Role) if err != nil { return nil, trace.Wrap(err) } additionalPrincipals = utils.ReplaceInSlice( additionalPrincipals, defaults.AnyAddress, defaults.Localhost, ) principalsOrDNSNamesChanged := (len(additionalPrincipals) != 0 && !conn.ServerIdentity.HasPrincipals(additionalPrincipals)) || (len(dnsNames) != 0 && !conn.ServerIdentity.HasDNSNames(dnsNames)) if local.Matches(remote) && !principalsOrDNSNamesChanged { // nothing to do, local state and rotation state are in sync return &rotationStatus{}, nil } storage := process.storage const outOfSync = "%v and cluster rotation state (%v) is out of sync with local (%v). Clear local state and re-register this %v." writeStateAndIdentity := func(name string, identity *auth.Identity) error { err = storage.WriteIdentity(name, *identity) if err != nil { return trace.Wrap(err) } localState.Spec.Rotation = remote err = storage.WriteState(id.Role, localState) if err != nil { return trace.Wrap(err) } return nil } switch remote.State { case "", services.RotationStateStandby: switch local.State { // There is nothing to do, it could happen // that the old node came up and missed the whole rotation // rollback cycle. case "", services.RotationStateStandby: if principalsOrDNSNamesChanged { process.Infof("Service %v has updated principals to %q, DNS Names to %q, going to request new principals and update.", id.Role, additionalPrincipals, dnsNames) identity, err := process.reRegister(conn, additionalPrincipals, dnsNames, remote) if err != nil { return nil, trace.Wrap(err) } err = storage.WriteIdentity(auth.IdentityCurrent, *identity) if err != nil { return nil, trace.Wrap(err) } return &rotationStatus{needsReload: true}, nil } return &rotationStatus{}, nil case services.RotationStateInProgress: // Rollback phase has been completed, all services // will receive new identities. if local.Phase != services.RotationPhaseRollback && local.CurrentID != remote.CurrentID { return nil, trace.CompareFailed(outOfSync, id.Role, remote, local, id.Role) } identity, err := process.reRegister(conn, additionalPrincipals, dnsNames, remote) if err != nil { return nil, trace.Wrap(err) } err = writeStateAndIdentity(auth.IdentityCurrent, identity) if err != nil { return nil, trace.Wrap(err) } return &rotationStatus{needsReload: true}, nil default: return nil, trace.BadParameter("unsupported state: %q", localState) } case services.RotationStateInProgress: switch remote.Phase { case services.RotationPhaseStandby, "": // There is nothing to do. return &rotationStatus{}, nil case services.RotationPhaseInit: // Only allow transition in case if local rotation state is standby // so this server is in the "clean" state. if local.State != services.RotationStateStandby && local.State != "" { return nil, trace.CompareFailed(outOfSync, id.Role, remote, local, id.Role) } // only update local phase, there is no need to reload localState.Spec.Rotation = remote err = storage.WriteState(id.Role, localState) if err != nil { return nil, trace.Wrap(err) } return &rotationStatus{phaseChanged: true}, nil case services.RotationPhaseUpdateClients: // Allow transition to this phase only if the previous // phase was "Init". if local.Phase != services.RotationPhaseInit && local.CurrentID != remote.CurrentID { return nil, trace.CompareFailed(outOfSync, id.Role, remote, local, id.Role) } identity, err := process.reRegister(conn, additionalPrincipals, dnsNames, remote) if err != nil { return nil, trace.Wrap(err) } process.Debugf("Re-registered, received new identity %v.", identity) err = writeStateAndIdentity(auth.IdentityReplacement, identity) if err != nil { return nil, trace.Wrap(err) } // Require reload of teleport process to update client and servers. return &rotationStatus{needsReload: true}, nil case services.RotationPhaseUpdateServers: // Allow transition to this phase only if the previous // phase was "Update clients". if local.Phase != services.RotationPhaseUpdateClients && local.CurrentID != remote.CurrentID { return nil, trace.CompareFailed(outOfSync, id.Role, remote, local, id.Role) } // Write the replacement identity as a current identity and reload the server. replacement, err := storage.ReadIdentity(auth.IdentityReplacement, id.Role) if err != nil { return nil, trace.Wrap(err) } err = writeStateAndIdentity(auth.IdentityCurrent, replacement) if err != nil { return nil, trace.Wrap(err) } // Require reload of teleport process to update servers. return &rotationStatus{needsReload: true}, nil case services.RotationPhaseRollback: // Allow transition to this phase from any other local phase // because it will be widely used to recover cluster state to // the previously valid state, client will re-register to receive // credentials signed by the "old" CA. identity, err := process.reRegister(conn, additionalPrincipals, dnsNames, remote) if err != nil { return nil, trace.Wrap(err) } err = writeStateAndIdentity(auth.IdentityCurrent, identity) if err != nil { return nil, trace.Wrap(err) } // Require reload of teleport process to update servers. return &rotationStatus{needsReload: true}, nil default: return nil, trace.BadParameter("unsupported phase: %q", remote.Phase) } default: return nil, trace.BadParameter("unsupported state: %q", remote.State) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L778-L806
go
train
// newClient attempts to connect directly to the Auth Server. If it fails, it // falls back to trying to connect to the Auth Server through the proxy.
func (process *TeleportProcess) newClient(authServers []utils.NetAddr, identity *auth.Identity) (*auth.Client, bool, error)
// newClient attempts to connect directly to the Auth Server. If it fails, it // falls back to trying to connect to the Auth Server through the proxy. func (process *TeleportProcess) newClient(authServers []utils.NetAddr, identity *auth.Identity) (*auth.Client, bool, error)
{ directClient, err := process.newClientDirect(authServers, identity) if err != nil { return nil, false, trace.Wrap(err) } // Try and connect to the Auth Server. If the request fails, try and // connect through a tunnel. log.Debugf("Attempting to connect to Auth Server directly.") _, err = directClient.GetLocalClusterName() if err != nil { // Only attempt to connect through the proxy for nodes. if identity.ID.Role != teleport.RoleNode { return nil, false, trace.Wrap(err) } log.Debugf("Attempting to connect to Auth Server through tunnel.") tunnelClient, er := process.newClientThroughTunnel(authServers, identity) if er != nil { return nil, false, trace.NewAggregate(err, er) } log.Debugf("Connected to Auth Server through tunnel.") return tunnelClient, true, nil } log.Debugf("Connected to Auth Server with direct connection.") return directClient, false, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/service/connect.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/connect.go#L810-L835
go
train
// findReverseTunnel uses the web proxy to discover where the SSH reverse tunnel // server is running.
func (process *TeleportProcess) findReverseTunnel(addrs []utils.NetAddr) (string, error)
// findReverseTunnel uses the web proxy to discover where the SSH reverse tunnel // server is running. func (process *TeleportProcess) findReverseTunnel(addrs []utils.NetAddr) (string, error)
{ var errs []error for _, addr := range addrs { // In insecure mode, any certificate is accepted. In secure mode the hosts // CAs are used to validate the certificate on the proxy. clt, err := client.NewCredentialsClient( addr.String(), lib.IsInsecureDevMode(), nil) if err != nil { return "", trace.Wrap(err) } resp, err := clt.Find(process.ExitContext()) if err == nil { // If a tunnel public address is set, return it otherwise return the // tunnel listen address. if resp.Proxy.SSH.TunnelPublicAddr != "" { return resp.Proxy.SSH.TunnelPublicAddr, nil } return resp.Proxy.SSH.TunnelListenAddr, nil } errs = append(errs, err) } return "", trace.NewAggregate(errs...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/server.go#L47-L68
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 err := c.ForwarderConfig.CheckAndSetDefaults(); err != nil { return trace.Wrap(err) } if c.TLS == nil { return trace.BadParameter("missing parameter TLS") } c.TLS.ClientAuth = tls.RequireAndVerifyClientCert 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") } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/server.go#L78-L113
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) } fwd, err := NewForwarder(cfg.ForwarderConfig) 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 := &auth.AuthMiddleware{ AccessPoint: cfg.AccessPoint, AcceptedUsage: []string{teleport.UsageKubeOnly}, } authMiddleware.Wrap(fwd) // Wrap sets the next middleware in chain to the authMiddleware limiter.WrapHandle(authMiddleware) // force client auth if given cfg.TLS.ClientAuth = tls.VerifyClientCertIfGiven server := &TLSServer{ TLSServerConfig: cfg, Server: &http.Server{ Handler: limiter, }, } server.TLS.GetConfigForClient = server.GetConfigForClient return server, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/kube/proxy/server.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/server.go#L123-L144
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 = auth.DecodeClusterName(info.ServerName) if err != nil { if !trace.IsNotFound(err) { log.Debugf("Ignoring unsupported cluster name name %q.", info.ServerName) clusterName = "" } } } pool, err := auth.ClientCertPool(t.AccessPoint, clusterName) if err != nil { log.Errorf("failed to retrieve client pool: %v", trace.DebugReport(err)) // this falls back to the default config return nil, nil } tlsCopy := t.TLS.Clone() tlsCopy.ClientCAs = pool return tlsCopy, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/spki.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/spki.go#L30-L33
go
train
// CalculateSPKI the hash value of the SPKI header in a certificate.
func CalculateSPKI(cert *x509.Certificate) string
// CalculateSPKI the hash value of the SPKI header in a certificate. func CalculateSPKI(cert *x509.Certificate) string
{ sum := sha256.Sum256(cert.RawSubjectPublicKeyInfo) return "sha256:" + hex.EncodeToString(sum[:]) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/spki.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/spki.go#L36-L53
go
train
// CheckSPKI the passed in pin against the calculated value from a certificate.
func CheckSPKI(pin string, cert *x509.Certificate) error
// CheckSPKI the passed in pin against the calculated value from a certificate. func CheckSPKI(pin string, cert *x509.Certificate) error
{ // Check that the format of the pin is valid. parts := strings.Split(pin, ":") if len(parts) != 2 { return trace.BadParameter("invalid format for certificate pin, expected algorithm:pin") } if parts[0] != "sha256" { return trace.BadParameter("sha256 only supported hashing algorithm for certificate pin") } // Check that that pin itself matches that value calculated from the passed // in certificate. if subtle.ConstantTimeCompare([]byte(CalculateSPKI(cert)), []byte(pin)) != 1 { return trace.BadParameter(errorMessage) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L45-L59
go
train
// MakeHandler returns a new httprouter.Handle func from a handler func
func MakeHandler(fn HandlerFunc) httprouter.Handle
// MakeHandler returns a new httprouter.Handle func from a handler func func MakeHandler(fn HandlerFunc) httprouter.Handle
{ return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { // ensure that neither proxies nor browsers cache http traffic SetNoCacheHeaders(w.Header()) out, err := fn(w, r, p) if err != nil { trace.WriteError(w, err) return } if out != nil { roundtrip.ReplyJSON(w, http.StatusOK, out) } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L62-L76
go
train
// MakeStdHandler returns a new http.Handle func from http.HandlerFunc
func MakeStdHandler(fn StdHandlerFunc) http.HandlerFunc
// MakeStdHandler returns a new http.Handle func from http.HandlerFunc func MakeStdHandler(fn StdHandlerFunc) http.HandlerFunc
{ return func(w http.ResponseWriter, r *http.Request) { // ensure that neither proxies nor browsers cache http traffic SetNoCacheHeaders(w.Header()) out, err := fn(w, r) if err != nil { trace.WriteError(w, err) return } if out != nil { roundtrip.ReplyJSON(w, http.StatusOK, out) } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L79-L90
go
train
// WithCSRFProtection ensures that request to unauthenticated API is checked against CSRF attacks
func WithCSRFProtection(fn HandlerFunc) httprouter.Handle
// WithCSRFProtection ensures that request to unauthenticated API is checked against CSRF attacks func WithCSRFProtection(fn HandlerFunc) httprouter.Handle
{ hanlderFn := MakeHandler(fn) return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { err := csrf.VerifyHTTPHeader(r) if err != nil { log.Warningf("unable to validate CSRF token %v", err) trace.WriteError(w, trace.AccessDenied("access denied")) return } hanlderFn(w, r, p) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L94-L103
go
train
// ReadJSON reads HTTP json request and unmarshals it // into passed interface{} obj
func ReadJSON(r *http.Request, val interface{}) error
// ReadJSON reads HTTP json request and unmarshals it // into passed interface{} obj func ReadJSON(r *http.Request, val interface{}) error
{ data, err := ioutil.ReadAll(r.Body) if err != nil { return trace.Wrap(err) } if err := json.Unmarshal(data, &val); err != nil { return trace.BadParameter("request: %v", err.Error()) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L107-L115
go
train
// ConvertResponse converts http error to internal error type // based on HTTP response code and HTTP body contents
func ConvertResponse(re *roundtrip.Response, err error) (*roundtrip.Response, error)
// ConvertResponse converts http error to internal error type // based on HTTP response code and HTTP body contents func ConvertResponse(re *roundtrip.Response, err error) (*roundtrip.Response, error)
{ if err != nil { if uerr, ok := err.(*url.Error); ok && uerr != nil && uerr.Err != nil { return nil, trace.ConnectionProblem(uerr.Err, uerr.Error()) } return nil, trace.ConvertSystemError(err) } return re, trace.ReadError(re.Code(), re.Bytes()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L119-L131
go
train
// ParseBool will parse boolean variable from url query // returns value, ok, error
func ParseBool(q url.Values, name string) (bool, bool, error)
// ParseBool will parse boolean variable from url query // returns value, ok, error func ParseBool(q url.Values, name string) (bool, bool, error)
{ stringVal := q.Get(name) if stringVal == "" { return false, false, nil } val, err := strconv.ParseBool(stringVal) if err != nil { return false, false, trace.BadParameter( "'%v': expected 'true' or 'false', got %v", name, stringVal) } return val, true, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L143-L148
go
train
// Rewrite creates a rewrite pair, panics if in epxression // is not a valid regular expressoin
func Rewrite(in, out string) RewritePair
// Rewrite creates a rewrite pair, panics if in epxression // is not a valid regular expressoin func Rewrite(in, out string) RewritePair
{ return RewritePair{ Expr: regexp.MustCompile(in), Replacement: out, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L151-L158
go
train
// RewritePaths creates a middleware that rewrites paths in incoming request
func RewritePaths(next http.Handler, rewrites ...RewritePair) http.Handler
// RewritePaths creates a middleware that rewrites paths in incoming request func RewritePaths(next http.Handler, rewrites ...RewritePair) http.Handler
{ return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { for _, rewrite := range rewrites { req.URL.Path = rewrite.Expr.ReplaceAllString(req.URL.Path, rewrite.Replacement) } next.ServeHTTP(w, req) }) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/httplib/httplib.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httplib.go#L161-L168
go
train
// SafeRedirect performs a relative redirect to the URI part of the provided redirect URL
func SafeRedirect(w http.ResponseWriter, r *http.Request, redirectURL string) error
// SafeRedirect performs a relative redirect to the URI part of the provided redirect URL func SafeRedirect(w http.ResponseWriter, r *http.Request, redirectURL string) error
{ parsedURL, err := url.Parse(redirectURL) if err != nil { return trace.Wrap(err) } http.Redirect(w, r, parsedURL.RequestURI(), http.StatusFound) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L138-L150
go
train
// GetCertificate parses the SSH certificate bytes and returns a *ssh.Certificate.
func (c IdentityContext) GetCertificate() (*ssh.Certificate, error)
// GetCertificate parses the SSH certificate bytes and returns a *ssh.Certificate. func (c IdentityContext) GetCertificate() (*ssh.Certificate, error)
{ k, _, _, _, err := ssh.ParseAuthorizedKey(c.Certificate) if err != nil { return nil, trace.Wrap(err) } cert, ok := k.(*ssh.Certificate) if !ok { return nil, trace.BadParameter("not a certificate") } return cert, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L246-L313
go
train
// NewServerContext creates a new *ServerContext which is used to pass and // manage resources.
func NewServerContext(srv Server, conn *ssh.ServerConn, identityContext IdentityContext) (*ServerContext, error)
// NewServerContext creates a new *ServerContext which is used to pass and // manage resources. func NewServerContext(srv Server, conn *ssh.ServerConn, identityContext IdentityContext) (*ServerContext, error)
{ clusterConfig, err := srv.GetAccessPoint().GetClusterConfig() if err != nil { return nil, trace.Wrap(err) } cancelContext, cancel := context.WithCancel(context.TODO()) ctx := &ServerContext{ id: int(atomic.AddInt32(&ctxID, int32(1))), env: make(map[string]string), srv: srv, Conn: conn, ExecResultCh: make(chan ExecResult, 10), SubsystemResultCh: make(chan SubsystemResult, 10), ClusterName: conn.Permissions.Extensions[utils.CertTeleportClusterName], ClusterConfig: clusterConfig, Identity: identityContext, clientIdleTimeout: identityContext.RoleSet.AdjustClientIdleTimeout(clusterConfig.GetClientIdleTimeout()), cancelContext: cancelContext, cancel: cancel, } disconnectExpiredCert := identityContext.RoleSet.AdjustDisconnectExpiredCert(clusterConfig.GetDisconnectExpiredCert()) if !identityContext.CertValidBefore.IsZero() && disconnectExpiredCert { ctx.disconnectExpiredCert = identityContext.CertValidBefore } fields := log.Fields{ "local": conn.LocalAddr(), "remote": conn.RemoteAddr(), "login": ctx.Identity.Login, "teleportUser": ctx.Identity.TeleportUser, "id": ctx.id, } if !ctx.disconnectExpiredCert.IsZero() { fields["cert"] = ctx.disconnectExpiredCert } if ctx.clientIdleTimeout != 0 { fields["idle"] = ctx.clientIdleTimeout } ctx.Entry = log.WithFields(log.Fields{ trace.Component: srv.Component(), trace.ComponentFields: fields, }) if !ctx.disconnectExpiredCert.IsZero() || ctx.clientIdleTimeout != 0 { mon, err := NewMonitor(MonitorConfig{ DisconnectExpiredCert: ctx.disconnectExpiredCert, ClientIdleTimeout: ctx.clientIdleTimeout, Clock: ctx.srv.GetClock(), Tracker: ctx, Conn: conn, Context: cancelContext, TeleportUser: ctx.Identity.TeleportUser, Login: ctx.Identity.Login, ServerID: ctx.srv.ID(), Audit: ctx.srv.GetAuditLog(), Entry: ctx.Entry, }) if err != nil { ctx.Close() return nil, trace.Wrap(err) } go mon.Start() } return ctx, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L332-L360
go
train
// CreateOrJoinSession will look in the SessionRegistry for the session ID. If // no session is found, a new one is created. If one is found, it is returned.
func (c *ServerContext) CreateOrJoinSession(reg *SessionRegistry) error
// CreateOrJoinSession will look in the SessionRegistry for the session ID. If // no session is found, a new one is created. If one is found, it is returned. func (c *ServerContext) CreateOrJoinSession(reg *SessionRegistry) error
{ // As SSH conversation progresses, at some point a session will be created and // its ID will be added to the environment ssid, found := c.GetEnv(sshutils.SessionEnvVar) if !found { return nil } // make sure whatever session is requested is a valid session _, err := rsession.ParseID(ssid) if err != nil { return trace.BadParameter("invalid session id") } findSession := func() (*session, bool) { reg.Lock() defer reg.Unlock() return reg.findSession(rsession.ID(ssid)) } // update ctx with a session ID c.session, _ = findSession() if c.session == nil { log.Debugf("Will create new session for SSH connection %v.", c.Conn.RemoteAddr()) } else { log.Debugf("Will join session %v for SSH connection %v.", c.session, c.Conn.RemoteAddr()) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L363-L367
go
train
// GetClientLastActive returns time when client was last active
func (c *ServerContext) GetClientLastActive() time.Time
// GetClientLastActive returns time when client was last active func (c *ServerContext) GetClientLastActive() time.Time
{ c.RLock() defer c.RUnlock() return c.clientLastActive }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L371-L375
go
train
// UpdateClientActivity sets last recorded client activity associated with this context // either channel or session
func (c *ServerContext) UpdateClientActivity()
// UpdateClientActivity sets last recorded client activity associated with this context // either channel or session func (c *ServerContext) UpdateClientActivity()
{ c.Lock() defer c.Unlock() c.clientLastActive = c.srv.GetClock().Now().UTC() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L379-L383
go
train
// AddCloser adds any closer in ctx that will be called // whenever server closes session channel
func (c *ServerContext) AddCloser(closer io.Closer)
// AddCloser adds any closer in ctx that will be called // whenever server closes session channel func (c *ServerContext) AddCloser(closer io.Closer)
{ c.Lock() defer c.Unlock() c.closers = append(c.closers, closer) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L386-L390
go
train
// GetAgent returns a agent.Agent which represents the capabilities of an SSH agent.
func (c *ServerContext) GetAgent() agent.Agent
// GetAgent returns a agent.Agent which represents the capabilities of an SSH agent. func (c *ServerContext) GetAgent() agent.Agent
{ c.RLock() defer c.RUnlock() return c.agent }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L393-L397
go
train
// GetAgentChannel returns the channel over which communication with the agent occurs.
func (c *ServerContext) GetAgentChannel() ssh.Channel
// GetAgentChannel returns the channel over which communication with the agent occurs. func (c *ServerContext) GetAgentChannel() ssh.Channel
{ c.RLock() defer c.RUnlock() return c.agentChannel }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/srv/ctx.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/ctx.go#L400-L409
go
train
// SetAgent sets the agent and channel over which communication with the agent occurs.
func (c *ServerContext) SetAgent(a agent.Agent, channel ssh.Channel)
// SetAgent sets the agent and channel over which communication with the agent occurs. func (c *ServerContext) SetAgent(a agent.Agent, channel ssh.Channel)
{ c.Lock() defer c.Unlock() if c.agentChannel != nil { c.Infof("closing previous agent channel") c.agentChannel.Close() } c.agentChannel = channel c.agent = a }