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/reversetunnel/agent.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L241-L248
|
go
|
train
|
// connectedToRightProxy returns true if it connected to a proxy in the
// discover list.
|
func (a *Agent) connectedToRightProxy() bool
|
// connectedToRightProxy returns true if it connected to a proxy in the
// discover list.
func (a *Agent) connectedToRightProxy() bool
|
{
for _, proxy := range a.DiscoverProxies {
if a.connectedTo(proxy) {
return true
}
}
return false
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/reversetunnel/agent.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L324-L376
|
go
|
train
|
// run is the main agent loop. It tries to establish a connection to the
// remote proxy and then process requests that come over the tunnel.
//
// Once run connects to a proxy it starts processing requests from the proxy
// via SSH channels opened by the remote Proxy.
//
// Agent sends periodic heartbeats back to the Proxy and that is how Proxy
// determines disconnects.
|
func (a *Agent) run()
|
// run is the main agent loop. It tries to establish a connection to the
// remote proxy and then process requests that come over the tunnel.
//
// Once run connects to a proxy it starts processing requests from the proxy
// via SSH channels opened by the remote Proxy.
//
// Agent sends periodic heartbeats back to the Proxy and that is how Proxy
// determines disconnects.
func (a *Agent) run()
|
{
defer a.setState(agentStateDisconnected)
if len(a.DiscoverProxies) != 0 {
a.setStateAndPrincipals(agentStateDiscovering, nil)
} else {
a.setStateAndPrincipals(agentStateConnecting, nil)
}
// Try and connect to remote cluster.
conn, err := a.connect()
if err != nil || conn == nil {
a.Warningf("Failed to create remote tunnel: %v, conn: %v.", err, conn)
return
}
// Successfully connected to remote cluster.
a.Infof("Connected to %s", conn.RemoteAddr())
if len(a.DiscoverProxies) != 0 {
// If not connected to a proxy in the discover list (which means we
// connected to a proxy we already have a connection to), try again.
if !a.connectedToRightProxy() {
a.Debugf("Missed, connected to %v instead of %v.", a.getPrincipalsList(), Proxies(a.DiscoverProxies))
conn.Close()
return
}
a.setState(agentStateDiscovered)
} else {
a.setState(agentStateConnected)
}
// Notify waiters that the agent has connected.
if a.EventsC != nil {
select {
case a.EventsC <- ConnectedEvent:
case <-a.ctx.Done():
a.Debug("Context is closing.")
return
default:
}
}
// A connection has been established start processing requests. Note that
// this function blocks while the connection is up. It will unblock when
// the connection is closed either due to intermittent connectivity issues
// or permanent loss of a proxy.
err = a.processRequests(conn)
if err != nil {
a.Warnf("Unable to continue processesing requests: %v.", err)
return
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/reversetunnel/agent.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L384-L454
|
go
|
train
|
// processRequests is a blocking function which runs in a loop sending heartbeats
// to the given SSH connection and processes inbound requests from the
// remote proxy
|
func (a *Agent) processRequests(conn *ssh.Client) error
|
// processRequests is a blocking function which runs in a loop sending heartbeats
// to the given SSH connection and processes inbound requests from the
// remote proxy
func (a *Agent) processRequests(conn *ssh.Client) error
|
{
defer conn.Close()
ticker := time.NewTicker(defaults.ReverseTunnelAgentHeartbeatPeriod)
defer ticker.Stop()
hb, reqC, err := conn.OpenChannel(chanHeartbeat, nil)
if err != nil {
return trace.Wrap(err)
}
newTransportC := conn.HandleChannelOpen(chanTransport)
newDiscoveryC := conn.HandleChannelOpen(chanDiscovery)
// send first ping right away, then start a ping timer:
hb.SendRequest("ping", false, nil)
for {
select {
// need to exit:
case <-a.ctx.Done():
return trace.ConnectionProblem(nil, "heartbeat: agent is stopped")
// time to ping:
case <-ticker.C:
bytes, _ := a.Clock.Now().UTC().MarshalText()
_, err := hb.SendRequest("ping", false, bytes)
if err != nil {
a.Error(err)
return trace.Wrap(err)
}
a.Debugf("Ping -> %v.", conn.RemoteAddr())
// ssh channel closed:
case req := <-reqC:
if req == nil {
return trace.ConnectionProblem(nil, "heartbeat: connection closed")
}
// new transport request:
case nch := <-newTransportC:
if nch == nil {
continue
}
a.Debugf("Transport request: %v.", nch.ChannelType())
ch, req, err := nch.Accept()
if err != nil {
a.Warningf("Failed to accept request: %v.", err)
continue
}
go proxyTransport(&transportParams{
log: a.Entry,
closeContext: a.ctx,
authClient: a.Client,
kubeDialAddr: a.KubeDialAddr,
channel: ch,
requestCh: req,
sconn: conn.Conn,
server: a.Server,
component: teleport.ComponentReverseTunnelAgent,
})
// new discovery request
case nch := <-newDiscoveryC:
if nch == nil {
continue
}
a.Debugf("discovery request: %v", nch.ChannelType())
ch, req, err := nch.Accept()
if err != nil {
a.Warningf("failed to accept request: %v", err)
continue
}
go a.handleDiscovery(ch, req)
}
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/reversetunnel/agent.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/reversetunnel/agent.go#L462-L492
|
go
|
train
|
// handleDisovery receives discovery requests from the reverse tunnel
// server, that informs agent about proxies registered in the remote
// cluster and the reverse tunnels already established
//
// ch : SSH channel which received "teleport-transport" out-of-band request
// reqC : request payload
|
func (a *Agent) handleDiscovery(ch ssh.Channel, reqC <-chan *ssh.Request)
|
// handleDisovery receives discovery requests from the reverse tunnel
// server, that informs agent about proxies registered in the remote
// cluster and the reverse tunnels already established
//
// ch : SSH channel which received "teleport-transport" out-of-band request
// reqC : request payload
func (a *Agent) handleDiscovery(ch ssh.Channel, reqC <-chan *ssh.Request)
|
{
a.Debugf("handleDiscovery")
defer ch.Close()
for {
var req *ssh.Request
select {
case <-a.ctx.Done():
a.Infof("is closed, returning")
return
case req = <-reqC:
if req == nil {
a.Infof("connection closed, returning")
return
}
r, err := unmarshalDiscoveryRequest(req.Payload)
if err != nil {
a.Warningf("bad payload: %v", err)
return
}
r.ClusterAddr = a.Addr
select {
case a.DiscoveryC <- r:
case <-a.ctx.Done():
a.Infof("is closed, returning")
return
default:
}
}
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/retry.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/retry.go#L55-L63
|
go
|
train
|
// CheckAndSetDefaults checks and sets defaults
|
func (c *LinearConfig) CheckAndSetDefaults() error
|
// CheckAndSetDefaults checks and sets defaults
func (c *LinearConfig) CheckAndSetDefaults() error
|
{
if c.Step == 0 {
return trace.BadParameter("missing parameter Step")
}
if c.Max == 0 {
return trace.BadParameter("missing parameter Max")
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/retry.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/retry.go#L66-L73
|
go
|
train
|
// NewLinear returns a new instance of linear retry
|
func NewLinear(cfg LinearConfig) (*Linear, error)
|
// NewLinear returns a new instance of linear retry
func NewLinear(cfg LinearConfig) (*Linear, error)
|
{
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
closedChan := make(chan time.Time)
close(closedChan)
return &Linear{LinearConfig: cfg, closedChan: closedChan}, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/retry.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/retry.go#L98-L107
|
go
|
train
|
// Duration returns retry duration based on state
|
func (r *Linear) Duration() time.Duration
|
// Duration returns retry duration based on state
func (r *Linear) Duration() time.Duration
|
{
a := r.First + time.Duration(r.attempt)*r.Step
if a < 0 {
return 0
}
if a <= r.Max {
return a
}
return r.Max
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/retry.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/retry.go#L112-L117
|
go
|
train
|
// After returns channel that fires with timeout
// defined in Duration method, as a special case
// if Duration is 0 returns a closed channel
|
func (r *Linear) After() <-chan time.Time
|
// After returns channel that fires with timeout
// defined in Duration method, as a special case
// if Duration is 0 returns a closed channel
func (r *Linear) After() <-chan time.Time
|
{
if r.Duration() == 0 {
return r.closedChan
}
return time.After(r.Duration())
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/retry.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/retry.go#L120-L122
|
go
|
train
|
// String returns user-friendly representation of the LinearPeriod
|
func (r *Linear) String() string
|
// String returns user-friendly representation of the LinearPeriod
func (r *Linear) String() string
|
{
return fmt.Sprintf("Linear(attempt=%v, duration=%v)", r.attempt, r.Duration())
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/shell/shell_unix.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/shell/shell_unix.go#L46-L88
|
go
|
train
|
// getLoginShell determines the login shell for a given username
|
func getLoginShell(username string) (string, error)
|
// getLoginShell determines the login shell for a given username
func getLoginShell(username string) (string, error)
|
{
// See if the username is valid.
_, err := user.Lookup(username)
if err != nil {
return "", trace.Wrap(err)
}
// Based on stdlib user/lookup_unix.go packages which does not return
// user shell: https://golang.org/src/os/user/lookup_unix.go
var pwd C.struct_passwd
var result *C.struct_passwd
bufSize := C.sysconf(C._SC_GETPW_R_SIZE_MAX)
if bufSize == -1 {
bufSize = 1024
}
if bufSize <= 0 || bufSize > 1<<20 {
return "", trace.BadParameter("lookupPosixShell: unreasonable _SC_GETPW_R_SIZE_MAX of %d", bufSize)
}
buf := C.malloc(C.size_t(bufSize))
defer C.free(buf)
var rv C.int
nameC := C.CString(username)
defer C.free(unsafe.Pointer(nameC))
rv = C.mygetpwnam_r(nameC,
&pwd,
(*C.char)(buf),
C.size_t(bufSize),
&result)
if rv != 0 || result == nil {
log.Errorf("lookupPosixShell: lookup username %s: %s", username, syscall.Errno(rv))
return "", trace.BadParameter("cannot determine shell for %s", username)
}
// If no shell was found, return trace.NotFound to allow the caller to set
// the default shell.
shellCmd := strings.TrimSpace(C.GoString(pwd.pw_shell))
if len(shellCmd) == 0 {
return "", trace.NotFound("no shell specified for %v", username)
}
return shellCmd, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/fingerprint.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/fingerprint.go#L15-L21
|
go
|
train
|
// AuthorizedKeyFingerprint returns fingerprint from public key
// in authorized key format
|
func AuthorizedKeyFingerprint(publicKey []byte) (string, error)
|
// AuthorizedKeyFingerprint returns fingerprint from public key
// in authorized key format
func AuthorizedKeyFingerprint(publicKey []byte) (string, error)
|
{
key, _, _, _, err := ssh.ParseAuthorizedKey(publicKey)
if err != nil {
return "", trace.Wrap(err)
}
return Fingerprint(key), nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/fingerprint.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/fingerprint.go#L25-L31
|
go
|
train
|
// PrivateKeyFingerprint returns fingerprint of the public key
// extracted from the PEM encoded private key
|
func PrivateKeyFingerprint(keyBytes []byte) (string, error)
|
// PrivateKeyFingerprint returns fingerprint of the public key
// extracted from the PEM encoded private key
func PrivateKeyFingerprint(keyBytes []byte) (string, error)
|
{
signer, err := ssh.ParsePrivateKey(keyBytes)
if err != nil {
return "", trace.Wrap(err)
}
return Fingerprint(signer.PublicKey()), nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/environment.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/environment.go#L16-L71
|
go
|
train
|
// ReadEnvironmentFile will read environment variables from a passed in location.
// Lines that start with "#" or empty lines are ignored. Assignments are in the
// form name=value and no variable expansion occurs.
|
func ReadEnvironmentFile(filename string) ([]string, error)
|
// ReadEnvironmentFile will read environment variables from a passed in location.
// Lines that start with "#" or empty lines are ignored. Assignments are in the
// form name=value and no variable expansion occurs.
func ReadEnvironmentFile(filename string) ([]string, error)
|
{
// open the users environment file. if we don't find a file, move on as
// having this file for the user is optional.
file, err := os.Open(filename)
if err != nil {
log.Warnf("Unable to open environment file %v: %v, skipping", filename, err)
return []string{}, nil
}
defer file.Close()
var lineno int
var envs []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
// follow the lead of OpenSSH and don't allow more than 1,000 environment variables
// https://github.com/openssh/openssh-portable/blob/master/session.c#L873-L874
lineno = lineno + 1
if lineno > teleport.MaxEnvironmentFileLines {
log.Warnf("Too many lines in environment file %v, returning first %v lines", filename, teleport.MaxEnvironmentFileLines)
return envs, nil
}
// empty lines or lines that start with # are ignored
if line == "" || line[0] == '#' {
continue
}
// split on first =, if not found, log it and continue
idx := strings.Index(line, "=")
if idx == -1 {
log.Debugf("Bad line %v while reading %v: no = separator found", lineno, filename)
continue
}
// split key and value and make sure that key has a name
key := line[:idx]
value := line[idx+1:]
if strings.TrimSpace(key) == "" {
log.Debugf("Bad line %v while reading %v: key without name", lineno, filename)
continue
}
envs = append(envs, key+"="+value)
}
err = scanner.Err()
if err != nil {
log.Warnf("Unable to read environment file %v: %v, skipping", filename, err)
return []string{}, nil
}
return envs, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/anonymizer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/anonymizer.go#L41-L48
|
go
|
train
|
// NewHMACAnonymizer returns a new HMAC-based anonymizer
|
func NewHMACAnonymizer(key string) (*hmacAnonymizer, error)
|
// NewHMACAnonymizer returns a new HMAC-based anonymizer
func NewHMACAnonymizer(key string) (*hmacAnonymizer, error)
|
{
if strings.TrimSpace(key) == "" {
return nil, trace.BadParameter("HMAC key must not be empty")
}
return &hmacAnonymizer{
key: key,
}, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/anonymizer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/anonymizer.go#L51-L55
|
go
|
train
|
// Anonymize anonymizes the provided data using HMAC
|
func (a *hmacAnonymizer) Anonymize(data []byte) string
|
// Anonymize anonymizes the provided data using HMAC
func (a *hmacAnonymizer) Anonymize(data []byte) string
|
{
h := hmac.New(sha256.New, []byte(a.key))
h.Write(data)
return base64.StdEncoding.EncodeToString(h.Sum(nil))
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/schema.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/schema.go#L28-L57
|
go
|
train
|
// UnmarshalWithSchema processes YAML or JSON encoded object with JSON schema, sets defaults
// and unmarshals resulting object into given struct
|
func UnmarshalWithSchema(schemaDefinition string, object interface{}, data []byte) error
|
// UnmarshalWithSchema processes YAML or JSON encoded object with JSON schema, sets defaults
// and unmarshals resulting object into given struct
func UnmarshalWithSchema(schemaDefinition string, object interface{}, data []byte) error
|
{
schema, err := jsonschema.New([]byte(schemaDefinition))
if err != nil {
return trace.Wrap(err)
}
jsonData, err := ToJSON(data)
if err != nil {
return trace.Wrap(err)
}
raw := map[string]interface{}{}
if err := json.Unmarshal(jsonData, &raw); err != nil {
return trace.Wrap(err)
}
// schema will check format and set defaults
processed, err := schema.ProcessObject(raw)
if err != nil {
return trace.Wrap(err)
}
// since ProcessObject works with unstructured data, the
// data needs to be re-interpreted in structured form
bytes, err := json.Marshal(processed)
if err != nil {
return trace.Wrap(err)
}
if err := json.Unmarshal(bytes, object); err != nil {
return trace.Wrap(err)
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/archive.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/archive.go#L30-L49
|
go
|
train
|
// NewSessionArchive returns generated tar archive with all components
|
func NewSessionArchive(dataDir, serverID, namespace string, sessionID session.ID) (io.ReadCloser, error)
|
// NewSessionArchive returns generated tar archive with all components
func NewSessionArchive(dataDir, serverID, namespace string, sessionID session.ID) (io.ReadCloser, error)
|
{
index, err := readSessionIndex(
dataDir, []string{serverID}, namespace, sessionID)
if err != nil {
return nil, trace.Wrap(err)
}
// io.Pipe allows to generate the archive part by part
// without writing to disk or generating it in memory
// at the pace which reader is ready to consume it
reader, writer := io.Pipe()
tarball := tar.NewWriter(writer)
go func() {
if err := writeSessionArchive(index, tarball, writer); err != nil {
log.Warningf("Failed to write archive: %v.", trace.DebugReport(err))
}
}()
return reader, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/certs.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L36-L54
|
go
|
train
|
// ParseSigningKeyStore parses signing key store from PEM encoded key pair
|
func ParseSigningKeyStorePEM(keyPEM, certPEM string) (*SigningKeyStore, error)
|
// ParseSigningKeyStore parses signing key store from PEM encoded key pair
func ParseSigningKeyStorePEM(keyPEM, certPEM string) (*SigningKeyStore, error)
|
{
_, err := ParseCertificatePEM([]byte(certPEM))
if err != nil {
return nil, trace.Wrap(err)
}
key, err := ParsePrivateKeyPEM([]byte(keyPEM))
if err != nil {
return nil, trace.Wrap(err)
}
rsaKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, trace.BadParameter("key of type %T is not supported, only RSA keys are supported for signatures", key)
}
certASN, _ := pem.Decode([]byte(certPEM))
if certASN == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
return &SigningKeyStore{privateKey: rsaKey, cert: certASN.Bytes}, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/certs.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L105-L115
|
go
|
train
|
// ParseCertificateRequestPEM parses PEM-encoded certificate signing request
|
func ParseCertificateRequestPEM(bytes []byte) (*x509.CertificateRequest, error)
|
// ParseCertificateRequestPEM parses PEM-encoded certificate signing request
func ParseCertificateRequestPEM(bytes []byte) (*x509.CertificateRequest, error)
|
{
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
csr, err := x509.ParseCertificateRequest(block.Bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
return csr, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/certs.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L118-L128
|
go
|
train
|
// ParseCertificatePEM parses PEM-encoded certificate
|
func ParseCertificatePEM(bytes []byte) (*x509.Certificate, error)
|
// ParseCertificatePEM parses PEM-encoded certificate
func ParseCertificatePEM(bytes []byte) (*x509.Certificate, error)
|
{
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
return cert, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/certs.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L131-L137
|
go
|
train
|
// ParsePrivateKeyPEM parses PEM-encoded private key
|
func ParsePrivateKeyPEM(bytes []byte) (crypto.Signer, error)
|
// ParsePrivateKeyPEM parses PEM-encoded private key
func ParsePrivateKeyPEM(bytes []byte) (crypto.Signer, error)
|
{
block, _ := pem.Decode(bytes)
if block == nil {
return nil, trace.BadParameter("expected PEM-encoded block")
}
return ParsePrivateKeyDER(block.Bytes)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/certs.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L140-L161
|
go
|
train
|
// ParsePrivateKeyDER parses unencrypted DER-encoded private key
|
func ParsePrivateKeyDER(der []byte) (crypto.Signer, error)
|
// ParsePrivateKeyDER parses unencrypted DER-encoded private key
func ParsePrivateKeyDER(der []byte) (crypto.Signer, error)
|
{
generalKey, err := x509.ParsePKCS8PrivateKey(der)
if err != nil {
generalKey, err = x509.ParsePKCS1PrivateKey(der)
if err != nil {
generalKey, err = x509.ParseECPrivateKey(der)
if err != nil {
logrus.Errorf("Failed to parse key: %v.", err)
return nil, trace.BadParameter("failed parsing private key")
}
}
}
switch generalKey.(type) {
case *rsa.PrivateKey:
return generalKey.(*rsa.PrivateKey), nil
case *ecdsa.PrivateKey:
return generalKey.(*ecdsa.PrivateKey), nil
}
return nil, trace.BadParameter("unsupported private key type")
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/certs.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L166-L196
|
go
|
train
|
// VerifyCertificateChain reads in chain of certificates and makes sure the
// chain from leaf to root is valid. This ensures that clients (web browsers
// and CLI) won't have problem validating the chain.
|
func VerifyCertificateChain(certificateChain []*x509.Certificate) error
|
// VerifyCertificateChain reads in chain of certificates and makes sure the
// chain from leaf to root is valid. This ensures that clients (web browsers
// and CLI) won't have problem validating the chain.
func VerifyCertificateChain(certificateChain []*x509.Certificate) error
|
{
// chain needs at least one certificate
if len(certificateChain) == 0 {
return trace.BadParameter("need at least one certificate in chain")
}
// extract leaf of certificate chain. it is safe to index into the chain here
// because readCertificateChain always returns a valid chain with at least
// one certificate.
leaf := certificateChain[0]
// extract intermediate certificate chain.
intermediates := x509.NewCertPool()
if len(certificateChain) > 1 {
for _, v := range certificateChain[1:len(certificateChain)] {
intermediates.AddCert(v)
}
}
// verify certificate chain, roots is nil which will cause us to to use the
// system roots.
opts := x509.VerifyOptions{
Intermediates: intermediates,
}
_, err := leaf.Verify(opts)
if err != nil {
return trace.Wrap(err)
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/certs.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L212-L222
|
go
|
train
|
// IsSelfSigned checks if the certificate is a self-signed certificate. To
// check if a certificate is self signed, we make sure that only one
// certificate is in the chain and that the SubjectKeyId and AuthorityKeyId
// match.
//
// From RFC5280: https://tools.ietf.org/html/rfc5280#section-4.2.1.1
//
// The signature on a self-signed certificate is generated with the private
// key associated with the certificate's subject public key. (This
// proves that the issuer possesses both the public and private keys.)
// In this case, the subject and authority key identifiers would be
// identical, but only the subject key identifier is needed for
// certification path building.
//
|
func IsSelfSigned(certificateChain []*x509.Certificate) bool
|
// IsSelfSigned checks if the certificate is a self-signed certificate. To
// check if a certificate is self signed, we make sure that only one
// certificate is in the chain and that the SubjectKeyId and AuthorityKeyId
// match.
//
// From RFC5280: https://tools.ietf.org/html/rfc5280#section-4.2.1.1
//
// The signature on a self-signed certificate is generated with the private
// key associated with the certificate's subject public key. (This
// proves that the issuer possesses both the public and private keys.)
// In this case, the subject and authority key identifiers would be
// identical, but only the subject key identifier is needed for
// certification path building.
//
func IsSelfSigned(certificateChain []*x509.Certificate) bool
|
{
if len(certificateChain) != 1 {
return false
}
if bytes.Compare(certificateChain[0].SubjectKeyId, certificateChain[0].AuthorityKeyId) != 0 {
return false
}
return true
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/certs.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/certs.go#L226-L260
|
go
|
train
|
// ReadCertificateChain parses PEM encoded bytes that can contain one or
// multiple certificates and returns a slice of x509.Certificate.
|
func ReadCertificateChain(certificateChainBytes []byte) ([]*x509.Certificate, error)
|
// ReadCertificateChain parses PEM encoded bytes that can contain one or
// multiple certificates and returns a slice of x509.Certificate.
func ReadCertificateChain(certificateChainBytes []byte) ([]*x509.Certificate, error)
|
{
// build the certificate chain next
var certificateBlock *pem.Block
var remainingBytes []byte = bytes.TrimSpace(certificateChainBytes)
var certificateChain [][]byte
for {
certificateBlock, remainingBytes = pem.Decode(remainingBytes)
if certificateBlock == nil || certificateBlock.Type != pemBlockCertificate {
return nil, trace.NotFound("no PEM data found")
}
certificateChain = append(certificateChain, certificateBlock.Bytes)
if len(remainingBytes) == 0 {
break
}
}
// build a concatenated certificate chain
var buf bytes.Buffer
for _, cc := range certificateChain {
_, err := buf.Write(cc)
if err != nil {
return nil, trace.Wrap(err)
}
}
// parse the chain and get a slice of x509.Certificates.
x509Chain, err := x509.ParseCertificates(buf.Bytes())
if err != nil {
return nil, trace.Wrap(err)
}
return x509Chain, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/timeout.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/timeout.go#L46-L52
|
go
|
train
|
// ObeyIdleTimeout wraps an existing network connection with timeout-obeying
// Write() and Read() - it will drop the connection after 'timeout' on idle
//
// Example:
// ObeyIdletimeout(conn, time.Second * 60, "api server").
|
func ObeyIdleTimeout(conn net.Conn, timeout time.Duration, ownerName string) net.Conn
|
// ObeyIdleTimeout wraps an existing network connection with timeout-obeying
// Write() and Read() - it will drop the connection after 'timeout' on idle
//
// Example:
// ObeyIdletimeout(conn, time.Second * 60, "api server").
func ObeyIdleTimeout(conn net.Conn, timeout time.Duration, ownerName string) net.Conn
|
{
return &TimeoutConn{
Conn: conn,
TimeoutDuration: timeout,
OwnerName: ownerName,
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/loadbalancer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L32-L52
|
go
|
train
|
// NewLoadBalancer returns new load balancer listening on frontend
// and redirecting requests to backends using round robin algo
|
func NewLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error)
|
// NewLoadBalancer returns new load balancer listening on frontend
// and redirecting requests to backends using round robin algo
func NewLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error)
|
{
if ctx == nil {
return nil, trace.BadParameter("missing parameter context")
}
waitCtx, waitCancel := context.WithCancel(ctx)
return &LoadBalancer{
frontend: frontend,
ctx: ctx,
backends: backends,
currentIndex: -1,
waitCtx: waitCtx,
waitCancel: waitCancel,
Entry: log.WithFields(log.Fields{
trace.Component: "loadbalancer",
trace.ComponentFields: log.Fields{
"listen": frontend.String(),
},
}),
connections: make(map[NetAddr]map[int64]net.Conn),
}, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/loadbalancer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L72-L83
|
go
|
train
|
// trackeConnection adds connection to the connection tracker
|
func (l *LoadBalancer) trackConnection(backend NetAddr, conn net.Conn) int64
|
// trackeConnection adds connection to the connection tracker
func (l *LoadBalancer) trackConnection(backend NetAddr, conn net.Conn) int64
|
{
l.Lock()
defer l.Unlock()
l.connID += 1
tracker, ok := l.connections[backend]
if !ok {
tracker = make(map[int64]net.Conn)
l.connections[backend] = tracker
}
tracker[l.connID] = conn
return l.connID
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/loadbalancer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L86-L94
|
go
|
train
|
// untrackConnection removes connection from connection tracker
|
func (l *LoadBalancer) untrackConnection(backend NetAddr, id int64)
|
// untrackConnection removes connection from connection tracker
func (l *LoadBalancer) untrackConnection(backend NetAddr, id int64)
|
{
l.Lock()
defer l.Unlock()
tracker, ok := l.connections[backend]
if !ok {
return
}
delete(tracker, id)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/loadbalancer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L97-L103
|
go
|
train
|
// dropConnections drops connections associated with backend
|
func (l *LoadBalancer) dropConnections(backend NetAddr)
|
// dropConnections drops connections associated with backend
func (l *LoadBalancer) dropConnections(backend NetAddr)
|
{
tracker := l.connections[backend]
for _, conn := range tracker {
conn.Close()
}
delete(l.connections, backend)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/loadbalancer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L106-L111
|
go
|
train
|
// AddBackend adds backend
|
func (l *LoadBalancer) AddBackend(b NetAddr)
|
// AddBackend adds backend
func (l *LoadBalancer) AddBackend(b NetAddr)
|
{
l.Lock()
defer l.Unlock()
l.backends = append(l.backends, b)
l.Debugf("backends %v", l.backends)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/loadbalancer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L114-L125
|
go
|
train
|
// RemoveBackend removes backend
|
func (l *LoadBalancer) RemoveBackend(b NetAddr)
|
// RemoveBackend removes backend
func (l *LoadBalancer) RemoveBackend(b NetAddr)
|
{
l.Lock()
defer l.Unlock()
l.currentIndex = -1
for i := range l.backends {
if l.backends[i].Equals(b) {
l.backends = append(l.backends[:i], l.backends[i+1:]...)
l.dropConnections(b)
return
}
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/loadbalancer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L162-L167
|
go
|
train
|
// ListenAndServe starts listening socket and serves connections on it
|
func (l *LoadBalancer) ListenAndServe() error
|
// ListenAndServe starts listening socket and serves connections on it
func (l *LoadBalancer) ListenAndServe() error
|
{
if err := l.Listen(); err != nil {
return trace.Wrap(err)
}
return l.Serve()
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/loadbalancer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L170-L178
|
go
|
train
|
// Listen creates a listener on the frontend addr
|
func (l *LoadBalancer) Listen() error
|
// Listen creates a listener on the frontend addr
func (l *LoadBalancer) Listen() error
|
{
var err error
l.listener, err = net.Listen(l.frontend.AddrNetwork, l.frontend.Addr)
if err != nil {
return trace.ConvertSystemError(err)
}
l.Debugf("created listening socket")
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/loadbalancer.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/loadbalancer.go#L181-L200
|
go
|
train
|
// Serve starts accepting connections
|
func (l *LoadBalancer) Serve() error
|
// Serve starts accepting connections
func (l *LoadBalancer) Serve() error
|
{
defer l.waitCancel()
backoffTimer := time.NewTicker(5 * time.Second)
defer backoffTimer.Stop()
for {
conn, err := l.listener.Accept()
if err != nil {
if l.isClosed() {
return trace.ConnectionProblem(nil, "listener is closed")
}
select {
case <-backoffTimer.C:
l.Debugf("backoff on network error")
case <-l.ctx.Done():
return trace.ConnectionProblem(nil, "context is closing")
}
}
go l.forwardConnection(conn)
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/sessionlog.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L80-L107
|
go
|
train
|
// NewDiskSessionLogger creates new disk based session logger
|
func NewDiskSessionLogger(cfg DiskSessionLoggerConfig) (*DiskSessionLogger, error)
|
// NewDiskSessionLogger creates new disk based session logger
func NewDiskSessionLogger(cfg DiskSessionLoggerConfig) (*DiskSessionLogger, error)
|
{
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
var err error
sessionDir := filepath.Join(cfg.DataDir, cfg.ServerID, SessionLogsDir, cfg.Namespace)
indexFile, err := os.OpenFile(
filepath.Join(sessionDir, fmt.Sprintf("%v.index", cfg.SessionID.String())), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
return nil, trace.Wrap(err)
}
sessionLogger := &DiskSessionLogger{
DiskSessionLoggerConfig: cfg,
Entry: log.WithFields(log.Fields{
trace.Component: teleport.ComponentAuditLog,
trace.ComponentFields: log.Fields{
"sid": cfg.SessionID,
},
}),
sessionDir: sessionDir,
indexFile: indexFile,
lastEventIndex: -1,
lastChunkIndex: -1,
}
return sessionLogger, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/sessionlog.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L163-L168
|
go
|
train
|
// Finalize is called by the session when it's closing. This is where we're
// releasing audit resources associated with the session
|
func (sl *DiskSessionLogger) Finalize() error
|
// Finalize is called by the session when it's closing. This is where we're
// releasing audit resources associated with the session
func (sl *DiskSessionLogger) Finalize() error
|
{
sl.Lock()
defer sl.Unlock()
return sl.finalize()
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/sessionlog.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L172-L182
|
go
|
train
|
// flush is used to flush gzip frames to file, otherwise
// some attempts to read the file could fail
|
func (sl *DiskSessionLogger) flush() error
|
// flush is used to flush gzip frames to file, otherwise
// some attempts to read the file could fail
func (sl *DiskSessionLogger) flush() error
|
{
var err, err2 error
if sl.RecordSessions && sl.chunksFile != nil {
err = sl.chunksFile.Flush()
}
if sl.eventsFile != nil {
err2 = sl.eventsFile.Flush()
}
return trace.NewAggregate(err, err2)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/sessionlog.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L215-L217
|
go
|
train
|
// eventsFileName consists of session id and the first global event index recorded there
|
func eventsFileName(dataDir string, sessionID session.ID, eventIndex int64) string
|
// eventsFileName consists of session id and the first global event index recorded there
func eventsFileName(dataDir string, sessionID session.ID, eventIndex int64) string
|
{
return filepath.Join(dataDir, fmt.Sprintf("%v-%v.events.gz", sessionID.String(), eventIndex))
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/sessionlog.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L220-L222
|
go
|
train
|
// chunksFileName consists of session id and the first global offset recorded
|
func chunksFileName(dataDir string, sessionID session.ID, offset int64) string
|
// chunksFileName consists of session id and the first global offset recorded
func chunksFileName(dataDir string, sessionID session.ID, offset int64) string
|
{
return filepath.Join(dataDir, fmt.Sprintf("%v-%v.chunks.gz", sessionID.String(), offset))
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/sessionlog.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L292-L303
|
go
|
train
|
// PostSessionSlice takes series of events associated with the session
// and writes them to events files and data file for future replays
|
func (sl *DiskSessionLogger) PostSessionSlice(slice SessionSlice) error
|
// PostSessionSlice takes series of events associated with the session
// and writes them to events files and data file for future replays
func (sl *DiskSessionLogger) PostSessionSlice(slice SessionSlice) error
|
{
sl.Lock()
defer sl.Unlock()
for i := range slice.Chunks {
_, err := sl.writeChunk(slice.SessionID, slice.Chunks[i])
if err != nil {
return trace.Wrap(err)
}
}
return sl.flush()
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/sessionlog.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L306-L321
|
go
|
train
|
// EventFromChunk returns event converted from session chunk
|
func EventFromChunk(sessionID string, chunk *SessionChunk) (EventFields, error)
|
// EventFromChunk returns event converted from session chunk
func EventFromChunk(sessionID string, chunk *SessionChunk) (EventFields, error)
|
{
var fields EventFields
eventStart := time.Unix(0, chunk.Time).In(time.UTC).Round(time.Millisecond)
err := json.Unmarshal(chunk.Data, &fields)
if err != nil {
return nil, trace.Wrap(err)
}
fields[SessionEventID] = sessionID
fields[EventIndex] = chunk.EventIndex
fields[EventTime] = eventStart
fields[EventType] = chunk.EventType
if fields[EventID] == "" {
fields[EventID] = uuid.New()
}
return fields, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/sessionlog.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L421-L434
|
go
|
train
|
// Close closes gzip writer and file
|
func (f *gzipWriter) Close() error
|
// Close closes gzip writer and file
func (f *gzipWriter) Close() error
|
{
var errors []error
if f.Writer != nil {
errors = append(errors, f.Writer.Close())
f.Writer.Reset(ioutil.Discard)
writerPool.Put(f.Writer)
f.Writer = nil
}
if f.file != nil {
errors = append(errors, f.file.Close())
f.file = nil
}
return trace.NewAggregate(errors...)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/sessionlog.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/sessionlog.go#L463-L474
|
go
|
train
|
// Close closes file and gzip writer
|
func (f *gzipReader) Close() error
|
// Close closes file and gzip writer
func (f *gzipReader) Close() error
|
{
var errors []error
if f.ReadCloser != nil {
errors = append(errors, f.ReadCloser.Close())
f.ReadCloser = nil
}
if f.file != nil {
errors = append(errors, f.file.Close())
f.file = nil
}
return trace.NewAggregate(errors...)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/srv/heartbeat.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L78-L85
|
go
|
train
|
// CheckAndSetDefaults checks values and sets defaults
|
func (h HeartbeatMode) CheckAndSetDefaults() error
|
// CheckAndSetDefaults checks values and sets defaults
func (h HeartbeatMode) CheckAndSetDefaults() error
|
{
switch h {
case HeartbeatModeNode, HeartbeatModeProxy, HeartbeatModeAuth:
return nil
default:
return trace.BadParameter("unrecognized mode")
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/srv/heartbeat.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L88-L99
|
go
|
train
|
// String returns user-friendly representation of the mode
|
func (h HeartbeatMode) String() string
|
// String returns user-friendly representation of the mode
func (h HeartbeatMode) String() string
|
{
switch h {
case HeartbeatModeNode:
return "Node"
case HeartbeatModeProxy:
return "Proxy"
case HeartbeatModeAuth:
return "Auth"
default:
return fmt.Sprintf("<unknown: %v>", int(h))
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/srv/heartbeat.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L114-L132
|
go
|
train
|
// NewHeartbeat returns a new instance of heartbeat
|
func NewHeartbeat(cfg HeartbeatConfig) (*Heartbeat, error)
|
// NewHeartbeat returns a new instance of heartbeat
func NewHeartbeat(cfg HeartbeatConfig) (*Heartbeat, error)
|
{
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
ctx, cancel := context.WithCancel(cfg.Context)
h := &Heartbeat{
cancelCtx: ctx,
cancel: cancel,
HeartbeatConfig: cfg,
Entry: log.WithFields(log.Fields{
trace.Component: teleport.Component(cfg.Component, "beat"),
}),
checkTicker: time.NewTicker(cfg.CheckPeriod),
announceC: make(chan struct{}, 1),
sendC: make(chan struct{}, 1),
}
h.Debugf("Starting %v heartbeat with announce period: %v, keep-alive period %v, poll period: %v", cfg.Mode, cfg.KeepAlivePeriod, cfg.AnnouncePeriod, cfg.CheckPeriod)
return h, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/srv/heartbeat.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L168-L201
|
go
|
train
|
// CheckAndSetDefaults checks and sets default values
|
func (cfg *HeartbeatConfig) CheckAndSetDefaults() error
|
// CheckAndSetDefaults checks and sets default values
func (cfg *HeartbeatConfig) CheckAndSetDefaults() error
|
{
if err := cfg.Mode.CheckAndSetDefaults(); err != nil {
return trace.Wrap(err)
}
if cfg.Context == nil {
return trace.BadParameter("missing parameter Context")
}
if cfg.Announcer == nil {
return trace.BadParameter("missing parameter Announcer")
}
if cfg.Component == "" {
return trace.BadParameter("missing parameter Component")
}
if cfg.CheckPeriod == 0 {
return trace.BadParameter("missing parameter CheckPeriod")
}
if cfg.KeepAlivePeriod == 0 {
return trace.BadParameter("missing parameter KeepAlivePeriod")
}
if cfg.AnnouncePeriod == 0 {
return trace.BadParameter("missing parameter AnnouncePeriod")
}
if cfg.ServerTTL == 0 {
return trace.BadParameter("missing parmeter ServerTTL")
}
if cfg.GetServerInfo == nil {
return trace.BadParameter("missing parameter GetServerInfo")
}
if cfg.Clock == nil {
cfg.Clock = clockwork.NewRealClock()
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/srv/heartbeat.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L233-L251
|
go
|
train
|
// Run periodically calls to announce presence,
// should be called explicitly in a separate goroutine
|
func (h *Heartbeat) Run() error
|
// Run periodically calls to announce presence,
// should be called explicitly in a separate goroutine
func (h *Heartbeat) Run() error
|
{
defer func() {
h.reset(HeartbeatStateInit)
h.checkTicker.Stop()
}()
for {
if err := h.fetchAndAnnounce(); err != nil {
h.Warningf("Heartbeat failed %v.", err)
}
select {
case <-h.checkTicker.C:
case <-h.sendC:
h.Debugf("Asked check out of cycle")
case <-h.cancelCtx.Done():
h.Debugf("Heartbeat exited.")
return nil
}
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/srv/heartbeat.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L276-L287
|
go
|
train
|
// reset resets keep alive state
// and sends the state back to the initial state
// of sending full update
|
func (h *Heartbeat) reset(state KeepAliveState)
|
// reset resets keep alive state
// and sends the state back to the initial state
// of sending full update
func (h *Heartbeat) reset(state KeepAliveState)
|
{
h.setState(state)
h.nextAnnounce = time.Time{}
h.nextKeepAlive = time.Time{}
h.keepAlive = nil
if h.keepAliver != nil {
if err := h.keepAliver.Close(); err != nil {
h.Warningf("Failed to close keep aliver: %v", err)
}
h.keepAliver = nil
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/srv/heartbeat.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L291-L343
|
go
|
train
|
// fetch, if succeeded updates or sets current server
// to the last received server
|
func (h *Heartbeat) fetch() error
|
// fetch, if succeeded updates or sets current server
// to the last received server
func (h *Heartbeat) fetch() error
|
{
// failed to fetch server info?
// reset to init state regardless of the current state
server, err := h.GetServerInfo()
if err != nil {
h.reset(HeartbeatStateInit)
return trace.Wrap(err)
}
switch h.state {
// in case of successfull state fetch, move to announce from init
case HeartbeatStateInit:
h.current = server
h.reset(HeartbeatStateAnnounce)
return nil
// nothing to do in announce state
case HeartbeatStateAnnounce:
return nil
case HeartbeatStateAnnounceWait:
// time to announce
if h.Clock.Now().UTC().After(h.nextAnnounce) {
h.current = server
h.reset(HeartbeatStateAnnounce)
return nil
}
result := services.CompareServers(h.current, server)
// server update happened, time to announce
if result == services.Different {
h.current = server
h.reset(HeartbeatStateAnnounce)
}
return nil
// nothing to do in keep alive state
case HeartbeatStateKeepAlive:
return nil
// Stay in keep alive state in case
// if there are no changes
case HeartbeatStateKeepAliveWait:
// time to send a new keep alive
if h.Clock.Now().UTC().After(h.nextKeepAlive) {
h.setState(HeartbeatStateKeepAlive)
return nil
}
result := services.CompareServers(h.current, server)
// server update happened, move to announce
if result == services.Different {
h.current = server
h.reset(HeartbeatStateAnnounce)
}
return nil
default:
return trace.BadParameter("unsupported state: %v", h.state)
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/srv/heartbeat.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L433-L441
|
go
|
train
|
// fetchAndAnnounce fetches data about server
// and announces it to the server
|
func (h *Heartbeat) fetchAndAnnounce() error
|
// fetchAndAnnounce fetches data about server
// and announces it to the server
func (h *Heartbeat) fetchAndAnnounce() error
|
{
if err := h.fetch(); err != nil {
return trace.Wrap(err)
}
if err := h.announce(); err != nil {
return trace.Wrap(err)
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/srv/heartbeat.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/heartbeat.go#L445-L458
|
go
|
train
|
// ForceSend forces send cycle, used in tests, returns
// nil in case of success, error otherwise
|
func (h *Heartbeat) ForceSend(timeout time.Duration) error
|
// ForceSend forces send cycle, used in tests, returns
// nil in case of success, error otherwise
func (h *Heartbeat) ForceSend(timeout time.Duration) error
|
{
timeoutC := time.After(timeout)
select {
case h.sendC <- struct{}{}:
case <-timeoutC:
return trace.ConnectionProblem(nil, "timeout waiting for send")
}
select {
case <-h.announceC:
return nil
case <-timeoutC:
return trace.ConnectionProblem(nil, "timeout waiting for announce to be sent")
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L65-L86
|
go
|
train
|
// CheckAndSetDefaults is a helper returns an error if the supplied configuration
// is not enough to connect to DynamoDB
|
func (cfg *Config) CheckAndSetDefaults() error
|
// CheckAndSetDefaults is a helper returns an error if the supplied configuration
// is not enough to connect to DynamoDB
func (cfg *Config) CheckAndSetDefaults() error
|
{
// table is not configured?
if cfg.Tablename == "" {
return trace.BadParameter("DynamoDB: table_name is not specified")
}
if cfg.ReadCapacityUnits == 0 {
cfg.ReadCapacityUnits = DefaultReadCapacityUnits
}
if cfg.WriteCapacityUnits == 0 {
cfg.WriteCapacityUnits = DefaultWriteCapacityUnits
}
if cfg.RetentionPeriod == 0 {
cfg.RetentionPeriod = DefaultRetentionPeriod
}
if cfg.Clock == nil {
cfg.Clock = clockwork.NewRealClock()
}
if cfg.UIDGenerator == nil {
cfg.UIDGenerator = utils.NewRealUID()
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L148-L199
|
go
|
train
|
// New returns new instance of DynamoDB backend.
// It's an implementation of backend API's NewFunc
|
func New(cfg Config) (*Log, error)
|
// New returns new instance of DynamoDB backend.
// It's an implementation of backend API's NewFunc
func New(cfg Config) (*Log, error)
|
{
l := log.WithFields(log.Fields{
trace.Component: teleport.Component(teleport.ComponentDynamoDB),
})
l.Info("Initializing event backend.")
if err := cfg.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
b := &Log{
Entry: l,
Config: cfg,
}
// create an AWS session using default SDK behavior, i.e. it will interpret
// the environment and ~/.aws directory just like an AWS CLI tool would:
sess, err := awssession.NewSessionWithOptions(awssession.Options{
SharedConfigState: awssession.SharedConfigEnable,
})
if err != nil {
return nil, trace.Wrap(err)
}
// override the default environment (region + credentials) with the values
// from the YAML file:
if cfg.Region != "" {
sess.Config.Region = aws.String(cfg.Region)
}
// create DynamoDB service:
b.svc = dynamodb.New(sess)
// check if the table exists?
ts, err := b.getTableStatus(b.Tablename)
if err != nil {
return nil, trace.Wrap(err)
}
switch ts {
case tableStatusOK:
break
case tableStatusMissing:
err = b.createTable(b.Tablename)
case tableStatusNeedsMigration:
return nil, trace.BadParameter("unsupported schema")
}
if err != nil {
return nil, trace.Wrap(err)
}
err = b.turnOnTimeToLive()
if err != nil {
return nil, trace.Wrap(err)
}
return b, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L211-L254
|
go
|
train
|
// EmitAuditEvent emits audit event
|
func (l *Log) EmitAuditEvent(ev events.Event, fields events.EventFields) error
|
// EmitAuditEvent emits audit event
func (l *Log) EmitAuditEvent(ev events.Event, fields events.EventFields) error
|
{
sessionID := fields.GetString(events.SessionEventID)
eventIndex := fields.GetInt(events.EventIndex)
// no session id - global event gets a random uuid to get a good partition
// key distribution
if sessionID == "" {
sessionID = uuid.New()
}
err := events.UpdateEventFields(ev, fields, l.Clock, l.UIDGenerator)
if err != nil {
log.Error(trace.DebugReport(err))
}
created := fields.GetTime(events.EventTime)
if created.IsZero() {
created = l.Clock.Now().UTC()
}
data, err := json.Marshal(fields)
if err != nil {
return trace.Wrap(err)
}
e := event{
SessionID: sessionID,
EventIndex: int64(eventIndex),
EventType: fields.GetString(events.EventType),
EventNamespace: defaults.Namespace,
CreatedAt: created.Unix(),
Fields: string(data),
}
l.setExpiry(&e)
av, err := dynamodbattribute.MarshalMap(e)
if err != nil {
return trace.Wrap(err)
}
input := dynamodb.PutItemInput{
Item: av,
TableName: aws.String(l.Tablename),
}
_, err = l.svc.PutItem(&input)
err = convertError(err)
if err != nil {
return trace.Wrap(err)
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L264-L314
|
go
|
train
|
// PostSessionSlice sends chunks of recorded session to the event log
|
func (l *Log) PostSessionSlice(slice events.SessionSlice) error
|
// PostSessionSlice sends chunks of recorded session to the event log
func (l *Log) PostSessionSlice(slice events.SessionSlice) error
|
{
var requests []*dynamodb.WriteRequest
for _, chunk := range slice.Chunks {
// if legacy event with no type or print event, skip it
if chunk.EventType == events.SessionPrintEvent || chunk.EventType == "" {
continue
}
fields, err := events.EventFromChunk(slice.SessionID, chunk)
if err != nil {
return trace.Wrap(err)
}
data, err := json.Marshal(fields)
if err != nil {
return trace.Wrap(err)
}
event := event{
SessionID: slice.SessionID,
EventNamespace: defaults.Namespace,
EventType: chunk.EventType,
EventIndex: chunk.EventIndex,
CreatedAt: time.Unix(0, chunk.Time).In(time.UTC).Unix(),
Fields: string(data),
}
l.setExpiry(&event)
item, err := dynamodbattribute.MarshalMap(event)
if err != nil {
return trace.Wrap(err)
}
requests = append(requests, &dynamodb.WriteRequest{
PutRequest: &dynamodb.PutRequest{
Item: item,
},
})
}
// no chunks to post (all chunks are print events)
if len(requests) == 0 {
return nil
}
input := dynamodb.BatchWriteItemInput{
RequestItems: map[string][]*dynamodb.WriteRequest{
l.Tablename: requests,
},
}
req, _ := l.svc.BatchWriteItemRequest(&input)
err := req.Send()
err = convertError(err)
if err != nil {
return trace.Wrap(err)
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L325-L327
|
go
|
train
|
// GetSessionChunk returns a reader which can be used to read a byte stream
// of a recorded session starting from 'offsetBytes' (pass 0 to start from the
// beginning) up to maxBytes bytes.
//
// If maxBytes > MaxChunkBytes, it gets rounded down to MaxChunkBytes
|
func (l *Log) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error)
|
// GetSessionChunk returns a reader which can be used to read a byte stream
// of a recorded session starting from 'offsetBytes' (pass 0 to start from the
// beginning) up to maxBytes bytes.
//
// If maxBytes > MaxChunkBytes, it gets rounded down to MaxChunkBytes
func (l *Log) GetSessionChunk(namespace string, sid session.ID, offsetBytes, maxBytes int) ([]byte, error)
|
{
return nil, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L336-L367
|
go
|
train
|
// Returns all events that happen during a session sorted by time
// (oldest first).
//
// after tells to use only return events after a specified cursor Id
//
// This function is usually used in conjunction with GetSessionReader to
// replay recorded session streams.
|
func (l *Log) GetSessionEvents(namespace string, sid session.ID, after int, inlcudePrintEvents bool) ([]events.EventFields, error)
|
// Returns all events that happen during a session sorted by time
// (oldest first).
//
// after tells to use only return events after a specified cursor Id
//
// This function is usually used in conjunction with GetSessionReader to
// replay recorded session streams.
func (l *Log) GetSessionEvents(namespace string, sid session.ID, after int, inlcudePrintEvents bool) ([]events.EventFields, error)
|
{
var values []events.EventFields
query := "SessionID = :sessionID AND EventIndex >= :eventIndex"
attributes := map[string]interface{}{
":sessionID": string(sid),
":eventIndex": after,
}
attributeValues, err := dynamodbattribute.MarshalMap(attributes)
input := dynamodb.QueryInput{
KeyConditionExpression: aws.String(query),
TableName: aws.String(l.Tablename),
ExpressionAttributeValues: attributeValues,
}
out, err := l.svc.Query(&input)
if err != nil {
return nil, trace.Wrap(err)
}
for _, item := range out.Items {
var e event
if err := dynamodbattribute.UnmarshalMap(item, &e); err != nil {
return nil, trace.BadParameter("failed to unmarshal event for session %q: %v", string(sid), err)
}
var fields events.EventFields
data := []byte(e.Fields)
if err := json.Unmarshal(data, &fields); err != nil {
return nil, trace.BadParameter("failed to unmarshal event for session %q: %v", string(sid), err)
}
values = append(values, fields)
}
sort.Sort(events.ByTimeAndIndex(values))
return values, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L377-L437
|
go
|
train
|
// SearchEvents is a flexible way to find The format of a query string
// depends on the implementing backend. A recommended format is urlencoded
// (good enough for Lucene/Solr)
//
// Pagination is also defined via backend-specific query format.
//
// The only mandatory requirement is a date range (UTC). Results must always
// show up sorted by date (newest first)
|
func (l *Log) SearchEvents(fromUTC, toUTC time.Time, filter string, limit int) ([]events.EventFields, error)
|
// SearchEvents is a flexible way to find The format of a query string
// depends on the implementing backend. A recommended format is urlencoded
// (good enough for Lucene/Solr)
//
// Pagination is also defined via backend-specific query format.
//
// The only mandatory requirement is a date range (UTC). Results must always
// show up sorted by date (newest first)
func (l *Log) SearchEvents(fromUTC, toUTC time.Time, filter string, limit int) ([]events.EventFields, error)
|
{
g := l.WithFields(log.Fields{"From": fromUTC, "To": toUTC, "Filter": filter, "Limit": limit})
filterVals, err := url.ParseQuery(filter)
if err != nil {
return nil, trace.BadParameter("missing parameter query")
}
eventFilter, ok := filterVals[events.EventType]
if !ok && len(filterVals) > 0 {
return nil, nil
}
doFilter := len(eventFilter) > 0
var values []events.EventFields
query := "EventNamespace = :eventNamespace AND CreatedAt BETWEEN :start and :end"
attributes := map[string]interface{}{
":eventNamespace": defaults.Namespace,
":start": fromUTC.Unix(),
":end": toUTC.Unix(),
}
attributeValues, err := dynamodbattribute.MarshalMap(attributes)
input := dynamodb.QueryInput{
KeyConditionExpression: aws.String(query),
TableName: aws.String(l.Tablename),
ExpressionAttributeValues: attributeValues,
IndexName: aws.String(indexTimeSearch),
}
start := time.Now()
out, err := l.svc.Query(&input)
if err != nil {
return nil, trace.Wrap(err)
}
g.WithFields(log.Fields{"duration": time.Now().Sub(start), "items": len(out.Items)}).Debugf("Query completed.")
var total int
for _, item := range out.Items {
var e event
if err := dynamodbattribute.UnmarshalMap(item, &e); err != nil {
return nil, trace.BadParameter("failed to unmarshal event for %v", err)
}
var fields events.EventFields
data := []byte(e.Fields)
if err := json.Unmarshal(data, &fields); err != nil {
return nil, trace.BadParameter("failed to unmarshal event %v", err)
}
var accepted bool
for i := range eventFilter {
if fields.GetString(events.EventType) == eventFilter[i] {
accepted = true
break
}
}
if accepted || !doFilter {
values = append(values, fields)
total += 1
if limit > 0 && total >= limit {
break
}
}
}
sort.Sort(events.ByTimeAndIndex(values))
return values, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L441-L449
|
go
|
train
|
// SearchSessionEvents returns session related events only. This is used to
// find completed session.
|
func (l *Log) SearchSessionEvents(fromUTC time.Time, toUTC time.Time, limit int) ([]events.EventFields, error)
|
// SearchSessionEvents returns session related events only. This is used to
// find completed session.
func (l *Log) SearchSessionEvents(fromUTC time.Time, toUTC time.Time, limit int) ([]events.EventFields, error)
|
{
// only search for specific event types
query := url.Values{}
query[events.EventType] = []string{
events.SessionStartEvent,
events.SessionEndEvent,
}
return l.SearchEvents(fromUTC, toUTC, query.Encode(), limit)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L479-L491
|
go
|
train
|
// getTableStatus checks if a given table exists
|
func (b *Log) getTableStatus(tableName string) (tableStatus, error)
|
// getTableStatus checks if a given table exists
func (b *Log) getTableStatus(tableName string) (tableStatus, error)
|
{
_, err := b.svc.DescribeTable(&dynamodb.DescribeTableInput{
TableName: aws.String(tableName),
})
err = convertError(err)
if err != nil {
if trace.IsNotFound(err) {
return tableStatusMissing, nil
}
return tableStatusError, trace.Wrap(err)
}
return tableStatusOK, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L499-L569
|
go
|
train
|
// createTable creates a DynamoDB table with a requested name and applies
// the back-end schema to it. The table must not exist.
//
// rangeKey is the name of the 'range key' the schema requires.
// currently is always set to "FullPath" (used to be something else, that's
// why it's a parameter for migration purposes)
|
func (b *Log) createTable(tableName string) error
|
// createTable creates a DynamoDB table with a requested name and applies
// the back-end schema to it. The table must not exist.
//
// rangeKey is the name of the 'range key' the schema requires.
// currently is always set to "FullPath" (used to be something else, that's
// why it's a parameter for migration purposes)
func (b *Log) createTable(tableName string) error
|
{
provisionedThroughput := dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(b.ReadCapacityUnits),
WriteCapacityUnits: aws.Int64(b.WriteCapacityUnits),
}
def := []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String(keySessionID),
AttributeType: aws.String("S"),
},
{
AttributeName: aws.String(keyEventIndex),
AttributeType: aws.String("N"),
},
{
AttributeName: aws.String(keyEventNamespace),
AttributeType: aws.String("S"),
},
{
AttributeName: aws.String(keyCreatedAt),
AttributeType: aws.String("N"),
},
}
elems := []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String(keySessionID),
KeyType: aws.String("HASH"),
},
{
AttributeName: aws.String(keyEventIndex),
KeyType: aws.String("RANGE"),
},
}
c := dynamodb.CreateTableInput{
TableName: aws.String(tableName),
AttributeDefinitions: def,
KeySchema: elems,
ProvisionedThroughput: &provisionedThroughput,
GlobalSecondaryIndexes: []*dynamodb.GlobalSecondaryIndex{
&dynamodb.GlobalSecondaryIndex{
IndexName: aws.String(indexTimeSearch),
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String(keyEventNamespace),
KeyType: aws.String("HASH"),
},
{
AttributeName: aws.String(keyCreatedAt),
KeyType: aws.String("RANGE"),
},
},
Projection: &dynamodb.Projection{
ProjectionType: aws.String("ALL"),
},
ProvisionedThroughput: &provisionedThroughput,
},
},
}
_, err := b.svc.CreateTable(&c)
if err != nil {
return trace.Wrap(err)
}
log.Infof("Waiting until table %q is created", tableName)
err = b.svc.WaitUntilTableExists(&dynamodb.DescribeTableInput{
TableName: aws.String(tableName),
})
if err == nil {
log.Infof("Table %q has been created", tableName)
}
return trace.Wrap(err)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L572-L602
|
go
|
train
|
// deleteAllItems deletes all items from the database, used in tests
|
func (b *Log) deleteAllItems() error
|
// deleteAllItems deletes all items from the database, used in tests
func (b *Log) deleteAllItems() error
|
{
out, err := b.svc.Scan(&dynamodb.ScanInput{TableName: aws.String(b.Tablename)})
if err != nil {
return trace.Wrap(err)
}
var requests []*dynamodb.WriteRequest
for _, item := range out.Items {
requests = append(requests, &dynamodb.WriteRequest{
DeleteRequest: &dynamodb.DeleteRequest{
Key: map[string]*dynamodb.AttributeValue{
keySessionID: item[keySessionID],
keyEventIndex: item[keyEventIndex],
},
},
})
}
if len(requests) == 0 {
return nil
}
req, _ := b.svc.BatchWriteItemRequest(&dynamodb.BatchWriteItemInput{
RequestItems: map[string][]*dynamodb.WriteRequest{
b.Tablename: requests,
},
})
err = req.Send()
err = convertError(err)
if err != nil {
return trace.Wrap(err)
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L655-L657
|
go
|
train
|
// Swap is part of sort.Interface.
|
func (e eventlist) Swap(i, j int)
|
// Swap is part of sort.Interface.
func (e eventlist) Swap(i, j int)
|
{
e[i], e[j] = e[j], e[i]
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/events/dynamoevents/dynamoevents.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/dynamoevents/dynamoevents.go#L660-L662
|
go
|
train
|
// Less is part of sort.Interface.
|
func (e eventlist) Less(i, j int) bool
|
// Less is part of sort.Interface.
func (e eventlist) Less(i, j int) bool
|
{
return e[i].EventIndex < e[j].EventIndex
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/services/local/events.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/events.go#L39-L44
|
go
|
train
|
// NewEventsService returns new events service instance
|
func NewEventsService(b backend.Backend) *EventsService
|
// NewEventsService returns new events service instance
func NewEventsService(b backend.Backend) *EventsService
|
{
return &EventsService{
Entry: logrus.WithFields(logrus.Fields{trace.Component: "Events"}),
backend: b,
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/services/local/events.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/events.go#L47-L103
|
go
|
train
|
// NewWatcher returns a new event watcher
|
func (e *EventsService) NewWatcher(ctx context.Context, watch services.Watch) (services.Watcher, error)
|
// NewWatcher returns a new event watcher
func (e *EventsService) NewWatcher(ctx context.Context, watch services.Watch) (services.Watcher, error)
|
{
if len(watch.Kinds) == 0 {
return nil, trace.BadParameter("global watches are not supported yet")
}
var parsers []resourceParser
var prefixes [][]byte
for _, kind := range watch.Kinds {
if kind.Name != "" && kind.Kind != services.KindNamespace {
return nil, trace.BadParameter("watch with Name is only supported for Namespace resource")
}
var parser resourceParser
switch kind.Kind {
case services.KindCertAuthority:
parser = newCertAuthorityParser(kind.LoadSecrets)
case services.KindToken:
parser = newProvisionTokenParser()
case services.KindStaticTokens:
parser = newStaticTokensParser()
case services.KindClusterConfig:
parser = newClusterConfigParser()
case services.KindClusterName:
parser = newClusterNameParser()
case services.KindNamespace:
parser = newNamespaceParser(kind.Name)
case services.KindRole:
parser = newRoleParser()
case services.KindUser:
parser = newUserParser()
case services.KindNode:
parser = newNodeParser()
case services.KindProxy:
parser = newProxyParser()
case services.KindAuthServer:
parser = newAuthServerParser()
case services.KindTunnelConnection:
parser = newTunnelConnectionParser()
case services.KindReverseTunnel:
parser = newReverseTunnelParser()
default:
return nil, trace.BadParameter("watcher on object kind %v is not supported", kind)
}
prefixes = append(prefixes, parser.prefix())
parsers = append(parsers, parser)
}
// sort so that longer prefixes get first
sort.Slice(parsers, func(i, j int) bool { return len(parsers[i].prefix()) > len(parsers[j].prefix()) })
w, err := e.backend.NewWatcher(ctx, backend.Watch{
Name: watch.Name,
Prefixes: prefixes,
QueueSize: watch.QueueSize,
MetricComponent: watch.MetricComponent,
})
if err != nil {
return nil, trace.Wrap(err)
}
return newWatcher(w, e.Entry, parsers), nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/services/local/events.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/events.go#L715-L721
|
go
|
train
|
// base returns last element delimited by separator, index is
// is an index of the key part to get counting from the end
|
func base(key []byte, offset int) ([]byte, error)
|
// base returns last element delimited by separator, index is
// is an index of the key part to get counting from the end
func base(key []byte, offset int) ([]byte, error)
|
{
parts := bytes.Split(key, []byte{backend.Separator})
if len(parts) < offset+1 {
return nil, trace.NotFound("failed parsing %v", string(key))
}
return parts[len(parts)-offset-1], nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/services/local/events.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/events.go#L724-L730
|
go
|
train
|
// baseTwoKeys returns two last keys
|
func baseTwoKeys(key []byte) (string, string, error)
|
// baseTwoKeys returns two last keys
func baseTwoKeys(key []byte) (string, string, error)
|
{
parts := bytes.Split(key, []byte{backend.Separator})
if len(parts) < 2 {
return "", "", trace.NotFound("failed parsing %v", string(key))
}
return string(parts[len(parts)-2]), string(parts[len(parts)-1]), nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/auth/api.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L142-L147
|
go
|
train
|
// NewWrapper returns new access point wrapper
|
func NewWrapper(writer AccessPoint, cache ReadAccessPoint) AccessPoint
|
// NewWrapper returns new access point wrapper
func NewWrapper(writer AccessPoint, cache ReadAccessPoint) AccessPoint
|
{
return &Wrapper{
Write: writer,
ReadAccessPoint: cache,
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/auth/api.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L158-L160
|
go
|
train
|
// UpsertNode is part of auth.AccessPoint implementation
|
func (w *Wrapper) UpsertNode(s services.Server) (*services.KeepAlive, error)
|
// UpsertNode is part of auth.AccessPoint implementation
func (w *Wrapper) UpsertNode(s services.Server) (*services.KeepAlive, error)
|
{
return w.Write.UpsertNode(s)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/auth/api.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L163-L165
|
go
|
train
|
// UpsertAuthServer is part of auth.AccessPoint implementation
|
func (w *Wrapper) UpsertAuthServer(s services.Server) error
|
// UpsertAuthServer is part of auth.AccessPoint implementation
func (w *Wrapper) UpsertAuthServer(s services.Server) error
|
{
return w.Write.UpsertAuthServer(s)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/auth/api.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L168-L170
|
go
|
train
|
// NewKeepAliver returns a new instance of keep aliver
|
func (w *Wrapper) NewKeepAliver(ctx context.Context) (services.KeepAliver, error)
|
// NewKeepAliver returns a new instance of keep aliver
func (w *Wrapper) NewKeepAliver(ctx context.Context) (services.KeepAliver, error)
|
{
return w.Write.NewKeepAliver(ctx)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/auth/api.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L173-L175
|
go
|
train
|
// UpsertProxy is part of auth.AccessPoint implementation
|
func (w *Wrapper) UpsertProxy(s services.Server) error
|
// UpsertProxy is part of auth.AccessPoint implementation
func (w *Wrapper) UpsertProxy(s services.Server) error
|
{
return w.Write.UpsertProxy(s)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/auth/api.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L178-L180
|
go
|
train
|
// UpsertTunnelConnection is a part of auth.AccessPoint implementation
|
func (w *Wrapper) UpsertTunnelConnection(conn services.TunnelConnection) error
|
// UpsertTunnelConnection is a part of auth.AccessPoint implementation
func (w *Wrapper) UpsertTunnelConnection(conn services.TunnelConnection) error
|
{
return w.Write.UpsertTunnelConnection(conn)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/auth/api.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/api.go#L183-L185
|
go
|
train
|
// DeleteTunnelConnection is a part of auth.AccessPoint implementation
|
func (w *Wrapper) DeleteTunnelConnection(clusterName, connName string) error
|
// DeleteTunnelConnection is a part of auth.AccessPoint implementation
func (w *Wrapper) DeleteTunnelConnection(clusterName, connName string) error
|
{
return w.Write.DeleteTunnelConnection(clusterName, connName)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/server.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L113-L118
|
go
|
train
|
// SetShutdownPollPeriod sets a polling period for graceful shutdowns of SSH servers
|
func SetShutdownPollPeriod(period time.Duration) ServerOption
|
// SetShutdownPollPeriod sets a polling period for graceful shutdowns of SSH servers
func SetShutdownPollPeriod(period time.Duration) ServerOption
|
{
return func(s *Server) error {
s.shutdownPollPeriod = period
return nil
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/server.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L268-L273
|
go
|
train
|
// Wait waits until server stops serving new connections
// on the listener socket
|
func (s *Server) Wait(ctx context.Context)
|
// Wait waits until server stops serving new connections
// on the listener socket
func (s *Server) Wait(ctx context.Context)
|
{
select {
case <-s.closeContext.Done():
case <-ctx.Done():
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/server.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L277-L305
|
go
|
train
|
// Shutdown initiates graceful shutdown - waiting until all active
// connections will get closed
|
func (s *Server) Shutdown(ctx context.Context) error
|
// Shutdown initiates graceful shutdown - waiting until all active
// connections will get closed
func (s *Server) Shutdown(ctx context.Context) error
|
{
// close listener to stop receiving new connections
err := s.Close()
s.Wait(ctx)
activeConnections := s.trackConnections(0)
if activeConnections == 0 {
return err
}
s.Infof("Shutdown: waiting for %v connections to finish.", activeConnections)
lastReport := time.Time{}
ticker := time.NewTicker(s.shutdownPollPeriod)
defer ticker.Stop()
for {
select {
case <-ticker.C:
activeConnections = s.trackConnections(0)
if activeConnections == 0 {
return err
}
if time.Now().Sub(lastReport) > 10*s.shutdownPollPeriod {
s.Infof("Shutdown: waiting for %v connections to finish.", activeConnections)
lastReport = time.Now()
}
case <-ctx.Done():
s.Infof("Context cancelled wait, returning.")
return trace.ConnectionProblem(err, "context cancelled")
}
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/server.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L308-L330
|
go
|
train
|
// Close closes listening socket and stops accepting connections
|
func (s *Server) Close() error
|
// Close closes listening socket and stops accepting connections
func (s *Server) Close() error
|
{
s.Lock()
defer s.Unlock()
// If no listener is set, the server is in tunnel mode which means
// closeFunc has to be manually called.
if s.listener == nil {
s.closeFunc()
return nil
}
// listener already closed, nothing to do
if s.listenerClosed {
return nil
}
s.listenerClosed = true
if s.listener != nil {
err := s.listener.Close()
return err
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/server.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L368-L449
|
go
|
train
|
// HandleConnection is called every time an SSH server accepts a new
// connection from a client.
//
// this is the foundation of all SSH connections in Teleport (between clients
// and proxies, proxies and servers, servers and auth, etc).
//
|
func (s *Server) HandleConnection(conn net.Conn)
|
// HandleConnection is called every time an SSH server accepts a new
// connection from a client.
//
// this is the foundation of all SSH connections in Teleport (between clients
// and proxies, proxies and servers, servers and auth, etc).
//
func (s *Server) HandleConnection(conn net.Conn)
|
{
s.trackConnections(1)
defer s.trackConnections(-1)
// initiate an SSH connection, note that we don't need to close the conn here
// in case of error as ssh server takes care of this
remoteAddr, _, err := net.SplitHostPort(conn.RemoteAddr().String())
if err != nil {
log.Errorf(err.Error())
}
if err := s.limiter.AcquireConnection(remoteAddr); err != nil {
log.Errorf(err.Error())
conn.Close()
return
}
defer s.limiter.ReleaseConnection(remoteAddr)
// apply idle read/write timeout to this connection.
conn = utils.ObeyIdleTimeout(conn,
defaults.DefaultIdleConnectionDuration,
s.component)
// Wrap connection with a tracker used to monitor how much data was
// transmitted and received over the connection.
wconn := utils.NewTrackingConn(conn)
// create a new SSH server which handles the handshake (and pass the custom
// payload structure which will be populated only when/if this connection
// comes from another Teleport proxy):
sconn, chans, reqs, err := ssh.NewServerConn(wrapConnection(wconn), &s.cfg)
if err != nil {
conn.SetDeadline(time.Time{})
return
}
user := sconn.User()
if err := s.limiter.RegisterRequest(user); err != nil {
log.Errorf(err.Error())
sconn.Close()
conn.Close()
return
}
// Connection successfully initiated
s.Debugf("Incoming connection %v -> %v vesion: %v.",
sconn.RemoteAddr(), sconn.LocalAddr(), string(sconn.ClientVersion()))
// will be called when the connection is closed
connClosed := func() {
s.Debugf("Closed connection %v.", sconn.RemoteAddr())
}
// The keepalive ticket will ensure that SSH keepalive requests are being sent
// to the client at an interval much shorter than idle connection kill switch
keepAliveTick := time.NewTicker(defaults.DefaultIdleConnectionDuration / 3)
defer keepAliveTick.Stop()
keepAlivePayload := [8]byte{0}
for {
select {
// handle out of band ssh requests
case req := <-reqs:
if req == nil {
connClosed()
return
}
s.Debugf("Received out-of-band request: %+v.", req)
if s.reqHandler != nil {
go s.reqHandler.HandleRequest(req)
}
// handle channels:
case nch := <-chans:
if nch == nil {
connClosed()
return
}
go s.newChanHandler.HandleNewChan(wconn, sconn, nch)
// send keepalive pings to the clients
case <-keepAliveTick.C:
const wantReply = true
sconn.SendRequest(teleport.KeepAliveReqType, wantReply, keepAlivePayload[:])
}
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/server.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L506-L522
|
go
|
train
|
// validateHostSigner make sure the signer is a valid certificate.
|
func validateHostSigner(signer ssh.Signer) error
|
// validateHostSigner make sure the signer is a valid certificate.
func validateHostSigner(signer ssh.Signer) error
|
{
cert, ok := signer.PublicKey().(*ssh.Certificate)
if !ok {
return trace.BadParameter("only host certificates supported")
}
if len(cert.ValidPrincipals) == 0 {
return trace.BadParameter("at least one valid principal is required in host certificate")
}
certChecker := utils.CertChecker{}
err := certChecker.CheckCert(cert.ValidPrincipals[0], cert)
if err != nil {
return trace.Wrap(err)
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/server.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L528-L532
|
go
|
train
|
// KeysEqual is constant time compare of the keys to avoid timing attacks
|
func KeysEqual(ak, bk ssh.PublicKey) bool
|
// KeysEqual is constant time compare of the keys to avoid timing attacks
func KeysEqual(ak, bk ssh.PublicKey) bool
|
{
a := ssh.Marshal(ak)
b := ssh.Marshal(bk)
return (len(a) == len(b) && subtle.ConstantTimeCompare(a, b) == 1)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/server.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L568-L612
|
go
|
train
|
// Read implements io.Read() part of net.Connection which allows us
// peek at the beginning of SSH handshake (that's why we're wrapping the connection)
|
func (c *connectionWrapper) Read(b []byte) (int, error)
|
// Read implements io.Read() part of net.Connection which allows us
// peek at the beginning of SSH handshake (that's why we're wrapping the connection)
func (c *connectionWrapper) Read(b []byte) (int, error)
|
{
// handshake already took place, forward upstream:
if c.upstreamReader != nil {
return c.upstreamReader.Read(b)
}
// inspect the client's hello message and see if it's a teleport
// proxy connecting?
buff := make([]byte, MaxVersionStringBytes)
n, err := c.Conn.Read(buff)
if err != nil {
// EOF happens quite often, don't pollute the logs with EOF
if err != io.EOF {
log.Error(err)
}
return n, err
}
// chop off extra unused bytes at the end of the buffer:
buff = buff[:n]
var skip = 0
// are we reading from a Teleport proxy?
if bytes.HasPrefix(buff, []byte(ProxyHelloSignature)) {
// the JSON paylaod ends with a binary zero:
payloadBoundary := bytes.IndexByte(buff, 0x00)
if payloadBoundary > 0 {
var hp HandshakePayload
payload := buff[len(ProxyHelloSignature):payloadBoundary]
if err = json.Unmarshal(payload, &hp); err != nil {
log.Error(err)
} else {
ca, err := utils.ParseAddr(hp.ClientAddr)
if err != nil {
log.Error(err)
} else {
// replace proxy's client addr with a real client address
// we just got from the custom payload:
c.clientAddr = ca
}
}
skip = payloadBoundary + 1
}
}
c.upstreamReader = io.MultiReader(bytes.NewBuffer(buff[skip:]), c.Conn)
return c.upstreamReader.Read(b)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/sshutils/server.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/server.go#L616-L621
|
go
|
train
|
// wrapConnection takes a network connection, wraps it into connectionWrapper
// object (which overrides Read method) and returns the wrapper.
|
func wrapConnection(conn net.Conn) net.Conn
|
// wrapConnection takes a network connection, wraps it into connectionWrapper
// object (which overrides Read method) and returns the wrapper.
func wrapConnection(conn net.Conn) net.Conn
|
{
return &connectionWrapper{
Conn: conn,
clientAddr: conn.RemoteAddr(),
}
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/backend/backend.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L132-L134
|
go
|
train
|
// String returns a user-friendly description
// of the watcher
|
func (w *Watch) String() string
|
// String returns a user-friendly description
// of the watcher
func (w *Watch) String() string
|
{
return fmt.Sprintf("Watcher(name=%v, prefixes=%v)", w.Name, string(bytes.Join(w.Prefixes, []byte(", "))))
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/backend/backend.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L229-L236
|
go
|
train
|
// GetString returns a string value stored in Params map, or an empty string
// if nothing is found
|
func (p Params) GetString(key string) string
|
// GetString returns a string value stored in Params map, or an empty string
// if nothing is found
func (p Params) GetString(key string) string
|
{
v, ok := p[key]
if !ok {
return ""
}
s, _ := v.(string)
return s
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/backend/backend.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L242-L254
|
go
|
train
|
// RangeEnd returns end of the range for given key
|
func RangeEnd(key []byte) []byte
|
// RangeEnd returns end of the range for given key
func RangeEnd(key []byte) []byte
|
{
end := make([]byte, len(key))
copy(end, key)
for i := len(end) - 1; i >= 0; i-- {
if end[i] < 0xff {
end[i] = end[i] + 1
end = end[:i+1]
return end
}
}
// next key does not exist (e.g., 0xffff);
return noEnd
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/backend/backend.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L269-L271
|
go
|
train
|
// Swap is part of sort.Interface.
|
func (it Items) Swap(i, j int)
|
// Swap is part of sort.Interface.
func (it Items) Swap(i, j int)
|
{
it[i], it[j] = it[j], it[i]
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/backend/backend.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L279-L285
|
go
|
train
|
// TTL returns TTL in duration units, rounds up to one second
|
func TTL(clock clockwork.Clock, expires time.Time) time.Duration
|
// TTL returns TTL in duration units, rounds up to one second
func TTL(clock clockwork.Clock, expires time.Time) time.Duration
|
{
ttl := expires.Sub(clock.Now())
if ttl < time.Second {
return time.Second
}
return ttl
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/backend/backend.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L289-L295
|
go
|
train
|
// EarliestExpiry returns first of the
// otherwise returns empty
|
func EarliestExpiry(times ...time.Time) time.Time
|
// EarliestExpiry returns first of the
// otherwise returns empty
func EarliestExpiry(times ...time.Time) time.Time
|
{
if len(times) == 0 {
return time.Time{}
}
sort.Sort(earliest(times))
return times[0]
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/backend/backend.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L299-L304
|
go
|
train
|
// Expiry converts ttl to expiry time, if ttl is 0
// returns empty time
|
func Expiry(clock clockwork.Clock, ttl time.Duration) time.Time
|
// Expiry converts ttl to expiry time, if ttl is 0
// returns empty time
func Expiry(clock clockwork.Clock, ttl time.Duration) time.Time
|
{
if ttl == 0 {
return time.Time{}
}
return clock.Now().UTC().Add(ttl)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/backend/backend.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/backend/backend.go#L331-L333
|
go
|
train
|
// Key joins parts into path separated by Separator,
// makes sure path always starts with Separator ("/")
|
func Key(parts ...string) []byte
|
// Key joins parts into path separated by Separator,
// makes sure path always starts with Separator ("/")
func Key(parts ...string) []byte
|
{
return []byte(strings.Join(append([]string{""}, parts...), string(Separator)))
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/utils/agentconn/agent_unix.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/agentconn/agent_unix.go#L28-L35
|
go
|
train
|
// Dial creates net.Conn to a SSH agent listening on a Unix socket.
|
func Dial(socket string) (net.Conn, error)
|
// Dial creates net.Conn to a SSH agent listening on a Unix socket.
func Dial(socket string) (net.Conn, error)
|
{
conn, err := net.Dial("unix", socket)
if err != nil {
return nil, trace.Wrap(err)
}
return conn, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/services/authentication.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L77-L87
|
go
|
train
|
// NewAuthPreference is a convenience method to to create AuthPreferenceV2.
|
func NewAuthPreference(spec AuthPreferenceSpecV2) (AuthPreference, error)
|
// NewAuthPreference is a convenience method to to create AuthPreferenceV2.
func NewAuthPreference(spec AuthPreferenceSpecV2) (AuthPreference, error)
|
{
return &AuthPreferenceV2{
Kind: KindClusterAuthPreference,
Version: V2,
Metadata: Metadata{
Name: MetaNameClusterAuthPreference,
Namespace: defaults.Namespace,
},
Spec: spec,
}, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/services/authentication.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L108-L110
|
go
|
train
|
// SetExpiry sets expiry time for the object
|
func (s *AuthPreferenceV2) SetExpiry(expires time.Time)
|
// SetExpiry sets expiry time for the object
func (s *AuthPreferenceV2) SetExpiry(expires time.Time)
|
{
s.Metadata.SetExpiry(expires)
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/services/authentication.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L175-L180
|
go
|
train
|
// GetU2F gets the U2F configuration settings.
|
func (c *AuthPreferenceV2) GetU2F() (*U2F, error)
|
// GetU2F gets the U2F configuration settings.
func (c *AuthPreferenceV2) GetU2F() (*U2F, error)
|
{
if c.Spec.U2F == nil {
return nil, trace.NotFound("U2F configuration not found")
}
return c.Spec.U2F, nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/services/authentication.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L188-L212
|
go
|
train
|
// CheckAndSetDefaults verifies the constraints for AuthPreference.
|
func (c *AuthPreferenceV2) CheckAndSetDefaults() error
|
// CheckAndSetDefaults verifies the constraints for AuthPreference.
func (c *AuthPreferenceV2) CheckAndSetDefaults() error
|
{
// if nothing is passed in, set defaults
if c.Spec.Type == "" {
c.Spec.Type = teleport.Local
}
if c.Spec.SecondFactor == "" {
c.Spec.SecondFactor = teleport.OTP
}
// make sure type makes sense
switch c.Spec.Type {
case teleport.Local, teleport.OIDC, teleport.SAML, teleport.Github:
default:
return trace.BadParameter("authentication type %q not supported", c.Spec.Type)
}
// make sure second factor makes sense
switch c.Spec.SecondFactor {
case teleport.OFF, teleport.OTP, teleport.U2F:
default:
return trace.BadParameter("second factor type %q not supported", c.Spec.SecondFactor)
}
return nil
}
|
gravitational/teleport
|
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
|
lib/services/authentication.go
|
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L215-L217
|
go
|
train
|
// String represents a human readable version of authentication settings.
|
func (c *AuthPreferenceV2) String() string
|
// String represents a human readable version of authentication settings.
func (c *AuthPreferenceV2) String() string
|
{
return fmt.Sprintf("AuthPreference(Type=%q,SecondFactor=%q)", c.Spec.Type, c.Spec.SecondFactor)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.