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/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L296-L303 | go | train | // CheckAndSetDefaults checks and set default values for any missing fields. | func (s *ServerV2) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and set default values for any missing fields.
func (s *ServerV2) CheckAndSetDefaults() error | {
err := s.Metadata.CheckAndSetDefaults()
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L316-L349 | go | train | // CompareServers returns difference between two server
// objects, Equal (0) if identical, OnlyTimestampsDifferent(1) if only timestamps differ, Different(2) otherwise | func CompareServers(a, b Server) int | // CompareServers returns difference between two server
// objects, Equal (0) if identical, OnlyTimestampsDifferent(1) if only timestamps differ, Different(2) otherwise
func CompareServers(a, b Server) int | {
if a.GetName() != b.GetName() {
return Different
}
if a.GetAddr() != b.GetAddr() {
return Different
}
if a.GetHostname() != b.GetHostname() {
return Different
}
if a.GetNamespace() != b.GetNamespace() {
return Different
}
if a.GetPublicAddr() != b.GetPublicAddr() {
return Different
}
r := a.GetRotation()
if !r.Matches(b.GetRotation()) {
return Different
}
if a.GetUseTunnel() != b.GetUseTunnel() {
return Different
}
if !utils.StringMapsEqual(a.GetLabels(), b.GetLabels()) {
return Different
}
if !CmdLabelMapsEqual(a.GetCmdLabels(), b.GetCmdLabels()) {
return Different
}
if !a.Expiry().Equal(b.Expiry()) {
return OnlyTimestampsDifferent
}
return Equal
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L353-L367 | go | train | // CmdLabelMapsEqual compares two maps with command labels,
// returns true if label sets are equal | func CmdLabelMapsEqual(a, b map[string]CommandLabel) bool | // CmdLabelMapsEqual compares two maps with command labels,
// returns true if label sets are equal
func CmdLabelMapsEqual(a, b map[string]CommandLabel) bool | {
if len(a) != len(b) {
return false
}
for key, val := range a {
val2, ok := b[key]
if !ok {
return false
}
if !val.Equals(val2) {
return false
}
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L422-L446 | go | train | // V2 returns V2 version of the resource | func (s *ServerV1) V2() *ServerV2 | // V2 returns V2 version of the resource
func (s *ServerV1) V2() *ServerV2 | {
labels := make(map[string]CommandLabelV2, len(s.CmdLabels))
for key := range s.CmdLabels {
val := s.CmdLabels[key]
labels[key] = CommandLabelV2{
Period: Duration(val.Period),
Result: val.Result,
Command: val.Command,
}
}
return &ServerV2{
Kind: s.Kind,
Version: V2,
Metadata: Metadata{
Name: s.ID,
Namespace: ProcessNamespace(s.Namespace),
Labels: s.Labels,
},
Spec: ServerSpecV2{
Addr: s.Addr,
Hostname: s.Hostname,
CmdLabels: labels,
},
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L449-L459 | go | train | // LabelsToV2 converts labels from interface to V2 spec | func LabelsToV2(labels map[string]CommandLabel) map[string]CommandLabelV2 | // LabelsToV2 converts labels from interface to V2 spec
func LabelsToV2(labels map[string]CommandLabel) map[string]CommandLabelV2 | {
out := make(map[string]CommandLabelV2, len(labels))
for key, val := range labels {
out[key] = CommandLabelV2{
Period: NewDuration(val.GetPeriod()),
Result: val.GetResult(),
Command: val.GetCommand(),
}
}
return out
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L482-L493 | go | train | // Equals returns true if labels are equal, false otherwise | func (c *CommandLabelV2) Equals(other CommandLabel) bool | // Equals returns true if labels are equal, false otherwise
func (c *CommandLabelV2) Equals(other CommandLabel) bool | {
if c.GetPeriod() != other.GetPeriod() {
return false
}
if c.GetResult() != other.GetResult() {
return false
}
if !utils.StringSlicesEqual(c.GetCommand(), other.GetCommand()) {
return false
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L496-L504 | go | train | // Clone returns non-shallow copy of the label | func (c *CommandLabelV2) Clone() CommandLabel | // Clone returns non-shallow copy of the label
func (c *CommandLabelV2) Clone() CommandLabel | {
command := make([]string, len(c.Command))
copy(command, c.Command)
return &CommandLabelV2{
Command: command,
Period: c.Period,
Result: c.Result,
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L512-L514 | go | train | // SetPeriod sets label period | func (c *CommandLabelV2) SetPeriod(p time.Duration) | // SetPeriod sets label period
func (c *CommandLabelV2) SetPeriod(p time.Duration) | {
c.Period = Duration(p)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L546-L552 | go | train | // Clone returns copy of the set | func (c *CommandLabels) Clone() CommandLabels | // Clone returns copy of the set
func (c *CommandLabels) Clone() CommandLabels | {
out := make(CommandLabels, len(*c))
for name, label := range *c {
out[name] = label.Clone()
}
return out
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L555-L560 | go | train | // SetEnv sets the value of the label from environment variable | func (c *CommandLabels) SetEnv(v string) error | // SetEnv sets the value of the label from environment variable
func (c *CommandLabels) SetEnv(v string) error | {
if err := json.Unmarshal([]byte(v), c); err != nil {
return trace.Wrap(err, "can not parse Command Labels")
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L564-L566 | go | train | // GetServerSchema returns role schema with optionally injected
// schema for extensions | func GetServerSchema() string | // GetServerSchema returns role schema with optionally injected
// schema for extensions
func GetServerSchema() string | {
return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, fmt.Sprintf(ServerSpecV2Schema, RotationSchema), DefaultDefinitions)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L570-L622 | go | train | // UnmarshalServerResource unmarshals role from JSON or YAML,
// sets defaults and checks the schema | func UnmarshalServerResource(data []byte, kind string, cfg *MarshalConfig) (Server, error) | // UnmarshalServerResource unmarshals role from JSON or YAML,
// sets defaults and checks the schema
func UnmarshalServerResource(data []byte, kind string, cfg *MarshalConfig) (Server, error) | {
if len(data) == 0 {
return nil, trace.BadParameter("missing server data")
}
var h ResourceHeader
err := utils.FastUnmarshal(data, &h)
if err != nil {
return nil, trace.Wrap(err)
}
switch h.Version {
case "":
var s ServerV1
err := utils.FastUnmarshal(data, &s)
if err != nil {
return nil, trace.Wrap(err)
}
s.Kind = kind
v2 := s.V2()
if cfg.ID != 0 {
v2.SetResourceID(cfg.ID)
}
if !cfg.Expires.IsZero() {
v2.SetExpiry(cfg.Expires)
}
return v2, nil
case V2:
var s ServerV2
if cfg.SkipValidation {
if err := utils.FastUnmarshal(data, &s); err != nil {
return nil, trace.BadParameter(err.Error())
}
} else {
if err := utils.UnmarshalWithSchema(GetServerSchema(), &s, data); err != nil {
return nil, trace.BadParameter(err.Error())
}
}
s.Kind = kind
if err := s.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
if cfg.ID != 0 {
s.SetResourceID(cfg.ID)
}
if !cfg.Expires.IsZero() {
s.SetExpiry(cfg.Expires)
}
return &s, nil
}
return nil, trace.BadParameter("server resource version %q is not supported", h.Version)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L659-L666 | go | train | // UnmarshalServer unmarshals server from JSON | func (*TeleportServerMarshaler) UnmarshalServer(bytes []byte, kind string, opts ...MarshalOption) (Server, error) | // UnmarshalServer unmarshals server from JSON
func (*TeleportServerMarshaler) UnmarshalServer(bytes []byte, kind string, opts ...MarshalOption) (Server, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
return UnmarshalServerResource(bytes, kind, cfg)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L669-L705 | go | train | // MarshalServer marshals server into JSON. | func (*TeleportServerMarshaler) MarshalServer(s Server, opts ...MarshalOption) ([]byte, error) | // MarshalServer marshals server into JSON.
func (*TeleportServerMarshaler) MarshalServer(s Server, opts ...MarshalOption) ([]byte, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
type serverv1 interface {
V1() *ServerV1
}
type serverv2 interface {
V2() *ServerV2
}
version := cfg.GetVersion()
switch version {
case V1:
v, ok := s.(serverv1)
if !ok {
return nil, trace.BadParameter("don't know how to marshal %v", V1)
}
return utils.FastMarshal(v.V1())
case V2:
v, ok := s.(serverv2)
if !ok {
return nil, trace.BadParameter("don't know how to marshal %v", V2)
}
v2 := v.V2()
if !cfg.PreserveResourceID {
// avoid modifying the original object
// to prevent unexpected data races
copy := *v2
copy.SetResourceID(0)
v2 = ©
}
return utils.FastMarshal(v2)
default:
return nil, trace.BadParameter("version %v is not supported", version)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L709-L722 | go | train | // UnmarshalServers is used to unmarshal multiple servers from their
// binary representation. | func (*TeleportServerMarshaler) UnmarshalServers(bytes []byte) ([]Server, error) | // UnmarshalServers is used to unmarshal multiple servers from their
// binary representation.
func (*TeleportServerMarshaler) UnmarshalServers(bytes []byte) ([]Server, error) | {
var servers []ServerV2
err := utils.FastUnmarshal(bytes, &servers)
if err != nil {
return nil, trace.Wrap(err)
}
out := make([]Server, len(servers))
for i, v := range servers {
out[i] = Server(&v)
}
return out, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/server.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/server.go#L726-L733 | go | train | // MarshalServers is used to marshal multiple servers to their binary
// representation. | func (*TeleportServerMarshaler) MarshalServers(s []Server) ([]byte, error) | // MarshalServers is used to marshal multiple servers to their binary
// representation.
func (*TeleportServerMarshaler) MarshalServers(s []Server) ([]byte, error) | {
bytes, err := utils.FastMarshal(s)
if err != nil {
return nil, trace.Wrap(err)
}
return bytes, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/ui/cluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/ui/cluster.go#L45-L66 | go | train | // NewAvailableClusters returns all available clusters | func NewAvailableClusters(currentClusterName string, remoteClusters []reversetunnel.RemoteSite) *AvailableClusters | // NewAvailableClusters returns all available clusters
func NewAvailableClusters(currentClusterName string, remoteClusters []reversetunnel.RemoteSite) *AvailableClusters | {
out := AvailableClusters{}
for _, item := range remoteClusters {
cluster := Cluster{
Name: item.GetName(),
LastConnected: item.GetLastConnected(),
Status: item.GetStatus(),
}
if item.GetName() == currentClusterName {
out.Current = cluster
} else {
out.Trusted = append(out.Trusted, cluster)
}
}
sort.Slice(out.Trusted, func(i, j int) bool {
return out.Trusted[i].Name < out.Trusted[j].Name
})
return &out
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/defaults/defaults.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/defaults/defaults.go#L431-L434 | go | train | // ConfigureLimiter assigns the default parameters to a connection throttler (AKA limiter) | func ConfigureLimiter(lc *limiter.LimiterConfig) | // ConfigureLimiter assigns the default parameters to a connection throttler (AKA limiter)
func ConfigureLimiter(lc *limiter.LimiterConfig) | {
lc.MaxConnections = LimiterMaxConnections
lc.MaxNumberOfUsers = LimiterMaxConcurrentUsers
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/backend/legacy/import.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/legacy/import.go#L39-L74 | go | train | // Import imports backend data into importer unless importer has already
// imported data. If Importer has no imported data yet, exporter will
// not be initialized. This function can be called many times on the
// same importer. Importer will be closed if import has failed. | func Import(ctx context.Context, importer Importer, newExporter NewExporterFunc) error | // Import imports backend data into importer unless importer has already
// imported data. If Importer has no imported data yet, exporter will
// not be initialized. This function can be called many times on the
// same importer. Importer will be closed if import has failed.
func Import(ctx context.Context, importer Importer, newExporter NewExporterFunc) error | {
log := logrus.WithFields(logrus.Fields{
trace.Component: teleport.Component(teleport.ComponentMigrate),
})
err := func() error {
imported, err := importer.Imported(ctx)
if err != nil {
return trace.Wrap(err)
}
if imported {
log.Debugf("Detected legacy backend, data has already been imported.")
return nil
}
log.Infof("Importing data from legacy backend.")
exporter, err := newExporter()
if err != nil {
return trace.Wrap(err)
}
defer exporter.Close()
items, err := exporter.Export()
if err != nil {
return trace.Wrap(err)
}
if err := importer.Import(ctx, items); err != nil {
return trace.Wrap(err)
}
log.Infof("Successfully imported %v items.", len(items))
return nil
}()
if err != nil {
if err := importer.Close(); err != nil {
log.Errorf("Failed to close backend: %v.", err)
}
}
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/service/info.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/info.go#L33-L42 | go | train | // writeDebugInfo writes debugging information
// about this process | func writeDebugInfo(w io.Writer) | // writeDebugInfo writes debugging information
// about this process
func writeDebugInfo(w io.Writer) | {
fmt.Fprintf(w, "Runtime stats\n")
runtimeStats(w)
fmt.Fprintf(w, "Memory stats\n")
memStats(w)
fmt.Fprintf(w, "Goroutines\n")
goroutineDump(w)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/multiplexer/wrappers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/wrappers.go#L39-L41 | go | train | // Read reads from connection | func (c *Conn) Read(p []byte) (int, error) | // Read reads from connection
func (c *Conn) Read(p []byte) (int, error) | {
return c.reader.Read(p)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/multiplexer/wrappers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/wrappers.go#L44-L49 | go | train | // LocalAddr returns local address of the connection | func (c *Conn) LocalAddr() net.Addr | // LocalAddr returns local address of the connection
func (c *Conn) LocalAddr() net.Addr | {
if c.proxyLine != nil {
return &c.proxyLine.Destination
}
return c.Conn.LocalAddr()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/multiplexer/wrappers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/wrappers.go#L52-L57 | go | train | // RemoteAddr returns remote address of the connection | func (c *Conn) RemoteAddr() net.Addr | // RemoteAddr returns remote address of the connection
func (c *Conn) RemoteAddr() net.Addr | {
if c.proxyLine != nil {
return &c.proxyLine.Source
}
return c.Conn.RemoteAddr()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/multiplexer/wrappers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/wrappers.go#L84-L94 | go | train | // Accept accepts connections from parent multiplexer listener | func (l *Listener) Accept() (net.Conn, error) | // Accept accepts connections from parent multiplexer listener
func (l *Listener) Accept() (net.Conn, error) | {
select {
case <-l.context.Done():
return nil, trace.ConnectionProblem(nil, "listener is closed")
case conn := <-l.connC:
if conn == nil {
return nil, trace.ConnectionProblem(nil, "listener is closed")
}
return conn, nil
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/identity.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L220-L230 | go | train | // VerifyPassword makes sure password satisfies our requirements (relaxed),
// mostly to avoid putting garbage in | func VerifyPassword(password []byte) error | // VerifyPassword makes sure password satisfies our requirements (relaxed),
// mostly to avoid putting garbage in
func VerifyPassword(password []byte) error | {
if len(password) < defaults.MinPasswordLength {
return trace.BadParameter(
"password is too short, min length is %v", defaults.MinPasswordLength)
}
if len(password) > defaults.MaxPasswordLength {
return trace.BadParameter(
"password is too long, max length is %v", defaults.MaxPasswordLength)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/identity.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L252-L254 | go | train | // String returns debug friendly representation of this identity | func (i *ExternalIdentity) String() string | // String returns debug friendly representation of this identity
func (i *ExternalIdentity) String() string | {
return fmt.Sprintf("OIDCIdentity(connectorID=%v, username=%v)", i.ConnectorID, i.Username)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/identity.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L257-L259 | go | train | // Equals returns true if this identity equals to passed one | func (i *ExternalIdentity) Equals(other *ExternalIdentity) bool | // Equals returns true if this identity equals to passed one
func (i *ExternalIdentity) Equals(other *ExternalIdentity) bool | {
return i.ConnectorID == other.ConnectorID && i.Username == other.Username
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/identity.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L262-L270 | go | train | // Check returns nil if all parameters are great, err otherwise | func (i *ExternalIdentity) Check() error | // Check returns nil if all parameters are great, err otherwise
func (i *ExternalIdentity) Check() error | {
if i.ConnectorID == "" {
return trace.BadParameter("ConnectorID: missing value")
}
if i.Username == "" {
return trace.BadParameter("Username: missing username")
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/identity.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L301-L304 | go | train | // SetTTL sets Expires header using realtime clock | func (r *GithubAuthRequest) SetTTL(clock clockwork.Clock, ttl time.Duration) | // SetTTL sets Expires header using realtime clock
func (r *GithubAuthRequest) SetTTL(clock clockwork.Clock, ttl time.Duration) | {
expireTime := clock.Now().UTC().Add(ttl)
r.Expires = &expireTime
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/identity.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L312-L317 | go | train | // Expires returns object expiry setting. | func (r *GithubAuthRequest) Expiry() time.Time | // Expires returns object expiry setting.
func (r *GithubAuthRequest) Expiry() time.Time | {
if r.Expires == nil {
return time.Time{}
}
return *r.Expires
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/identity.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L320-L337 | go | train | // Check makes sure the request is valid | func (r *GithubAuthRequest) Check() error | // Check makes sure the request is valid
func (r *GithubAuthRequest) Check() error | {
if r.ConnectorID == "" {
return trace.BadParameter("missing ConnectorID")
}
if r.StateToken == "" {
return trace.BadParameter("missing StateToken")
}
if len(r.PublicKey) != 0 {
_, _, _, _, err := ssh.ParseAuthorizedKey(r.PublicKey)
if err != nil {
return trace.BadParameter("bad PublicKey: %v", err)
}
if (r.CertTTL > defaults.MaxCertDuration) || (r.CertTTL < defaults.MinCertDuration) {
return trace.BadParameter("wrong CertTTL")
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/identity.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L382-L400 | go | train | // Check returns nil if all parameters are great, err otherwise | func (i *OIDCAuthRequest) Check() error | // Check returns nil if all parameters are great, err otherwise
func (i *OIDCAuthRequest) Check() error | {
if i.ConnectorID == "" {
return trace.BadParameter("ConnectorID: missing value")
}
if i.StateToken == "" {
return trace.BadParameter("StateToken: missing value")
}
if len(i.PublicKey) != 0 {
_, _, _, _, err := ssh.ParseAuthorizedKey(i.PublicKey)
if err != nil {
return trace.BadParameter("PublicKey: bad key: %v", err)
}
if (i.CertTTL > defaults.MaxCertDuration) || (i.CertTTL < defaults.MinCertDuration) {
return trace.BadParameter("CertTTL: wrong certificate TTL")
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/identity.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L491-L493 | go | train | // Swap swaps two attempts | func (s SortedLoginAttempts) Swap(i, j int) | // Swap swaps two attempts
func (s SortedLoginAttempts) Swap(i, j int) | {
s[i], s[j] = s[j], s[i]
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/identity.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/identity.go#L496-L509 | go | train | // LastFailed calculates last x successive attempts are failed | func LastFailed(x int, attempts []LoginAttempt) bool | // LastFailed calculates last x successive attempts are failed
func LastFailed(x int, attempts []LoginAttempt) bool | {
var failed int
for i := len(attempts) - 1; i >= 0; i-- {
if !attempts[i].Success {
failed++
} else {
return false
}
if failed >= x {
return true
}
}
return false
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L84-L121 | go | train | // NewTerminal creates a web-based terminal based on WebSockets and returns a
// new TerminalHandler. | func NewTerminal(req TerminalRequest, authProvider AuthProvider, ctx *SessionContext) (*TerminalHandler, error) | // NewTerminal creates a web-based terminal based on WebSockets and returns a
// new TerminalHandler.
func NewTerminal(req TerminalRequest, authProvider AuthProvider, ctx *SessionContext) (*TerminalHandler, error) | {
// Make sure whatever session is requested is a valid session.
_, err := session.ParseID(string(req.SessionID))
if err != nil {
return nil, trace.BadParameter("sid: invalid session id")
}
if req.Login == "" {
return nil, trace.BadParameter("login: missing login")
}
if req.Term.W <= 0 || req.Term.H <= 0 {
return nil, trace.BadParameter("term: bad term dimensions")
}
servers, err := authProvider.GetNodes(req.Namespace, services.SkipValidation())
if err != nil {
return nil, trace.Wrap(err)
}
hostName, hostPort, err := resolveServerHostPort(req.Server, servers)
if err != nil {
return nil, trace.BadParameter("invalid server name %q: %v", req.Server, err)
}
return &TerminalHandler{
log: logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentWebsocket,
}),
params: req,
ctx: ctx,
hostName: hostName,
hostPort: hostPort,
authProvider: authProvider,
encoder: unicode.UTF8.NewEncoder(),
decoder: unicode.UTF8.NewDecoder(),
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L173-L188 | go | train | // Serve builds a connect to the remote node and then pumps back two types of
// events: raw input/output events for what's happening on the terminal itself
// and audit log events relevant to this session. | func (t *TerminalHandler) Serve(w http.ResponseWriter, r *http.Request) | // Serve builds a connect to the remote node and then pumps back two types of
// events: raw input/output events for what's happening on the terminal itself
// and audit log events relevant to this session.
func (t *TerminalHandler) Serve(w http.ResponseWriter, r *http.Request) | {
// This allows closing of the websocket if the user logs out before exiting
// the session.
t.ctx.AddClosers(t)
defer t.ctx.RemoveCloser(t)
// We initial a server explicitly here instead of using websocket.HandlerFunc
// to set an empty origin checker (this is to make our lives easier in tests).
// The main use of the origin checker is to enforce the browsers same-origin
// policy. That does not matter here because even if malicious Javascript
// would try and open a websocket the request to this endpoint requires the
// bearer token to be in the URL so it would not be sent along by default
// like cookies are.
ws := &websocket.Server{Handler: t.handler}
ws.ServeHTTP(w, r)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L191-L207 | go | train | // Close the websocket stream. | func (t *TerminalHandler) Close() error | // Close the websocket stream.
func (t *TerminalHandler) Close() error | {
// Close the websocket connection to the client web browser.
if t.ws != nil {
t.ws.Close()
}
// Close the SSH connection to the remote node.
if t.sshSession != nil {
t.sshSession.Close()
}
// If the terminal handler was closed (most likely due to the *SessionContext
// closing) then the stream should be closed as well.
t.terminalCancel()
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L212-L236 | go | train | // handler is the main websocket loop. It creates a Teleport client and then
// pumps raw events and audit events back to the client until the SSH session
// is complete. | func (t *TerminalHandler) handler(ws *websocket.Conn) | // handler is the main websocket loop. It creates a Teleport client and then
// pumps raw events and audit events back to the client until the SSH session
// is complete.
func (t *TerminalHandler) handler(ws *websocket.Conn) | {
// Create a Teleport client, if not able to, show the reason to the user in
// the terminal.
tc, err := t.makeClient(ws)
if err != nil {
er := t.writeError(err, ws)
if er != nil {
t.log.Warnf("Unable to send error to terminal: %v: %v.", err, er)
}
return
}
// Create a context for signaling when the terminal session is over.
t.terminalContext, t.terminalCancel = context.WithCancel(context.Background())
t.log.Debugf("Creating websocket stream for %v.", t.params.SessionID)
// Pump raw terminal in/out and audit events into the websocket.
go t.streamTerminal(ws, tc)
go t.streamEvents(ws, tc)
// Block until the terminal session is complete.
<-t.terminalContext.Done()
t.log.Debugf("Closing websocket stream for %v.", t.params.SessionID)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L239-L284 | go | train | // makeClient builds a *client.TeleportClient for the connection. | func (t *TerminalHandler) makeClient(ws *websocket.Conn) (*client.TeleportClient, error) | // makeClient builds a *client.TeleportClient for the connection.
func (t *TerminalHandler) makeClient(ws *websocket.Conn) (*client.TeleportClient, error) | {
clientConfig, err := makeTeleportClientConfig(t.ctx)
if err != nil {
return nil, trace.Wrap(err)
}
// Create a terminal stream that wraps/unwraps the envelope used to
// communicate over the websocket.
stream, err := t.asTerminalStream(ws)
if err != nil {
return nil, trace.Wrap(err)
}
clientConfig.ForwardAgent = true
clientConfig.HostLogin = t.params.Login
clientConfig.Namespace = t.params.Namespace
clientConfig.Stdout = stream
clientConfig.Stderr = stream
clientConfig.Stdin = stream
clientConfig.SiteName = t.params.Cluster
clientConfig.ParseProxyHost(t.params.ProxyHostPort)
clientConfig.Host = t.hostName
clientConfig.HostPort = t.hostPort
clientConfig.Env = map[string]string{sshutils.SessionEnvVar: string(t.params.SessionID)}
clientConfig.ClientAddr = ws.Request().RemoteAddr
if len(t.params.InteractiveCommand) > 0 {
clientConfig.Interactive = true
}
tc, err := client.NewClient(clientConfig)
if err != nil {
return nil, trace.BadParameter("failed to create client: %v", err)
}
// Save the *ssh.Session after the shell has been created. The session is
// used to update all other parties window size to that of the web client and
// to allow future window changes.
tc.OnShellCreated = func(s *ssh.Session, c *ssh.Client, _ io.ReadWriteCloser) (bool, error) {
t.sshSession = s
t.windowChange(&t.params.Term)
return false, nil
}
return tc, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L288-L320 | go | train | // streamTerminal opens a SSH connection to the remote host and streams
// events back to the web client. | func (t *TerminalHandler) streamTerminal(ws *websocket.Conn, tc *client.TeleportClient) | // streamTerminal opens a SSH connection to the remote host and streams
// events back to the web client.
func (t *TerminalHandler) streamTerminal(ws *websocket.Conn, tc *client.TeleportClient) | {
defer t.terminalCancel()
// Establish SSH connection to the server. This function will block until
// either an error occurs or it completes successfully.
err := tc.SSH(t.terminalContext, t.params.InteractiveCommand, false)
if err != nil {
t.log.Warnf("Unable to stream terminal: %v.", err)
er := t.writeError(err, ws)
if er != nil {
t.log.Warnf("Unable to send error to terminal: %v: %v.", err, er)
}
return
}
// Send close envelope to web terminal upon exit without an error.
envelope := &Envelope{
Version: defaults.WebsocketVersion,
Type: defaults.WebsocketClose,
Payload: "",
}
envelopeBytes, err := proto.Marshal(envelope)
if err != nil {
t.log.Errorf("Unable to marshal close event for web client.")
return
}
err = websocket.Message.Send(ws, envelopeBytes)
if err != nil {
t.log.Errorf("Unable to send close event to web client.")
return
}
t.log.Debugf("Sent close event to web client.")
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L324-L366 | go | train | // streamEvents receives events over the SSH connection and forwards them to
// the web client. | func (t *TerminalHandler) streamEvents(ws *websocket.Conn, tc *client.TeleportClient) | // streamEvents receives events over the SSH connection and forwards them to
// the web client.
func (t *TerminalHandler) streamEvents(ws *websocket.Conn, tc *client.TeleportClient) | {
for {
select {
// Send push events that come over the events channel to the web client.
case event := <-tc.EventsChannel():
data, err := json.Marshal(event)
if err != nil {
t.log.Errorf("Unable to marshal audit event %v: %v.", event.GetType(), err)
continue
}
t.log.Debugf("Sending audit event %v to web client.", event.GetType())
// UTF-8 encode the error message and then wrap it in a raw envelope.
encodedPayload, err := t.encoder.String(string(data))
if err != nil {
t.log.Debugf("Unable to send audit event %v to web client: %v.", event.GetType(), err)
continue
}
envelope := &Envelope{
Version: defaults.WebsocketVersion,
Type: defaults.WebsocketAudit,
Payload: encodedPayload,
}
envelopeBytes, err := proto.Marshal(envelope)
if err != nil {
t.log.Debugf("Unable to send audit event %v to web client: %v.", event.GetType(), err)
continue
}
// Send bytes over the websocket to the web client.
err = websocket.Message.Send(ws, envelopeBytes)
if err != nil {
t.log.Errorf("Unable to send audit event %v to web client: %v.", event.GetType(), err)
continue
}
// Once the terminal stream is over (and the close envelope has been sent),
// close stop streaming envelopes.
case <-t.terminalContext.Done():
return
}
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L370-L387 | go | train | // windowChange is called when the browser window is resized. It sends a
// "window-change" channel request to the server. | func (t *TerminalHandler) windowChange(params *session.TerminalParams) error | // windowChange is called when the browser window is resized. It sends a
// "window-change" channel request to the server.
func (t *TerminalHandler) windowChange(params *session.TerminalParams) error | {
if t.sshSession == nil {
return nil
}
_, err := t.sshSession.SendRequest(
sshutils.WindowChangeRequest,
false,
ssh.Marshal(sshutils.WinChangeReqParams{
W: uint32(params.W),
H: uint32(params.H),
}))
if err != nil {
t.log.Error(err)
}
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L390-L400 | go | train | // writeError displays an error in the terminal window. | func (t *TerminalHandler) writeError(err error, ws *websocket.Conn) error | // writeError displays an error in the terminal window.
func (t *TerminalHandler) writeError(err error, ws *websocket.Conn) error | {
// Replace \n with \r\n so the message correctly aligned.
r := strings.NewReplacer("\r\n", "\r\n", "\n", "\r\n")
errMessage := r.Replace(err.Error())
_, err = t.write([]byte(errMessage), ws)
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L404-L436 | go | train | // resolveServerHostPort parses server name and attempts to resolve hostname
// and port. | func resolveServerHostPort(servername string, existingServers []services.Server) (string, int, error) | // resolveServerHostPort parses server name and attempts to resolve hostname
// and port.
func resolveServerHostPort(servername string, existingServers []services.Server) (string, int, error) | {
// If port is 0, client wants us to figure out which port to use.
var defaultPort = 0
if servername == "" {
return "", defaultPort, trace.BadParameter("empty server name")
}
// Check if servername is UUID.
for i := range existingServers {
node := existingServers[i]
if node.GetName() == servername {
return node.GetHostname(), defaultPort, nil
}
}
if !strings.Contains(servername, ":") {
return servername, defaultPort, nil
}
// Check for explicitly specified port.
host, portString, err := utils.SplitHostPort(servername)
if err != nil {
return "", defaultPort, trace.Wrap(err)
}
port, err := strconv.Atoi(portString)
if err != nil {
return "", defaultPort, trace.BadParameter("invalid port: %v", err)
}
return host, port, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L465-L526 | go | train | // Read unwraps the envelope and either fills out the passed in bytes or
// performs an action on the connection (sending window-change request). | func (t *TerminalHandler) read(out []byte, ws *websocket.Conn) (n int, err error) | // Read unwraps the envelope and either fills out the passed in bytes or
// performs an action on the connection (sending window-change request).
func (t *TerminalHandler) read(out []byte, ws *websocket.Conn) (n int, err error) | {
if len(t.buffer) > 0 {
n := copy(out, t.buffer)
if n == len(t.buffer) {
t.buffer = []byte{}
} else {
t.buffer = t.buffer[n:]
}
return n, nil
}
var bytes []byte
err = websocket.Message.Receive(ws, &bytes)
if err != nil {
if err == io.EOF {
return 0, io.EOF
}
return 0, trace.Wrap(err)
}
var envelope Envelope
err = proto.Unmarshal(bytes, &envelope)
if err != nil {
return 0, trace.Wrap(err)
}
var data []byte
data, err = t.decoder.Bytes([]byte(envelope.GetPayload()))
if err != nil {
return 0, trace.Wrap(err)
}
switch string(envelope.GetType()) {
case defaults.WebsocketRaw:
n := copy(out, data)
// if payload size is greater than [out], store the remaining
// part in the buffer to be processed on the next Read call
if len(data) > n {
t.buffer = data[n:]
}
return n, nil
case defaults.WebsocketResize:
var e events.EventFields
err := json.Unmarshal(data, &e)
if err != nil {
return 0, trace.Wrap(err)
}
params, err := session.UnmarshalTerminalParams(e.GetString("size"))
if err != nil {
return 0, trace.Wrap(err)
}
// Send the window change request in a goroutine so reads are not blocked
// by network connectivity issues.
go t.windowChange(params)
return 0, nil
default:
return 0, trace.BadParameter("unknown prefix type: %v", envelope.GetType())
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L544-L546 | go | train | // Write wraps the data bytes in a raw envelope and sends. | func (w *terminalStream) Write(data []byte) (n int, err error) | // Write wraps the data bytes in a raw envelope and sends.
func (w *terminalStream) Write(data []byte) (n int, err error) | {
return w.terminal.write(data, w.ws)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L550-L552 | go | train | // Read unwraps the envelope and either fills out the passed in bytes or
// performs an action on the connection (sending window-change request). | func (w *terminalStream) Read(out []byte) (n int, err error) | // Read unwraps the envelope and either fills out the passed in bytes or
// performs an action on the connection (sending window-change request).
func (w *terminalStream) Read(out []byte) (n int, err error) | {
return w.terminal.read(out, w.ws)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/terminal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/terminal.go#L555-L557 | go | train | // SetReadDeadline sets the network read deadline on the underlying websocket. | func (w *terminalStream) SetReadDeadline(t time.Time) error | // SetReadDeadline sets the network read deadline on the underlying websocket.
func (w *terminalStream) SetReadDeadline(t time.Time) error | {
return w.ws.SetReadDeadline(t)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L102-L140 | go | train | // CheckAndSetDefaults checks and sets default values | func (f *ForwarderConfig) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets default values
func (f *ForwarderConfig) CheckAndSetDefaults() error | {
if f.Client == nil {
return trace.BadParameter("missing parameter Client")
}
if f.AccessPoint == nil {
return trace.BadParameter("missing parameter AccessPoint")
}
if f.Auth == nil {
return trace.BadParameter("missing parameter Auth")
}
if f.Tunnel == nil {
return trace.BadParameter("missing parameter Tunnel")
}
if f.ClusterName == "" {
return trace.BadParameter("missing parameter LocalCluster")
}
if f.Keygen == nil {
return trace.BadParameter("missing parameter Keygen")
}
if f.DataDir == "" {
return trace.BadParameter("missing parameter DataDir")
}
if f.ServerID == "" {
return trace.BadParameter("missing parameter ServerID")
}
if f.TargetAddr == "" {
f.TargetAddr = teleport.KubeServiceAddr
}
if f.Namespace == "" {
f.Namespace = defaults.Namespace
}
if f.Context == nil {
f.Context = context.TODO()
}
if f.Clock == nil {
f.Clock = clockwork.NewRealClock()
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L144-L187 | go | train | // NewForwarder returns new instance of Kubernetes request
// forwarding proxy. | func NewForwarder(cfg ForwarderConfig) (*Forwarder, error) | // NewForwarder returns new instance of Kubernetes request
// forwarding proxy.
func NewForwarder(cfg ForwarderConfig) (*Forwarder, error) | {
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
creds, err := getKubeCreds(cfg.KubeconfigPath)
if err != nil {
return nil, trace.Wrap(err)
}
clusterSessions, err := ttlmap.New(defaults.ClientCacheSize)
if err != nil {
return nil, trace.Wrap(err)
}
closeCtx, close := context.WithCancel(cfg.Context)
fwd := &Forwarder{
creds: *creds,
Entry: log.WithFields(log.Fields{
trace.Component: teleport.Component(teleport.ComponentKube),
}),
Router: *httprouter.New(),
ForwarderConfig: cfg,
clusterSessions: clusterSessions,
activeRequests: make(map[string]context.Context),
ctx: closeCtx,
close: close,
}
fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/exec", fwd.withAuth(fwd.exec))
fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/exec", fwd.withAuth(fwd.exec))
fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/attach", fwd.withAuth(fwd.exec))
fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/attach", fwd.withAuth(fwd.exec))
fwd.POST("/api/:ver/namespaces/:podNamespace/pods/:podName/portforward", fwd.withAuth(fwd.portForward))
fwd.GET("/api/:ver/namespaces/:podNamespace/pods/:podName/portforward", fwd.withAuth(fwd.portForward))
fwd.NotFound = fwd.withAuthStd(fwd.catchAll)
if cfg.ClusterOverride != "" {
fwd.Debugf("Cluster override is set, forwarder will send all requests to remote cluster %v.", cfg.ClusterOverride)
}
return fwd, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L274-L321 | go | train | // authenticate function authenticates request | func (f *Forwarder) authenticate(req *http.Request) (*authContext, error) | // authenticate function authenticates request
func (f *Forwarder) authenticate(req *http.Request) (*authContext, error) | {
const accessDeniedMsg = "[00] access denied"
var isRemoteUser bool
userTypeI := req.Context().Value(auth.ContextUser)
switch userTypeI.(type) {
case auth.LocalUser:
case auth.RemoteUser:
isRemoteUser = true
default:
f.Warningf("Denying proxy access to unsupported user type: %T.", userTypeI)
return nil, trace.AccessDenied(accessDeniedMsg)
}
userContext, err := f.Auth.Authorize(req.Context())
if err != nil {
switch {
// propagate connection problem error so we can differentiate
// between connection failed and access denied
case trace.IsConnectionProblem(err):
return nil, trace.ConnectionProblem(err, "[07] failed to connect to the database")
case trace.IsAccessDenied(err):
// don't print stack trace, just log the warning
f.Warn(err)
return nil, trace.AccessDenied(accessDeniedMsg)
default:
f.Warn(trace.DebugReport(err))
return nil, trace.AccessDenied(accessDeniedMsg)
}
}
peers := req.TLS.PeerCertificates
if len(peers) > 1 {
// when turning intermediaries on, don't forget to verify
// https://github.com/kubernetes/kubernetes/pull/34524/files#diff-2b283dde198c92424df5355f39544aa4R59
return nil, trace.AccessDenied("access denied: intermediaries are not supported")
}
if len(peers) == 0 {
return nil, trace.AccessDenied("access denied: only mutual TLS authentication is supported")
}
clientCert := peers[0]
authContext, err := f.setupContext(*userContext, req, isRemoteUser, clientCert.NotAfter)
if err != nil {
f.Warn(err.Error())
return nil, trace.AccessDenied(accessDeniedMsg)
}
return authContext, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L418-L565 | go | train | // exec forwards all exec requests to the target server, captures
// all output from the session | func (f *Forwarder) exec(ctx *authContext, w http.ResponseWriter, req *http.Request, p httprouter.Params) (interface{}, error) | // exec forwards all exec requests to the target server, captures
// all output from the session
func (f *Forwarder) exec(ctx *authContext, w http.ResponseWriter, req *http.Request, p httprouter.Params) (interface{}, error) | {
f.Debugf("Exec %v.", req.URL.String())
q := req.URL.Query()
request := remoteCommandRequest{
podNamespace: p.ByName("podNamespace"),
podName: p.ByName("podName"),
containerName: q.Get("container"),
cmd: q["command"],
stdin: utils.AsBool(q.Get("stdin")),
stdout: utils.AsBool(q.Get("stdout")),
stderr: utils.AsBool(q.Get("stderr")),
tty: utils.AsBool(q.Get("tty")),
httpRequest: req,
httpResponseWriter: w,
context: req.Context(),
}
var recorder events.SessionRecorder
sessionID := session.NewID()
var err error
if request.tty {
// create session recorder
// get the audit log from the server and create a session recorder. this will
// be a discard audit log if the proxy is in recording mode and a teleport
// node so we don't create double recordings.
recorder, err = events.NewForwardRecorder(events.ForwardRecorderConfig{
DataDir: filepath.Join(f.DataDir, teleport.LogsDir),
SessionID: sessionID,
Namespace: f.Namespace,
RecordSessions: ctx.clusterConfig.GetSessionRecording() != services.RecordOff,
Component: teleport.Component(teleport.ComponentSession, teleport.ComponentKube),
ForwardTo: f.AuditLog,
})
if err != nil {
return nil, trace.Wrap(err)
}
defer recorder.Close()
request.onResize = func(resize remotecommand.TerminalSize) {
params := session.TerminalParams{
W: int(resize.Width),
H: int(resize.Height),
}
// Build the resize event.
resizeEvent := events.EventFields{
events.EventProtocol: events.EventProtocolKube,
events.EventType: events.ResizeEvent,
events.EventNamespace: f.Namespace,
events.SessionEventID: sessionID,
events.EventLogin: ctx.User.GetName(),
events.EventUser: ctx.User.GetName(),
events.TerminalSize: params.Serialize(),
}
// Report the updated window size to the event log (this is so the sessions
// can be replayed correctly).
recorder.GetAuditLog().EmitAuditEvent(events.TerminalResize, resizeEvent)
}
}
sess, err := f.getOrCreateClusterSession(*ctx)
if err != nil {
return nil, trace.Wrap(err)
}
if request.tty {
// Emit "new session created" event. There are no initial terminal
// parameters per k8s protocol, so set up with any default
termParams := session.TerminalParams{
W: 100,
H: 100,
}
recorder.GetAuditLog().EmitAuditEvent(events.SessionStart, events.EventFields{
events.EventProtocol: events.EventProtocolKube,
events.EventNamespace: f.Namespace,
events.SessionEventID: string(sessionID),
events.SessionServerID: f.ServerID,
events.EventLogin: ctx.User.GetName(),
events.EventUser: ctx.User.GetName(),
events.LocalAddr: sess.cluster.targetAddr,
events.RemoteAddr: req.RemoteAddr,
events.TerminalSize: termParams.Serialize(),
})
}
if err := f.setupForwardingHeaders(ctx, sess, req); err != nil {
return nil, trace.Wrap(err)
}
proxy, err := createRemoteCommandProxy(request)
if err != nil {
return nil, trace.Wrap(err)
}
defer proxy.Close()
f.Debugf("Created streams, getting executor.")
executor, err := f.getExecutor(*ctx, sess, req)
if err != nil {
return nil, trace.Wrap(err)
}
streamOptions := proxy.options()
if request.tty {
// capture stderr and stdout writes to session recorder
streamOptions.Stdout = utils.NewBroadcastWriter(streamOptions.Stdout, recorder)
streamOptions.Stderr = utils.NewBroadcastWriter(streamOptions.Stderr, recorder)
}
err = executor.Stream(streamOptions)
if err := proxy.sendStatus(err); err != nil {
f.Warningf("Failed to send status: %v. Exec command was aborted by client.", err)
return nil, trace.Wrap(err)
}
if request.tty {
// send an event indicating that this session has ended
recorder.GetAuditLog().EmitAuditEvent(events.SessionEnd, events.EventFields{
events.EventProtocol: events.EventProtocolKube,
events.SessionEventID: sessionID,
events.EventUser: ctx.User.GetName(),
events.EventNamespace: f.Namespace,
})
} else {
f.Debugf("No tty, sending exec event.")
// send an exec event
fields := events.EventFields{
events.EventProtocol: events.EventProtocolKube,
events.ExecEventCommand: strings.Join(request.cmd, " "),
events.EventLogin: ctx.User.GetName(),
events.EventUser: ctx.User.GetName(),
events.LocalAddr: sess.cluster.targetAddr,
events.RemoteAddr: req.RemoteAddr,
events.EventNamespace: f.Namespace,
}
if err != nil {
fields[events.ExecEventError] = err.Error()
if exitErr, ok := err.(utilexec.ExitError); ok && exitErr.Exited() {
fields[events.ExecEventCode] = fmt.Sprintf("%d", exitErr.ExitStatus())
}
f.AuditLog.EmitAuditEvent(events.ExecFailure, fields)
} else {
f.AuditLog.EmitAuditEvent(events.Exec, fields)
}
}
f.Debugf("Exited successfully.")
return nil, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L568-L619 | go | train | // portForward starts port forwarding to the remote cluster | func (f *Forwarder) portForward(ctx *authContext, w http.ResponseWriter, req *http.Request, p httprouter.Params) (interface{}, error) | // portForward starts port forwarding to the remote cluster
func (f *Forwarder) portForward(ctx *authContext, w http.ResponseWriter, req *http.Request, p httprouter.Params) (interface{}, error) | {
f.Debugf("Port forward: %v. req headers: %v", req.URL.String(), req.Header)
sess, err := f.getOrCreateClusterSession(*ctx)
if err != nil {
return nil, trace.Wrap(err)
}
if err := f.setupForwardingHeaders(ctx, sess, req); err != nil {
f.Debugf("DENIED Port forward: %v.", req.URL.String())
return nil, trace.Wrap(err)
}
dialer, err := f.getDialer(*ctx, sess, req)
if err != nil {
return nil, trace.Wrap(err)
}
onPortForward := func(addr string, success bool) {
event := events.PortForward
if !success {
event = events.PortForwardFailure
}
f.AuditLog.EmitAuditEvent(event, events.EventFields{
events.EventProtocol: events.EventProtocolKube,
events.PortForwardAddr: addr,
events.PortForwardSuccess: success,
events.EventLogin: ctx.User.GetName(),
events.EventUser: ctx.User.GetName(),
events.LocalAddr: sess.cluster.targetAddr,
events.RemoteAddr: req.RemoteAddr,
})
}
q := req.URL.Query()
request := portForwardRequest{
podNamespace: p.ByName("podNamespace"),
podName: p.ByName("podName"),
ports: q["ports"],
context: req.Context(),
httpRequest: req,
httpResponseWriter: w,
onPortForward: onPortForward,
targetDialer: dialer,
}
f.Debugf("Starting %v.", request)
err = runPortForwarding(request)
if err != nil {
return nil, trace.Wrap(err)
}
f.Debugf("Done %v.", request)
return nil, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L655-L665 | go | train | // catchAll forwards all HTTP requests to the target k8s API server | func (f *Forwarder) catchAll(ctx *authContext, w http.ResponseWriter, req *http.Request) (interface{}, error) | // catchAll forwards all HTTP requests to the target k8s API server
func (f *Forwarder) catchAll(ctx *authContext, w http.ResponseWriter, req *http.Request) (interface{}, error) | {
sess, err := f.getOrCreateClusterSession(*ctx)
if err != nil {
return nil, trace.Wrap(err)
}
if err := f.setupForwardingHeaders(ctx, sess, req); err != nil {
return nil, trace.Wrap(err)
}
sess.forwarder.ServeHTTP(w, req)
return nil, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L759-L763 | go | train | // Read reads data from the connection.
// Read can be made to time out and return an Error with Timeout() == true
// after a fixed time limit; see SetDeadline and SetReadDeadline. | func (t *trackingConn) Read(b []byte) (int, error) | // Read reads data from the connection.
// Read can be made to time out and return an Error with Timeout() == true
// after a fixed time limit; see SetDeadline and SetReadDeadline.
func (t *trackingConn) Read(b []byte) (int, error) | {
n, err := t.Conn.Read(b)
t.UpdateClientActivity()
return n, err
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L771-L775 | go | train | // GetClientLastActive returns time when client was last active | func (t *trackingConn) GetClientLastActive() time.Time | // GetClientLastActive returns time when client was last active
func (t *trackingConn) GetClientLastActive() time.Time | {
t.RLock()
defer t.RUnlock()
return t.lastActive
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L778-L782 | go | train | // UpdateClientActivity sets last recorded client activity | func (t *trackingConn) UpdateClientActivity() | // UpdateClientActivity sets last recorded client activity
func (t *trackingConn) UpdateClientActivity() | {
t.Lock()
defer t.Unlock()
t.lastActive = t.clock.Now().UTC()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L936-L951 | go | train | // getOrCreateRequestContext creates a new certificate request for a given context,
// if there is no active CSR request in progress, or returns an existing one.
// if the new context has been created, cancel function is returned as a
// second argument. Caller should call this function to signal that CSR has been
// completed or failed. | func (f *Forwarder) getOrCreateRequestContext(key string) (context.Context, context.CancelFunc) | // getOrCreateRequestContext creates a new certificate request for a given context,
// if there is no active CSR request in progress, or returns an existing one.
// if the new context has been created, cancel function is returned as a
// second argument. Caller should call this function to signal that CSR has been
// completed or failed.
func (f *Forwarder) getOrCreateRequestContext(key string) (context.Context, context.CancelFunc) | {
f.Lock()
defer f.Unlock()
ctx, ok := f.activeRequests[key]
if ok {
return ctx, nil
}
ctx, cancel := context.WithCancel(context.TODO())
f.activeRequests[key] = ctx
return ctx, func() {
cancel()
f.Lock()
defer f.Unlock()
delete(f.activeRequests, key)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/forwarder.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/forwarder.go#L1079-L1089 | go | train | // parseKubeHost parses and formats kubernetes hostname
// to host:port format, if no port it set,
// it assumes default HTTPS port | func parseKubeHost(host string) (string, error) | // parseKubeHost parses and formats kubernetes hostname
// to host:port format, if no port it set,
// it assumes default HTTPS port
func parseKubeHost(host string) (string, error) | {
u, err := url.Parse(host)
if err != nil {
return "", trace.Wrap(err, "failed to parse kubernetes host")
}
if _, _, err := net.SplitHostPort(u.Host); err != nil {
// add default HTTPS port
return fmt.Sprintf("%v:443", u.Host), nil
}
return u.Host, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/multiplexer/proxyline.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/proxyline.go#L55-L57 | go | train | // String returns on-the wire string representation of the proxy line | func (p *ProxyLine) String() string | // String returns on-the wire string representation of the proxy line
func (p *ProxyLine) String() string | {
return fmt.Sprintf("PROXY %s %s %s %d %d\r\n", p.Protocol, p.Source.IP.String(), p.Destination.IP.String(), p.Source.Port, p.Destination.Port)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/multiplexer/proxyline.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/multiplexer/proxyline.go#L60-L100 | go | train | // ReadProxyLine reads proxy line protocol from the reader | func ReadProxyLine(reader *bufio.Reader) (*ProxyLine, error) | // ReadProxyLine reads proxy line protocol from the reader
func ReadProxyLine(reader *bufio.Reader) (*ProxyLine, error) | {
line, err := reader.ReadString('\n')
if err != nil {
return nil, trace.Wrap(err)
}
if !strings.HasSuffix(line, proxyCRLF) {
return nil, trace.BadParameter("expected CRLF in proxy protocol, got something else")
}
tokens := strings.Split(line[:len(line)-2], proxySep)
ret := ProxyLine{}
if len(tokens) < 6 {
return nil, trace.BadParameter("malformed PROXY line protocol string")
}
switch tokens[1] {
case TCP4:
ret.Protocol = TCP4
case TCP6:
ret.Protocol = TCP6
default:
ret.Protocol = UNKNOWN
}
sourceIP, err := parseIP(ret.Protocol, tokens[2])
if err != nil {
return nil, trace.Wrap(err)
}
destIP, err := parseIP(ret.Protocol, tokens[3])
if err != nil {
return nil, trace.Wrap(err)
}
sourcePort, err := parsePortNumber(tokens[4])
if err != nil {
return nil, trace.Wrap(err)
}
destPort, err := parsePortNumber(tokens[5])
if err != nil {
return nil, err
}
ret.Source = net.TCPAddr{IP: sourceIP, Port: sourcePort}
ret.Destination = net.TCPAddr{IP: destIP, Port: destPort}
return &ret, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/service/state.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/state.go#L46-L52 | go | train | // newProcessState returns a new FSM that tracks the state of the Teleport process. | func newProcessState(process *TeleportProcess) *processState | // newProcessState returns a new FSM that tracks the state of the Teleport process.
func newProcessState(process *TeleportProcess) *processState | {
return &processState{
process: process,
recoveryTime: process.Clock.Now(),
currentState: stateOK,
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/service/state.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/service/state.go#L55-L83 | go | train | // Process updates the state of Teleport. | func (f *processState) Process(event Event) | // Process updates the state of Teleport.
func (f *processState) Process(event Event) | {
switch event.Name {
// Ready event means Teleport has started successfully.
case TeleportReadyEvent:
atomic.StoreInt64(&f.currentState, stateOK)
f.process.Infof("Detected that service started and joined the cluster successfully.")
// If a degraded event was received, always change the state to degraded.
case TeleportDegradedEvent:
atomic.StoreInt64(&f.currentState, stateDegraded)
f.process.Infof("Detected Teleport is running in a degraded state.")
// If the current state is degraded, and a OK event has been
// received, change the state to recovering. If the current state is
// recovering and a OK events is received, if it's been longer
// than the recovery time (2 time the server keep alive ttl), change
// state to OK.
case TeleportOKEvent:
switch atomic.LoadInt64(&f.currentState) {
case stateDegraded:
atomic.StoreInt64(&f.currentState, stateRecovering)
f.recoveryTime = f.process.Clock.Now()
f.process.Infof("Teleport is recovering from a degraded state.")
case stateRecovering:
if f.process.Clock.Now().Sub(f.recoveryTime) > defaults.ServerKeepAliveTTL*2 {
atomic.StoreInt64(&f.currentState, stateOK)
f.process.Infof("Teleport has recovered from a degraded state.")
}
}
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L42-L48 | go | train | // Host returns host part of address without port | func (a *NetAddr) Host() string | // Host returns host part of address without port
func (a *NetAddr) Host() string | {
host, _, err := net.SplitHostPort(a.Addr)
if err != nil {
return a.Addr
}
return host
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L52-L62 | go | train | // Port returns defaultPort if no port is set or is invalid,
// the real port otherwise | func (a *NetAddr) Port(defaultPort int) int | // Port returns defaultPort if no port is set or is invalid,
// the real port otherwise
func (a *NetAddr) Port(defaultPort int) int | {
_, port, err := net.SplitHostPort(a.Addr)
if err != nil {
return defaultPort
}
porti, err := strconv.Atoi(port)
if err != nil {
return defaultPort
}
return porti
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L65-L67 | go | train | // Equals returns true if address is equal to other | func (a *NetAddr) Equals(other NetAddr) bool | // Equals returns true if address is equal to other
func (a *NetAddr) Equals(other NetAddr) bool | {
return a.Addr == other.Addr && a.AddrNetwork == other.AddrNetwork && a.Path == other.Path
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L70-L76 | go | train | // IsLocal returns true if this is a local address | func (a *NetAddr) IsLocal() bool | // IsLocal returns true if this is a local address
func (a *NetAddr) IsLocal() bool | {
host, _, err := net.SplitHostPort(a.Addr)
if err != nil {
return false
}
return IsLocalhost(host)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L84-L86 | go | train | // IsEmpty returns true if address is empty | func (a *NetAddr) IsEmpty() bool | // IsEmpty returns true if address is empty
func (a *NetAddr) IsEmpty() bool | {
return a.Addr == "" && a.AddrNetwork == "" && a.Path == ""
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L89-L91 | go | train | // FullAddress returns full address including network and address (tcp://0.0.0.0:1243) | func (a *NetAddr) FullAddress() string | // FullAddress returns full address including network and address (tcp://0.0.0.0:1243)
func (a *NetAddr) FullAddress() string | {
return fmt.Sprintf("%v://%v", a.AddrNetwork, a.Addr)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L104-L107 | go | train | // MarshalYAML defines how a network address should be marshalled to a string | func (a *NetAddr) MarshalYAML() (interface{}, error) | // MarshalYAML defines how a network address should be marshalled to a string
func (a *NetAddr) MarshalYAML() (interface{}, error) | {
url := url.URL{Scheme: a.AddrNetwork, Host: a.Addr, Path: a.Path}
return strings.TrimLeft(url.String(), "/"), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L110-L124 | go | train | // UnmarshalYAML defines how a string can be unmarshalled into a network address | func (a *NetAddr) UnmarshalYAML(unmarshal func(interface{}) error) error | // UnmarshalYAML defines how a string can be unmarshalled into a network address
func (a *NetAddr) UnmarshalYAML(unmarshal func(interface{}) error) error | {
var addr string
err := unmarshal(&addr)
if err != nil {
return err
}
parsedAddr, err := ParseAddr(addr)
if err != nil {
return err
}
*a = *parsedAddr
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L138-L159 | go | train | // ParseAddr takes strings like "tcp://host:port/path" and returns
// *NetAddr or an error | func ParseAddr(a string) (*NetAddr, error) | // ParseAddr takes strings like "tcp://host:port/path" and returns
// *NetAddr or an error
func ParseAddr(a string) (*NetAddr, error) | {
if a == "" {
return nil, trace.BadParameter("missing parameter address")
}
if !strings.Contains(a, "://") {
return &NetAddr{Addr: a, AddrNetwork: "tcp"}, nil
}
u, err := url.Parse(a)
if err != nil {
return nil, trace.BadParameter("failed to parse %q: %v", a, err)
}
switch u.Scheme {
case "tcp":
return &NetAddr{Addr: u.Host, AddrNetwork: u.Scheme, Path: u.Path}, nil
case "unix":
return &NetAddr{Addr: u.Path, AddrNetwork: u.Scheme}, nil
case "http", "https":
return &NetAddr{Addr: u.Host, AddrNetwork: u.Scheme, Path: u.Path}, nil
default:
return nil, trace.BadParameter("'%v': unsupported scheme: '%v'", a, u.Scheme)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L162-L168 | go | train | // MustParseAddr parses the provided string into NetAddr or panics on an error | func MustParseAddr(a string) *NetAddr | // MustParseAddr parses the provided string into NetAddr or panics on an error
func MustParseAddr(a string) *NetAddr | {
addr, err := ParseAddr(a)
if err != nil {
panic(fmt.Sprintf("failed to parse %v: %v", a, err))
}
return addr
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L171-L173 | go | train | // FromAddr returns NetAddr from golang standard net.Addr | func FromAddr(a net.Addr) NetAddr | // FromAddr returns NetAddr from golang standard net.Addr
func FromAddr(a net.Addr) NetAddr | {
return NetAddr{AddrNetwork: a.Network(), Addr: a.String()}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L176-L184 | go | train | // JoinAddrSlices joins two addr slices and returns a resulting slice | func JoinAddrSlices(a []NetAddr, b []NetAddr) []NetAddr | // JoinAddrSlices joins two addr slices and returns a resulting slice
func JoinAddrSlices(a []NetAddr, b []NetAddr) []NetAddr | {
if len(a)+len(b) == 0 {
return nil
}
out := make([]NetAddr, 0, len(a)+len(b))
out = append(out, a...)
out = append(out, b...)
return out
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L190-L201 | go | train | // ParseHostPortAddr takes strings like "host:port" and returns
// *NetAddr or an error
//
// If defaultPort == -1 it expects 'hostport' string to have it | func ParseHostPortAddr(hostport string, defaultPort int) (*NetAddr, error) | // ParseHostPortAddr takes strings like "host:port" and returns
// *NetAddr or an error
//
// If defaultPort == -1 it expects 'hostport' string to have it
func ParseHostPortAddr(hostport string, defaultPort int) (*NetAddr, error) | {
addr, err := ParseAddr(hostport)
if err != nil {
return nil, trace.Wrap(err)
}
// port is required but not set
if defaultPort == -1 && addr.Addr == addr.Host() {
return nil, trace.BadParameter("missing port in address %q", hostport)
}
addr.Addr = fmt.Sprintf("%v:%v", addr.Host(), addr.Port(defaultPort))
return addr, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L204-L209 | go | train | // DialAddrFromListenAddr returns dial address from listen address | func DialAddrFromListenAddr(listenAddr NetAddr) NetAddr | // DialAddrFromListenAddr returns dial address from listen address
func DialAddrFromListenAddr(listenAddr NetAddr) NetAddr | {
if listenAddr.IsEmpty() {
return listenAddr
}
return NetAddr{Addr: ReplaceLocalhost(listenAddr.Addr, "127.0.0.1")}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L242-L248 | go | train | // Addresses returns a slice of strings converted from the addresses | func (nl *NetAddrList) Addresses() []string | // Addresses returns a slice of strings converted from the addresses
func (nl *NetAddrList) Addresses() []string | {
var ns []string
for _, n := range *nl {
ns = append(ns, n.FullAddress())
}
return ns
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L251-L259 | go | train | // Set is called by CLI tools | func (nl *NetAddrList) Set(s string) error | // Set is called by CLI tools
func (nl *NetAddrList) Set(s string) error | {
v, err := ParseAddr(s)
if err != nil {
return err
}
*nl = append(*nl, *v)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L262-L268 | go | train | // String returns debug-friendly representation of the tool | func (nl *NetAddrList) String() string | // String returns debug-friendly representation of the tool
func (nl *NetAddrList) String() string | {
var ns []string
for _, n := range *nl {
ns = append(ns, n.FullAddress())
}
return strings.Join(ns, " ")
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L275-L288 | go | train | // ReplaceLocalhost checks if a given address is link-local (like 0.0.0.0 or 127.0.0.1)
// and replaces it with the IP taken from replaceWith, preserving the original port
//
// Both addresses are in "host:port" format
// The function returns the original value if it encounters any problems with parsing | func ReplaceLocalhost(addr, replaceWith string) string | // ReplaceLocalhost checks if a given address is link-local (like 0.0.0.0 or 127.0.0.1)
// and replaces it with the IP taken from replaceWith, preserving the original port
//
// Both addresses are in "host:port" format
// The function returns the original value if it encounters any problems with parsing
func ReplaceLocalhost(addr, replaceWith string) string | {
host, port, err := net.SplitHostPort(addr)
if err != nil {
return addr
}
if IsLocalhost(host) {
host, _, err = net.SplitHostPort(replaceWith)
if err != nil {
return addr
}
addr = net.JoinHostPort(host, port)
}
return addr
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L291-L297 | go | train | // IsLocalhost returns true if this is a local hostname or ip | func IsLocalhost(host string) bool | // IsLocalhost returns true if this is a local hostname or ip
func IsLocalhost(host string) bool | {
if host == "localhost" {
return true
}
ip := net.ParseIP(host)
return ip.IsLoopback() || ip.IsUnspecified()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L301-L319 | go | train | // IsLoopback returns 'true' if a given hostname resolves to local
// host's loopback interface | func IsLoopback(host string) bool | // IsLoopback returns 'true' if a given hostname resolves to local
// host's loopback interface
func IsLoopback(host string) bool | {
if strings.Contains(host, ":") {
var err error
host, _, err = net.SplitHostPort(host)
if err != nil {
return false
}
}
ips, err := net.LookupIP(host)
if err != nil {
return false
}
for _, ip := range ips {
if ip.IsLoopback() {
return true
}
}
return false
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/addr.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/addr.go#L326-L341 | go | train | // GuessIP tries to guess an IP address this machine is reachable at on the
// internal network, always picking IPv4 from the internal address space
//
// If no internal IPs are found, it returns 127.0.0.1 but it never returns
// an address from the public IP space | func GuessHostIP() (ip net.IP, err error) | // GuessIP tries to guess an IP address this machine is reachable at on the
// internal network, always picking IPv4 from the internal address space
//
// If no internal IPs are found, it returns 127.0.0.1 but it never returns
// an address from the public IP space
func GuessHostIP() (ip net.IP, err error) | {
ifaces, err := net.Interfaces()
if err != nil {
return nil, trace.Wrap(err)
}
adrs := make([]net.Addr, 0)
for _, iface := range ifaces {
ifadrs, err := iface.Addrs()
if err != nil {
log.Warn(err)
} else {
adrs = append(adrs, ifadrs...)
}
}
return guessHostIP(adrs), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/mocku2f/mocku2f.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/mocku2f/mocku2f.go#L52-L57 | go | train | // The "websafe-base64 encoding" in the U2F specifications removes the padding | func decodeBase64(s string) ([]byte, error) | // The "websafe-base64 encoding" in the U2F specifications removes the padding
func decodeBase64(s string) ([]byte, error) | {
for i := 0; i < len(s)%4; i++ {
s += "="
}
return base64.URLEncoding.DecodeString(s)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/reversetunnel/peer.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/peer.go#L127-L129 | go | train | // Dial is used to connect a requesting client (say, tsh) to an SSH server
// located in a remote connected site, the connection goes through the
// reverse proxy tunnel. | func (p *clusterPeers) Dial(params DialParams) (conn net.Conn, err error) | // Dial is used to connect a requesting client (say, tsh) to an SSH server
// located in a remote connected site, the connection goes through the
// reverse proxy tunnel.
func (p *clusterPeers) Dial(params DialParams) (conn net.Conn, err error) | {
return p.DialTCP(params.From, params.To)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/reversetunnel/peer.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/peer.go#L136-L149 | go | train | // newClusterPeer returns new cluster peer | func newClusterPeer(srv *server, connInfo services.TunnelConnection) (*clusterPeer, error) | // newClusterPeer returns new cluster peer
func newClusterPeer(srv *server, connInfo services.TunnelConnection) (*clusterPeer, error) | {
clusterPeer := &clusterPeer{
srv: srv,
connInfo: connInfo,
log: log.WithFields(log.Fields{
trace.Component: teleport.ComponentReverseTunnelServer,
trace.ComponentFields: map[string]string{
"cluster": connInfo.GetClusterName(),
},
}),
}
return clusterPeer, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/reversetunnel/peer.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/peer.go#L190-L192 | go | train | // Dial is used to connect a requesting client (say, tsh) to an SSH server
// located in a remote connected site, the connection goes through the
// reverse proxy tunnel. | func (s *clusterPeer) Dial(params DialParams) (conn net.Conn, err error) | // Dial is used to connect a requesting client (say, tsh) to an SSH server
// located in a remote connected site, the connection goes through the
// reverse proxy tunnel.
func (s *clusterPeer) Dial(params DialParams) (conn net.Conn, err error) | {
return nil, trace.ConnectionProblem(nil, "unable to dial, this proxy %v has not been discovered yet, try again later", s)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/otp.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/otp.go#L15-L33 | go | train | // GenerateQRCode takes in a OTP Key URL and returns a PNG-encoded QR code. | func GenerateQRCode(u string) ([]byte, error) | // GenerateQRCode takes in a OTP Key URL and returns a PNG-encoded QR code.
func GenerateQRCode(u string) ([]byte, error) | {
otpKey, err := otp.NewKeyFromURL(u)
if err != nil {
return nil, trace.Wrap(err)
}
otpImage, err := otpKey.Image(450, 450)
if err != nil {
return nil, trace.Wrap(err)
}
var otpQR bytes.Buffer
err = png.Encode(&otpQR, otpImage)
if err != nil {
return nil, trace.Wrap(err)
}
return otpQR.Bytes(), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/otp.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/otp.go#L38-L55 | go | train | // GenerateOTPURL returns a OTP Key URL that can be used to construct a HOTP or TOTP key. For more
// details see: https://github.com/google/google-authenticator/wiki/Key-Uri-Format
// Example: otpauth://totp/foo:bar@baz.com?secret=qux | func GenerateOTPURL(typ string, label string, parameters map[string][]byte) string | // GenerateOTPURL returns a OTP Key URL that can be used to construct a HOTP or TOTP key. For more
// details see: https://github.com/google/google-authenticator/wiki/Key-Uri-Format
// Example: otpauth://totp/foo:bar@baz.com?secret=qux
func GenerateOTPURL(typ string, label string, parameters map[string][]byte) string | {
var u url.URL
u.Scheme = "otpauth"
u.Host = typ
u.Path = label
var params url.Values = make(url.Values)
for k, v := range parameters {
if k == "secret" {
v = []byte(base32.StdEncoding.EncodeToString(v))
}
params.Add(k, string(v))
}
u.RawQuery = params.Encode()
return u.String()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/password.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/password.go#L45-L70 | go | train | // changePassword updates users password based on the old password | func (h *Handler) changePassword(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext) (interface{}, error) | // changePassword updates users password based on the old password
func (h *Handler) changePassword(w http.ResponseWriter, r *http.Request, p httprouter.Params, ctx *SessionContext) (interface{}, error) | {
var req *changePasswordReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
clt, err := ctx.GetClient()
if err != nil {
return nil, trace.Wrap(err)
}
servicedReq := services.ChangePasswordReq{
User: ctx.GetUser(),
OldPassword: req.OldPassword,
NewPassword: req.NewPassword,
SecondFactorToken: req.SecondFactorToken,
U2FSignResponse: req.U2FSignResponse,
}
err = clt.ChangePassword(servicedReq)
if err != nil {
return nil, trace.Wrap(err)
}
return ok(), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/password.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/password.go#L73-L98 | go | train | // u2fChangePasswordRequest is called to get U2F challedge for changing a user password | func (h *Handler) u2fChangePasswordRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params, ctx *SessionContext) (interface{}, error) | // u2fChangePasswordRequest is called to get U2F challedge for changing a user password
func (h *Handler) u2fChangePasswordRequest(w http.ResponseWriter, r *http.Request, _ httprouter.Params, ctx *SessionContext) (interface{}, error) | {
var req *client.U2fSignRequestReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
clt, err := ctx.GetClient()
if err != nil {
return nil, trace.Wrap(err)
}
u2fReq, err := clt.GetU2FSignRequest(ctx.GetUser(), []byte(req.Pass))
if err != nil && trace.IsAccessDenied(err) {
// logout in case of access denied
logoutErr := h.logout(w, ctx)
if logoutErr != nil {
return nil, trace.Wrap(logoutErr)
}
}
if err != nil {
return nil, trace.Wrap(err)
}
return u2fReq, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/static.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/static.go#L53-L77 | go | train | // NewStaticFileSystem returns the initialized implementation of http.FileSystem
// interface which can be used to serve Teleport Proxy Web UI
//
// If 'debugMode' is true, it will load the web assets from the same git repo
// directory where the executable is, otherwise it will load them from the embedded
// zip archive.
// | func NewStaticFileSystem(debugMode bool) (http.FileSystem, error) | // NewStaticFileSystem returns the initialized implementation of http.FileSystem
// interface which can be used to serve Teleport Proxy Web UI
//
// If 'debugMode' is true, it will load the web assets from the same git repo
// directory where the executable is, otherwise it will load them from the embedded
// zip archive.
//
func NewStaticFileSystem(debugMode bool) (http.FileSystem, error) | {
if debugMode {
assetsToCheck := []string{"index.html", "/app"}
if debugAssetsPath == "" {
exePath, err := osext.ExecutableFolder()
if err != nil {
return nil, trace.Wrap(err)
}
debugAssetsPath = path.Join(exePath, "../web/dist")
}
for _, af := range assetsToCheck {
_, err := os.Stat(filepath.Join(debugAssetsPath, af))
if err != nil {
return nil, trace.Wrap(err)
}
}
log.Infof("[Web] Using filesystem for serving web assets: %s", debugAssetsPath)
return http.Dir(debugAssetsPath), nil
}
// otherwise, lets use the zip archive attached to the executable:
return loadZippedExeAssets()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/static.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/static.go#L81-L84 | go | train | // isDebugMode determines if teleport is running in a "debug" mode.
// It looks at DEBUG environment variable | func isDebugMode() bool | // isDebugMode determines if teleport is running in a "debug" mode.
// It looks at DEBUG environment variable
func isDebugMode() bool | {
v, _ := strconv.ParseBool(os.Getenv(teleport.DebugEnvVar))
return v
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/web/static.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/web/static.go#L92-L100 | go | train | // LoadWebResources returns a filesystem implementation compatible
// with http.Serve.
//
// The "filesystem" is served from a zip file attached at the end of
// the executable
// | func loadZippedExeAssets() (ResourceMap, error) | // LoadWebResources returns a filesystem implementation compatible
// with http.Serve.
//
// The "filesystem" is served from a zip file attached at the end of
// the executable
//
func loadZippedExeAssets() (ResourceMap, error) | {
// open ourselves (teleport binary) for reading:
// NOTE: the file stays open to serve future Read() requests
myExe, err := osext.Executable()
if err != nil {
return nil, trace.Wrap(err)
}
return readZipArchive(myExe)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/broadcaster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/broadcaster.go#L39-L44 | go | train | // Close closes channel (once) to start broadcasting it's closed state | func (b *CloseBroadcaster) Close() error | // Close closes channel (once) to start broadcasting it's closed state
func (b *CloseBroadcaster) Close() error | {
b.Do(func() {
close(b.C)
})
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/register.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L37-L62 | go | train | // LocalRegister is used to generate host keys when a node or proxy is running
// within the same process as the Auth Server and as such, does not need to
// use provisioning tokens. | func LocalRegister(id IdentityID, authServer *AuthServer, additionalPrincipals, dnsNames []string, remoteAddr string) (*Identity, error) | // LocalRegister is used to generate host keys when a node or proxy is running
// within the same process as the Auth Server and as such, does not need to
// use provisioning tokens.
func LocalRegister(id IdentityID, authServer *AuthServer, additionalPrincipals, dnsNames []string, remoteAddr string) (*Identity, error) | {
// If local registration is happening and no remote address was passed in
// (which means no advertise IP was set), use localhost.
if remoteAddr == "" {
remoteAddr = defaults.Localhost
}
keys, err := authServer.GenerateServerKeys(GenerateServerKeysRequest{
HostID: id.HostUUID,
NodeName: id.NodeName,
Roles: teleport.Roles{id.Role},
AdditionalPrincipals: additionalPrincipals,
RemoteAddr: remoteAddr,
DNSNames: dnsNames,
NoCache: true,
})
if err != nil {
return nil, trace.Wrap(err)
}
identity, err := ReadIdentityFromKeyPair(keys)
if err != nil {
return nil, trace.Wrap(err)
}
return identity, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/register.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L108-L137 | go | train | // Register is used to generate host keys when a node or proxy are running on
// different hosts than the auth server. This method requires provisioning
// tokens to prove a valid auth server was used to issue the joining request
// as well as a method for the node to validate the auth server. | func Register(params RegisterParams) (*Identity, error) | // Register is used to generate host keys when a node or proxy are running on
// different hosts than the auth server. This method requires provisioning
// tokens to prove a valid auth server was used to issue the joining request
// as well as a method for the node to validate the auth server.
func Register(params RegisterParams) (*Identity, error) | {
// Read in the token. The token can either be passed in or come from a file
// on disk.
token, err := readToken(params.Token)
if err != nil {
return nil, trace.Wrap(err)
}
// Attempt to register through the auth server, if it fails, try and
// register through the proxy server.
ident, err := registerThroughAuth(token, params)
if err != nil {
// If no params client was set this is a proxy and fail right away.
if params.CredsClient == nil {
log.Debugf("Missing client, failing with error from Auth Server: %v.", err)
return nil, trace.Wrap(err)
}
ident, er := registerThroughProxy(token, params)
if er != nil {
return nil, trace.NewAggregate(err, er)
}
log.Debugf("Successfully registered through proxy server.")
return ident, nil
}
log.Debugf("Successfully registered through auth server.")
return ident, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/register.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L140-L160 | go | train | // registerThroughProxy is used to register through the proxy server. | func registerThroughProxy(token string, params RegisterParams) (*Identity, error) | // registerThroughProxy is used to register through the proxy server.
func registerThroughProxy(token string, params RegisterParams) (*Identity, error) | {
log.Debugf("Attempting to register through proxy server.")
keys, err := params.CredsClient.HostCredentials(context.Background(),
RegisterUsingTokenRequest{
Token: token,
HostID: params.ID.HostUUID,
NodeName: params.ID.NodeName,
Role: params.ID.Role,
AdditionalPrincipals: params.AdditionalPrincipals,
DNSNames: params.DNSNames,
PublicTLSKey: params.PublicTLSKey,
PublicSSHKey: params.PublicSSHKey,
})
if err != nil {
return nil, trace.Wrap(err)
}
keys.Key = params.PrivateKey
return ReadIdentityFromKeyPair(keys)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/register.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L163-L200 | go | train | // registerThroughAuth is used to register through the auth server. | func registerThroughAuth(token string, params RegisterParams) (*Identity, error) | // registerThroughAuth is used to register through the auth server.
func registerThroughAuth(token string, params RegisterParams) (*Identity, error) | {
log.Debugf("Attempting to register through auth server.")
var client *Client
var err error
// Build a client to the Auth Server. If a CA pin is specified require the
// Auth Server is validated. Otherwise attempt to use the CA file on disk
// but if it's not available connect without validating the Auth Server CA.
switch {
case params.CAPin != "":
client, err = pinRegisterClient(params)
default:
client, err = insecureRegisterClient(params)
}
if err != nil {
return nil, trace.Wrap(err)
}
defer client.Close()
// Get the SSH and X509 certificates for a node.
keys, err := client.RegisterUsingToken(RegisterUsingTokenRequest{
Token: token,
HostID: params.ID.HostUUID,
NodeName: params.ID.NodeName,
Role: params.ID.Role,
AdditionalPrincipals: params.AdditionalPrincipals,
DNSNames: params.DNSNames,
PublicTLSKey: params.PublicTLSKey,
PublicSSHKey: params.PublicSSHKey,
})
if err != nil {
return nil, trace.Wrap(err)
}
keys.Key = params.PrivateKey
return ReadIdentityFromKeyPair(keys)
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.