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/events/multilog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/events/multilog.go#L127-L135
go
train
// SearchEvents is a flexible way to find events. 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 (m *MultiLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) (events []EventFields, err error)
// SearchEvents is a flexible way to find events. 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 (m *MultiLog) SearchEvents(fromUTC, toUTC time.Time, query string, limit int) (events []EventFields, err error)
{ for _, log := range m.loggers { events, err = log.SearchEvents(fromUTC, toUTC, query, limit) if !trace.IsNotImplemented(err) { return events, err } } return events, err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L73-L109
go
train
// GetSites returns list of the "sites" (AKA teleport clusters) connected to the proxy // Each site is returned as an instance of its auth server //
func (proxy *ProxyClient) GetSites() ([]services.Site, error)
// GetSites returns list of the "sites" (AKA teleport clusters) connected to the proxy // Each site is returned as an instance of its auth server // func (proxy *ProxyClient) GetSites() ([]services.Site, error)
{ proxySession, err := proxy.Client.NewSession() defer proxySession.Close() if err != nil { return nil, trace.Wrap(err) } stdout := &bytes.Buffer{} reader, err := proxySession.StdoutPipe() if err != nil { return nil, trace.Wrap(err) } done := make(chan struct{}) go func() { io.Copy(stdout, reader) close(done) }() // this function is async because, // the function call StdoutPipe() could fail if proxy rejected // the session request, and then RequestSubsystem call could hang // forever go func() { if err := proxySession.RequestSubsystem("proxysites"); err != nil { log.Warningf("Failed to request subsystem: %v", err) } }() select { case <-done: case <-time.After(defaults.DefaultDialTimeout): return nil, trace.ConnectionProblem(nil, "timeout") } log.Debugf("Found clusters: %v", stdout.String()) var sites []services.Site if err := json.Unmarshal(stdout.Bytes(), &sites); err != nil { return nil, trace.Wrap(err) } return sites, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L116-L138
go
train
// FindServersByLabels returns list of the nodes which have labels exactly matching // the given label set. // // A server is matched when ALL labels match. // If no labels are passed, ALL nodes are returned.
func (proxy *ProxyClient) FindServersByLabels(ctx context.Context, namespace string, labels map[string]string) ([]services.Server, error)
// FindServersByLabels returns list of the nodes which have labels exactly matching // the given label set. // // A server is matched when ALL labels match. // If no labels are passed, ALL nodes are returned. func (proxy *ProxyClient) FindServersByLabels(ctx context.Context, namespace string, labels map[string]string) ([]services.Server, error)
{ if namespace == "" { return nil, trace.BadParameter(auth.MissingNamespaceError) } nodes := make([]services.Server, 0) site, err := proxy.CurrentClusterAccessPoint(ctx, false) if err != nil { return nil, trace.Wrap(err) } siteNodes, err := site.GetNodes(namespace, services.SkipValidation()) if err != nil { return nil, trace.Wrap(err) } // look at every node on this site and see which ones match: for _, node := range siteNodes { if node.MatchAgainst(labels) { nodes = append(nodes, node) } } return nodes, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L143-L150
go
train
// CurrentClusterAccessPoint returns cluster access point to the currently // selected cluster and is used for discovery // and could be cached based on the access policy
func (proxy *ProxyClient) CurrentClusterAccessPoint(ctx context.Context, quiet bool) (auth.AccessPoint, error)
// CurrentClusterAccessPoint returns cluster access point to the currently // selected cluster and is used for discovery // and could be cached based on the access policy func (proxy *ProxyClient) CurrentClusterAccessPoint(ctx context.Context, quiet bool) (auth.AccessPoint, error)
{ // get the current cluster: cluster, err := proxy.currentCluster() if err != nil { return nil, trace.Wrap(err) } return proxy.ClusterAccessPoint(ctx, cluster.Name, quiet) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L154-L163
go
train
// ClusterAccessPoint returns cluster access point used for discovery // and could be cached based on the access policy
func (proxy *ProxyClient) ClusterAccessPoint(ctx context.Context, clusterName string, quiet bool) (auth.AccessPoint, error)
// ClusterAccessPoint returns cluster access point used for discovery // and could be cached based on the access policy func (proxy *ProxyClient) ClusterAccessPoint(ctx context.Context, clusterName string, quiet bool) (auth.AccessPoint, error)
{ if clusterName == "" { return nil, trace.BadParameter("parameter clusterName is missing") } clt, err := proxy.ConnectToCluster(ctx, clusterName, quiet) if err != nil { return nil, trace.Wrap(err) } return proxy.teleportClient.accessPoint(clt, proxy.proxyAddress, clusterName) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L170-L176
go
train
// ConnectToCurrentCluster connects to the auth server of the currently selected // cluster via proxy. It returns connected and authenticated auth server client // // if 'quiet' is set to true, no errors will be printed to stdout, otherwise // any connection errors are visible to a user.
func (proxy *ProxyClient) ConnectToCurrentCluster(ctx context.Context, quiet bool) (auth.ClientI, error)
// ConnectToCurrentCluster connects to the auth server of the currently selected // cluster via proxy. It returns connected and authenticated auth server client // // if 'quiet' is set to true, no errors will be printed to stdout, otherwise // any connection errors are visible to a user. func (proxy *ProxyClient) ConnectToCurrentCluster(ctx context.Context, quiet bool) (auth.ClientI, error)
{ cluster, err := proxy.currentCluster() if err != nil { return nil, trace.Wrap(err) } return proxy.ConnectToCluster(ctx, cluster.Name, quiet) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L183-L226
go
train
// ConnectToCluster connects to the auth server of the given cluster via proxy. // It returns connected and authenticated auth server client // // if 'quiet' is set to true, no errors will be printed to stdout, otherwise // any connection errors are visible to a user.
func (proxy *ProxyClient) ConnectToCluster(ctx context.Context, clusterName string, quiet bool) (auth.ClientI, error)
// ConnectToCluster connects to the auth server of the given cluster via proxy. // It returns connected and authenticated auth server client // // if 'quiet' is set to true, no errors will be printed to stdout, otherwise // any connection errors are visible to a user. func (proxy *ProxyClient) ConnectToCluster(ctx context.Context, clusterName string, quiet bool) (auth.ClientI, error)
{ dialer := func(ctx context.Context, network, _ string) (net.Conn, error) { return proxy.dialAuthServer(ctx, clusterName) } if proxy.teleportClient.SkipLocalAuth { return auth.NewTLSClient(auth.ClientConfig{ DialContext: dialer, TLS: proxy.teleportClient.TLS, }) } // Because Teleport clients can't be configured (yet), they take the default // list of cipher suites from Go. tlsConfig := utils.TLSConfig(nil) localAgent := proxy.teleportClient.LocalAgent() pool, err := localAgent.GetCerts() if err != nil { return nil, trace.Wrap(err) } tlsConfig.RootCAs = pool key, err := localAgent.GetKey() if err != nil { return nil, trace.Wrap(err, "failed to fetch TLS key for %v", proxy.teleportClient.Username) } if len(key.TLSCert) != 0 { tlsCert, err := tls.X509KeyPair(key.TLSCert, key.Priv) if err != nil { return nil, trace.Wrap(err, "failed to parse TLS cert and key") } tlsConfig.Certificates = append(tlsConfig.Certificates, tlsCert) } if len(tlsConfig.Certificates) == 0 { return nil, trace.BadParameter("no TLS keys found for user %v, please relogin to get new credentials", proxy.teleportClient.Username) } clt, err := auth.NewTLSClient(auth.ClientConfig{ DialContext: dialer, TLS: tlsConfig, }) if err != nil { return nil, trace.Wrap(err) } return clt, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L236-L238
go
train
// addCloser adds any closer in ctx that will be called // whenever server closes session channel
func (c *closerConn) addCloser(closer io.Closer)
// addCloser adds any closer in ctx that will be called // whenever server closes session channel func (c *closerConn) addCloser(closer io.Closer)
{ c.closers = append(c.closers, closer) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L250-L256
go
train
// nodeName removes the port number from the hostname, if present
func nodeName(node string) string
// nodeName removes the port number from the hostname, if present func nodeName(node string) string
{ n, _, err := net.SplitHostPort(node) if err != nil { return node } return n }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L266-L305
go
train
// isRecordingProxy returns true if the proxy is in recording mode. Note, this // function can only be called after authentication has occurred and should be // called before the first session is created.
func (proxy *ProxyClient) isRecordingProxy() (bool, error)
// isRecordingProxy returns true if the proxy is in recording mode. Note, this // function can only be called after authentication has occurred and should be // called before the first session is created. func (proxy *ProxyClient) isRecordingProxy() (bool, error)
{ responseCh := make(chan proxyResponse) // we have to run this in a goroutine because older version of Teleport handled // global out-of-band requests incorrectly: Teleport would ignore requests it // does not know about and never reply to them. So if we wait a second and // don't hear anything back, most likley we are trying to connect to an older // version of Teleport and we should not try and forward our agent. go func() { ok, responseBytes, err := proxy.Client.SendRequest(teleport.RecordingProxyReqType, true, nil) if err != nil { responseCh <- proxyResponse{isRecord: false, err: trace.Wrap(err)} return } if !ok { responseCh <- proxyResponse{isRecord: false, err: trace.AccessDenied("unable to determine proxy type")} return } recordingProxy, err := strconv.ParseBool(string(responseBytes)) if err != nil { responseCh <- proxyResponse{isRecord: false, err: trace.Wrap(err)} return } responseCh <- proxyResponse{isRecord: recordingProxy, err: nil} }() select { case resp := <-responseCh: if resp.err != nil { return false, trace.Wrap(resp.err) } return resp.isRecord, nil case <-time.After(1 * time.Second): // probably the older version of the proxy or at least someone that is // responding incorrectly, don't forward agent to it return false, nil } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L308-L355
go
train
// dialAuthServer returns auth server connection forwarded via proxy
func (proxy *ProxyClient) dialAuthServer(ctx context.Context, clusterName string) (net.Conn, error)
// dialAuthServer returns auth server connection forwarded via proxy func (proxy *ProxyClient) dialAuthServer(ctx context.Context, clusterName string) (net.Conn, error)
{ log.Debugf("Client %v is connecting to auth server on cluster %q.", proxy.clientAddr, clusterName) address := "@" + clusterName // parse destination first: localAddr, err := utils.ParseAddr("tcp://" + proxy.proxyAddress) if err != nil { return nil, trace.Wrap(err) } fakeAddr, err := utils.ParseAddr("tcp://" + address) if err != nil { return nil, trace.Wrap(err) } proxySession, err := proxy.Client.NewSession() if err != nil { return nil, trace.Wrap(err) } proxyWriter, err := proxySession.StdinPipe() if err != nil { return nil, trace.Wrap(err) } proxyReader, err := proxySession.StdoutPipe() if err != nil { return nil, trace.Wrap(err) } proxyErr, err := proxySession.StderrPipe() if err != nil { return nil, trace.Wrap(err) } err = proxySession.RequestSubsystem("proxy:" + address) if err != nil { // read the stderr output from the failed SSH session and append // it to the end of our own message: serverErrorMsg, _ := ioutil.ReadAll(proxyErr) return nil, trace.ConnectionProblem(err, "failed connecting to node %v. %s", nodeName(strings.Split(address, "@")[0]), serverErrorMsg) } return utils.NewPipeNetConn( proxyReader, proxyWriter, proxySession, localAddr, fakeAddr, ), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L359-L474
go
train
// ConnectToNode connects to the ssh server via Proxy. // It returns connected and authenticated NodeClient
func (proxy *ProxyClient) ConnectToNode(ctx context.Context, nodeAddress string, user string, quiet bool) (*NodeClient, error)
// ConnectToNode connects to the ssh server via Proxy. // It returns connected and authenticated NodeClient func (proxy *ProxyClient) ConnectToNode(ctx context.Context, nodeAddress string, user string, quiet bool) (*NodeClient, error)
{ log.Infof("Client=%v connecting to node=%s", proxy.clientAddr, nodeAddress) // parse destination first: localAddr, err := utils.ParseAddr("tcp://" + proxy.proxyAddress) if err != nil { return nil, trace.Wrap(err) } fakeAddr, err := utils.ParseAddr("tcp://" + nodeAddress) if err != nil { return nil, trace.Wrap(err) } // after auth but before we create the first session, find out if the proxy // is in recording mode or not recordingProxy, err := proxy.isRecordingProxy() if err != nil { return nil, trace.Wrap(err) } proxySession, err := proxy.Client.NewSession() if err != nil { return nil, trace.Wrap(err) } proxyWriter, err := proxySession.StdinPipe() if err != nil { return nil, trace.Wrap(err) } proxyReader, err := proxySession.StdoutPipe() if err != nil { return nil, trace.Wrap(err) } proxyErr, err := proxySession.StderrPipe() if err != nil { return nil, trace.Wrap(err) } // pass the true client IP (if specified) to the proxy so it could pass it into the // SSH session for proper audit if len(proxy.clientAddr) > 0 { if err = proxySession.Setenv(sshutils.TrueClientAddrVar, proxy.clientAddr); err != nil { log.Error(err) } } // the client only tries to forward an agent when the proxy is in recording // mode. we always try and forward an agent here because each new session // creates a new context which holds the agent. if ForwardToAgent returns an error // "already have handler for" we ignore it. if recordingProxy { err = agent.ForwardToAgent(proxy.Client, proxy.teleportClient.localAgent.Agent) if err != nil && !strings.Contains(err.Error(), "agent: already have handler for") { return nil, trace.Wrap(err) } err = agent.RequestAgentForwarding(proxySession) if err != nil { return nil, trace.Wrap(err) } } err = proxySession.RequestSubsystem("proxy:" + nodeAddress) if err != nil { // read the stderr output from the failed SSH session and append // it to the end of our own message: serverErrorMsg, _ := ioutil.ReadAll(proxyErr) return nil, trace.ConnectionProblem(err, "failed connecting to node %v. %s", nodeName(strings.Split(nodeAddress, "@")[0]), serverErrorMsg) } pipeNetConn := utils.NewPipeNetConn( proxyReader, proxyWriter, proxySession, localAddr, fakeAddr, ) sshConfig := &ssh.ClientConfig{ User: user, Auth: []ssh.AuthMethod{proxy.authMethod}, HostKeyCallback: proxy.hostKeyCallback, } conn, chans, reqs, err := newClientConn(ctx, pipeNetConn, nodeAddress, sshConfig) if err != nil { if utils.IsHandshakeFailedError(err) { proxySession.Close() parts := strings.Split(nodeAddress, "@") hostname := parts[0] if len(hostname) == 0 && len(parts) > 1 { hostname = "cluster " + parts[1] } return nil, trace.Errorf(`access denied to %v connecting to %v`, user, nodeName(hostname)) } return nil, trace.Wrap(err) } // We pass an empty channel which we close right away to ssh.NewClient // because the client need to handle requests itself. emptyCh := make(chan *ssh.Request) close(emptyCh) client := ssh.NewClient(conn, chans, emptyCh) nc := &NodeClient{ Client: client, Proxy: proxy, Namespace: defaults.Namespace, TC: proxy.teleportClient, } // Start a goroutine that will run for the duration of the client to process // global requests from the client. Teleport clients will use this to update // terminal sizes when the remote PTY size has changed. go nc.handleGlobalRequests(ctx, reqs) return nc, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L517-L550
go
train
// newClientConn is a wrapper around ssh.NewClientConn
func newClientConn(ctx context.Context, conn net.Conn, nodeAddress string, config *ssh.ClientConfig) (ssh.Conn, <-chan ssh.NewChannel, <-chan *ssh.Request, error)
// newClientConn is a wrapper around ssh.NewClientConn func newClientConn(ctx context.Context, conn net.Conn, nodeAddress string, config *ssh.ClientConfig) (ssh.Conn, <-chan ssh.NewChannel, <-chan *ssh.Request, error)
{ type response struct { conn ssh.Conn chanCh <-chan ssh.NewChannel reqCh <-chan *ssh.Request err error } respCh := make(chan response, 1) go func() { conn, chans, reqs, err := ssh.NewClientConn(conn, nodeAddress, config) respCh <- response{conn, chans, reqs, err} }() select { case resp := <-respCh: if resp.err != nil { return nil, nil, nil, trace.Wrap(resp.err, "failed to connect to %q", nodeAddress) } return resp.conn, resp.chanCh, resp.reqCh, nil case <-ctx.Done(): errClose := conn.Close() if errClose != nil { log.Error(errClose) } // drain the channel resp := <-respCh return nil, nil, nil, trace.ConnectionProblem(resp.err, "failed to connect to %q", nodeAddress) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L558-L607
go
train
// ExecuteSCP runs remote scp command(shellCmd) on the remote server and // runs local scp handler using SCP Command
func (client *NodeClient) ExecuteSCP(cmd scp.Command) error
// ExecuteSCP runs remote scp command(shellCmd) on the remote server and // runs local scp handler using SCP Command func (client *NodeClient) ExecuteSCP(cmd scp.Command) error
{ shellCmd, err := cmd.GetRemoteShellCmd() if err != nil { return trace.Wrap(err) } s, err := client.Client.NewSession() if err != nil { return trace.Wrap(err) } defer s.Close() stdin, err := s.StdinPipe() if err != nil { return trace.Wrap(err) } stdout, err := s.StdoutPipe() if err != nil { return trace.Wrap(err) } ch := utils.NewPipeNetConn( stdout, stdin, utils.MultiCloser(), &net.IPAddr{}, &net.IPAddr{}, ) closeC := make(chan interface{}, 1) go func() { if err = cmd.Execute(ch); err != nil { log.Error(err) } stdin.Close() close(closeC) }() runErr := s.Run(shellCmd) <-closeC if runErr != nil && (err == nil || trace.IsEOF(err)) { err = runErr } if trace.IsEOF(err) { err = nil } return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L675-L695
go
train
// listenAndForward listens on a given socket and forwards all incoming // commands to the remote address through the SSH tunnel.
func (c *NodeClient) listenAndForward(ctx context.Context, ln net.Listener, remoteAddr string)
// listenAndForward listens on a given socket and forwards all incoming // commands to the remote address through the SSH tunnel. func (c *NodeClient) listenAndForward(ctx context.Context, ln net.Listener, remoteAddr string)
{ defer ln.Close() defer c.Close() for { // Accept connections from the client. conn, err := ln.Accept() if err != nil { log.Errorf("Port forwarding failed: %v.", err) break } // Proxy the connection to the remote address. go func() { err := c.proxyConnection(ctx, conn, remoteAddr) if err != nil { log.Warnf("Failed to proxy connection: %v.", err) } }() } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L699-L729
go
train
// dynamicListenAndForward listens for connections, performs a SOCKS5 // handshake, and then proxies the connection to the requested address.
func (c *NodeClient) dynamicListenAndForward(ctx context.Context, ln net.Listener)
// dynamicListenAndForward listens for connections, performs a SOCKS5 // handshake, and then proxies the connection to the requested address. func (c *NodeClient) dynamicListenAndForward(ctx context.Context, ln net.Listener)
{ defer ln.Close() defer c.Close() for { // Accept connection from the client. Here the client is typically // something like a web browser or other SOCKS5 aware application. conn, err := ln.Accept() if err != nil { log.Errorf("Dynamic port forwarding (SOCKS5) failed: %v.", err) break } // Perform the SOCKS5 handshake with the client to find out the remote // address to proxy. remoteAddr, err := socks.Handshake(conn) if err != nil { log.Errorf("SOCKS5 handshake failed: %v.", err) break } log.Debugf("SOCKS5 proxy forwarding requests to %v.", remoteAddr) // Proxy the connection to the remote address. go func() { err := c.proxyConnection(ctx, conn, remoteAddr) if err != nil { log.Warnf("Failed to proxy connection: %v.", err) } }() } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/client.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/client.go#L737-L754
go
train
// currentCluster returns the connection to the API of the current cluster
func (proxy *ProxyClient) currentCluster() (*services.Site, error)
// currentCluster returns the connection to the API of the current cluster func (proxy *ProxyClient) currentCluster() (*services.Site, error)
{ sites, err := proxy.GetSites() if err != nil { return nil, trace.Wrap(err) } if len(sites) == 0 { return nil, trace.NotFound("no clusters registered") } if proxy.siteName == "" { return &sites[0], nil } for _, site := range sites { if site.Name == proxy.siteName { return &site, nil } } return nil, trace.NotFound("cluster %v not found", proxy.siteName) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/scp/scp.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/scp.go#L129-L138
go
train
// CreateDownloadCommand configures and returns a command used // to download a file
func CreateDownloadCommand(cfg Config) (Command, error)
// CreateDownloadCommand configures and returns a command used // to download a file func CreateDownloadCommand(cfg Config) (Command, error)
{ cfg.Flags.Sink = true cfg.Flags.Source = false cmd, err := CreateCommand(cfg) if err != nil { return nil, trace.Wrap(err) } return cmd, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/scp/scp.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/scp.go#L154-L164
go
train
// CheckAndSetDefaults checks and sets default values
func (c *Config) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets default values func (c *Config) CheckAndSetDefaults() error
{ if c.FileSystem == nil { c.FileSystem = &localFileSystem{} } if c.User == "" { return trace.BadParameter("missing User parameter") } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/scp/scp.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/scp.go#L167-L190
go
train
// CreateCommand creates and returns a new Command
func CreateCommand(cfg Config) (Command, error)
// CreateCommand creates and returns a new Command func CreateCommand(cfg Config) (Command, error)
{ err := cfg.CheckAndSetDefaults() if err != nil { return nil, trace.Wrap(err) } cmd := command{ Config: cfg, } cmd.log = log.WithFields(log.Fields{ trace.Component: "SCP", trace.ComponentFields: log.Fields{ "LocalAddr": cfg.Flags.LocalAddr, "RemoteAddr": cfg.Flags.RemoteAddr, "Target": cfg.Flags.Target, "User": cfg.User, "RunOnServer": cfg.RunOnServer, "RemoteLocation": cfg.RemoteLocation, }, }) return &cmd, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/scp/scp.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/scp.go#L201-L218
go
train
// Execute() implements SSH file copy (SCP). It is called on both tsh (client) // and teleport (server) side.
func (cmd *command) Execute(ch io.ReadWriter) (err error)
// Execute() implements SSH file copy (SCP). It is called on both tsh (client) // and teleport (server) side. func (cmd *command) Execute(ch io.ReadWriter) (err error)
{ if cmd.Flags.Source { err = cmd.serveSource(ch) } else { err = cmd.serveSink(ch) } if err != nil { if cmd.Config.RunOnServer == false { return trace.Wrap(err) } else { // when 'teleport scp' encounters an error, it SHOULD NOT be logged // to stderr (i.e. we should not return an error here) and instead // it should be sent back to scp client using scp protocol cmd.sendError(ch, err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/scp/scp.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/scp.go#L359-L411
go
train
// serveSink executes file uploading, when a remote server sends file(s) // via scp
func (cmd *command) serveSink(ch io.ReadWriter) error
// serveSink executes file uploading, when a remote server sends file(s) // via scp func (cmd *command) serveSink(ch io.ReadWriter) error
{ // Validate that if directory mode flag was sent, the target is an actual // directory. if cmd.Flags.DirectoryMode { if len(cmd.Flags.Target) != 1 { return trace.BadParameter("in directory mode, only single upload target is allowed, %v provided", len(cmd.Flags.Target)) } fi, err := os.Stat(cmd.Flags.Target[0]) if err != nil { return trace.Wrap(err) } if mode := fi.Mode(); !mode.IsDir() { return trace.BadParameter("target path must be a directory") } } if err := sendOK(ch); err != nil { return trace.Wrap(err) } var st state st.path = []string{"."} var b = make([]byte, 1) scanner := bufio.NewScanner(ch) for { n, err := ch.Read(b) if err != nil { if err == io.EOF { return nil } return trace.Wrap(err) } if n < 1 { return trace.Errorf("unexpected error, read 0 bytes") } if b[0] == OKByte { continue } scanner.Scan() if err := scanner.Err(); err != nil { return trace.Wrap(err) } if err := cmd.processCommand(ch, &st, b[0], scanner.Text()); err != nil { return trace.Wrap(err) } if err := sendOK(ch); err != nil { return trace.Wrap(err) } } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/scp/scp.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/scp.go#L515-L530
go
train
// sendError gets called during all errors during SCP transmission. // It writes it back to the SCP client
func (cmd *command) sendError(ch io.ReadWriter, err error) error
// sendError gets called during all errors during SCP transmission. // It writes it back to the SCP client func (cmd *command) sendError(ch io.ReadWriter, err error) error
{ if err == nil { return nil } cmd.log.Error(err) message := err.Error() bytes := make([]byte, 0, len(message)+2) bytes = append(bytes, ErrByte) bytes = append(bytes, message...) bytes = append(bytes, []byte{'\n'}...) _, writeErr := ch.Write(bytes) if writeErr != nil { cmd.log.Error(writeErr) } return trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/scp/scp.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/scp.go#L639-L659
go
train
// read is used to "ask" for response messages after each SCP transmission // it only reads text data until a newline and returns 'nil' for "OK" responses // and errors for everything else
func (r *reader) read() error
// read is used to "ask" for response messages after each SCP transmission // it only reads text data until a newline and returns 'nil' for "OK" responses // and errors for everything else func (r *reader) read() error
{ n, err := r.r.Read(r.b) if err != nil { return trace.Wrap(err) } if n < 1 { return trace.Errorf("unexpected error, read 0 bytes") } switch r.b[0] { case OKByte: return nil case WarnByte, ErrByte: r.s.Scan() if err := r.s.Err(); err != nil { return trace.Wrap(err) } return trace.Errorf(r.s.Text()) } return trace.Errorf("unrecognized command: %#v", r.b) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/scp/scp.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/scp/scp.go#L664-L681
go
train
// ParseSCPDestination takes a string representing a remote resource for SCP // to download/upload, like "user@host:/path/to/resource.txt" and returns // 3 components of it
func ParseSCPDestination(s string) (login, host, dest string)
// ParseSCPDestination takes a string representing a remote resource for SCP // to download/upload, like "user@host:/path/to/resource.txt" and returns // 3 components of it func ParseSCPDestination(s string) (login, host, dest string)
{ parts := strings.SplitN(s, "@", 2) if len(parts) > 1 { login = parts[0] host = parts[1] } else { host = parts[0] } parts = strings.SplitN(host, ":", 2) if len(parts) > 1 { host = parts[0] dest = parts[1] } if len(dest) == 0 { dest = "." } return login, host, dest }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L126-L138
go
train
// NewFSLocalKeyStore creates a new filesystem-based local keystore object // and initializes it. // // If dirPath is empty, sets it to ~/.tsh.
func NewFSLocalKeyStore(dirPath string) (s *FSLocalKeyStore, err error)
// NewFSLocalKeyStore creates a new filesystem-based local keystore object // and initializes it. // // If dirPath is empty, sets it to ~/.tsh. func NewFSLocalKeyStore(dirPath string) (s *FSLocalKeyStore, err error)
{ dirPath, err = initKeysDir(dirPath) if err != nil { return nil, trace.Wrap(err) } return &FSLocalKeyStore{ log: logrus.WithFields(logrus.Fields{ trace.Component: teleport.ComponentKeyStore, }), KeyDir: dirPath, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L142-L168
go
train
// AddKey adds a new key to the session store. If a key for the host is already // stored, overwrites it.
func (fs *FSLocalKeyStore) AddKey(host, username string, key *Key) error
// AddKey adds a new key to the session store. If a key for the host is already // stored, overwrites it. func (fs *FSLocalKeyStore) AddKey(host, username string, key *Key) error
{ dirPath, err := fs.dirFor(host, true) if err != nil { return trace.Wrap(err) } writeBytes := func(fname string, data []byte) error { fp := filepath.Join(dirPath, fname) err := ioutil.WriteFile(fp, data, keyFilePerms) if err != nil { fs.log.Error(err) } return err } if err = writeBytes(username+fileExtCert, key.Cert); err != nil { return trace.Wrap(err) } if err = writeBytes(username+fileExtTLSCert, key.TLSCert); err != nil { return trace.Wrap(err) } if err = writeBytes(username+fileExtPub, key.Pub); err != nil { return trace.Wrap(err) } if err = writeBytes(username, key.Priv); err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L171-L188
go
train
// DeleteKey deletes a key from the local store
func (fs *FSLocalKeyStore) DeleteKey(host string, username string) error
// DeleteKey deletes a key from the local store func (fs *FSLocalKeyStore) DeleteKey(host string, username string) error
{ dirPath, err := fs.dirFor(host, false) if err != nil { return trace.Wrap(err) } files := []string{ filepath.Join(dirPath, username+fileExtCert), filepath.Join(dirPath, username+fileExtTLSCert), filepath.Join(dirPath, username+fileExtPub), filepath.Join(dirPath, username), } for _, fn := range files { if err = os.Remove(fn); err != nil { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L191-L200
go
train
// DeleteKeys removes all session keys from disk.
func (fs *FSLocalKeyStore) DeleteKeys() error
// DeleteKeys removes all session keys from disk. func (fs *FSLocalKeyStore) DeleteKeys() error
{ dirPath := filepath.Join(fs.KeyDir, sessionKeyDir) err := os.RemoveAll(dirPath) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L204-L263
go
train
// GetKey returns a key for a given host. If the key is not found, // returns trace.NotFound error.
func (fs *FSLocalKeyStore) GetKey(proxyHost string, username string) (*Key, error)
// GetKey returns a key for a given host. If the key is not found, // returns trace.NotFound error. func (fs *FSLocalKeyStore) GetKey(proxyHost string, username string) (*Key, error)
{ dirPath, err := fs.dirFor(proxyHost, false) if err != nil { return nil, trace.Wrap(err) } _, err = ioutil.ReadDir(dirPath) if err != nil { return nil, trace.NotFound("no session keys for %v in %v", username, proxyHost) } certFile := filepath.Join(dirPath, username+fileExtCert) cert, err := ioutil.ReadFile(certFile) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } tlsCertFile := filepath.Join(dirPath, username+fileExtTLSCert) tlsCert, err := ioutil.ReadFile(tlsCertFile) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } pub, err := ioutil.ReadFile(filepath.Join(dirPath, username+fileExtPub)) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } priv, err := ioutil.ReadFile(filepath.Join(dirPath, username)) if err != nil { fs.log.Error(err) return nil, trace.Wrap(err) } key := &Key{Pub: pub, Priv: priv, Cert: cert, ProxyHost: proxyHost, TLSCert: tlsCert} // Validate the key loaded from disk. err = key.CheckCert() if err != nil { // KeyStore should return expired certificates as well if !utils.IsCertExpiredError(err) { return nil, trace.Wrap(err) } } sshCertExpiration, err := key.CertValidBefore() if err != nil { return nil, trace.Wrap(err) } tlsCertExpiration, err := key.TLSCertValidBefore() if err != nil { return nil, trace.Wrap(err) } // Note, we may be returning expired certificates here, that is okay. If the // certificates is expired, it's the responsibility of the TeleportClient to // perform cleanup of the certificates and the profile. fs.log.Debugf("Returning SSH certificate %q valid until %q, TLS certificate %q valid until %q.", certFile, sshCertExpiration, tlsCertFile, tlsCertExpiration) return key, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L266-L290
go
train
// SaveCerts saves trusted TLS certificates of certificate authorities
func (fs *FSLocalKeyStore) SaveCerts(proxy string, cas []auth.TrustedCerts) error
// SaveCerts saves trusted TLS certificates of certificate authorities func (fs *FSLocalKeyStore) SaveCerts(proxy string, cas []auth.TrustedCerts) error
{ dir, err := fs.dirFor(proxy, true) if err != nil { return trace.Wrap(err) } fp, err := os.OpenFile(filepath.Join(dir, fileNameTLSCerts), os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0640) if err != nil { return trace.Wrap(err) } defer fp.Sync() defer fp.Close() for _, ca := range cas { for _, cert := range ca.TLSCertificates { _, err := fp.Write(cert) if err != nil { return trace.ConvertSystemError(err) } _, err = fp.WriteString("\n") if err != nil { return trace.ConvertSystemError(err) } } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L293-L299
go
train
// GetCertsPEM returns trusted TLS certificates of certificate authorities PEM block
func (fs *FSLocalKeyStore) GetCertsPEM(proxy string) ([]byte, error)
// GetCertsPEM returns trusted TLS certificates of certificate authorities PEM block func (fs *FSLocalKeyStore) GetCertsPEM(proxy string) ([]byte, error)
{ dir, err := fs.dirFor(proxy, false) if err != nil { return nil, trace.Wrap(err) } return ioutil.ReadFile(filepath.Join(dir, fileNameTLSCerts)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L302-L331
go
train
// GetCerts returns trusted TLS certificates of certificate authorities
func (fs *FSLocalKeyStore) GetCerts(proxy string) (*x509.CertPool, error)
// GetCerts returns trusted TLS certificates of certificate authorities func (fs *FSLocalKeyStore) GetCerts(proxy string) (*x509.CertPool, error)
{ dir, err := fs.dirFor(proxy, false) if err != nil { return nil, trace.Wrap(err) } bytes, err := ioutil.ReadFile(filepath.Join(dir, fileNameTLSCerts)) if err != nil { return nil, trace.ConvertSystemError(err) } pool := x509.NewCertPool() for len(bytes) > 0 { var block *pem.Block block, bytes = pem.Decode(bytes) if block == nil { break } if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { fs.log.Debugf("Skipping PEM block type=%v headers=%v.", block.Type, block.Headers) continue } cert, err := x509.ParseCertificate(block.Bytes) if err != nil { return nil, trace.BadParameter("failed to parse certificate: %v", err) } fs.log.Debugf("Adding trusted cluster certificate authority %q to trusted pool.", cert.Issuer) pool.AddCert(cert) } return pool, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L334-L373
go
train
// AddKnownHostKeys adds a new entry to 'known_hosts' file
func (fs *FSLocalKeyStore) AddKnownHostKeys(hostname string, hostKeys []ssh.PublicKey) error
// AddKnownHostKeys adds a new entry to 'known_hosts' file func (fs *FSLocalKeyStore) AddKnownHostKeys(hostname string, hostKeys []ssh.PublicKey) error
{ fp, err := os.OpenFile(filepath.Join(fs.KeyDir, fileNameKnownHosts), os.O_CREATE|os.O_RDWR, 0640) if err != nil { return trace.Wrap(err) } defer fp.Sync() defer fp.Close() // read all existing entries into a map (this removes any pre-existing dupes) entries := make(map[string]int) output := make([]string, 0) scanner := bufio.NewScanner(fp) for scanner.Scan() { line := scanner.Text() if _, exists := entries[line]; !exists { output = append(output, line) entries[line] = 1 } } // add every host key to the list of entries for i := range hostKeys { fs.log.Debugf("Adding known host %s with key: %v", hostname, sshutils.Fingerprint(hostKeys[i])) bytes := ssh.MarshalAuthorizedKey(hostKeys[i]) line := strings.TrimSpace(fmt.Sprintf("%s %s", hostname, bytes)) if _, exists := entries[line]; !exists { output = append(output, line) } } // re-create the file: _, err = fp.Seek(0, 0) if err != nil { return trace.Wrap(err) } if err = fp.Truncate(0); err != nil { return trace.Wrap(err) } for _, line := range output { fmt.Fprintf(fp, "%s\n", line) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L376-L411
go
train
// GetKnownHostKeys returns all known public keys from 'known_hosts'
func (fs *FSLocalKeyStore) GetKnownHostKeys(hostname string) ([]ssh.PublicKey, error)
// GetKnownHostKeys returns all known public keys from 'known_hosts' func (fs *FSLocalKeyStore) GetKnownHostKeys(hostname string) ([]ssh.PublicKey, error)
{ bytes, err := ioutil.ReadFile(filepath.Join(fs.KeyDir, fileNameKnownHosts)) if err != nil { if os.IsNotExist(err) { return nil, nil } return nil, trace.Wrap(err) } var ( pubKey ssh.PublicKey retval []ssh.PublicKey = make([]ssh.PublicKey, 0) hosts []string hostMatch bool ) for err == nil { _, hosts, pubKey, _, bytes, err = ssh.ParseKnownHosts(bytes) if err == nil { hostMatch = (hostname == "") if !hostMatch { for i := range hosts { if hosts[i] == hostname { hostMatch = true break } } } if hostMatch { retval = append(retval, pubKey) } } } if err != io.EOF { return nil, trace.Wrap(err) } return retval, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L419-L430
go
train
// dirFor returns the path to the session keys for a given host. The value // for fs.KeyDir is typically "~/.tsh", sessionKeyDir is typically "keys", // and proxyHost typically has values like "proxy.example.com". // // If the create flag is true, the directory will be created if it does // not exist.
func (fs *FSLocalKeyStore) dirFor(proxyHost string, create bool) (string, error)
// dirFor returns the path to the session keys for a given host. The value // for fs.KeyDir is typically "~/.tsh", sessionKeyDir is typically "keys", // and proxyHost typically has values like "proxy.example.com". // // If the create flag is true, the directory will be created if it does // not exist. func (fs *FSLocalKeyStore) dirFor(proxyHost string, create bool) (string, error)
{ dirPath := filepath.Join(fs.KeyDir, sessionKeyDir, proxyHost) if create { if err := os.MkdirAll(dirPath, profileDirPerms); err != nil { fs.log.Error(err) return "", trace.ConvertSystemError(err) } } return dirPath, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/keystore.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/keystore.go#L433-L459
go
train
// initKeysDir initializes the keystore root directory. Usually it is ~/.tsh
func initKeysDir(dirPath string) (string, error)
// initKeysDir initializes the keystore root directory. Usually it is ~/.tsh func initKeysDir(dirPath string) (string, error)
{ var err error // not specified? use `~/.tsh` if dirPath == "" { u, err := user.Current() if err != nil { dirPath = os.TempDir() } else { dirPath = u.HomeDir } dirPath = filepath.Join(dirPath, defaultKeyDir) } // create if doesn't exist: _, err = os.Stat(dirPath) if err != nil { if os.IsNotExist(err) { err = os.MkdirAll(dirPath, os.ModeDir|profileDirPerms) if err != nil { return "", trace.ConvertSystemError(err) } } else { return "", trace.Wrap(err) } } return dirPath, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/node_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/node_command.go#L57-L72
go
train
// Initialize allows NodeCommand to plug itself into the CLI parser
func (c *NodeCommand) Initialize(app *kingpin.Application, config *service.Config)
// Initialize allows NodeCommand to plug itself into the CLI parser func (c *NodeCommand) Initialize(app *kingpin.Application, config *service.Config)
{ c.config = config // add node command nodes := app.Command("nodes", "Issue invites for other nodes to join the cluster") c.nodeAdd = nodes.Command("add", "Generate a node invitation token") c.nodeAdd.Flag("roles", "Comma-separated list of roles for the new node to assume [node]").Default("node").StringVar(&c.roles) c.nodeAdd.Flag("ttl", "Time to live for a generated token").Default(defaults.ProvisioningTokenTTL.String()).DurationVar(&c.ttl) c.nodeAdd.Flag("token", "Custom token to use, autogenerated if not provided").StringVar(&c.token) c.nodeAdd.Flag("format", "Output format, 'text' or 'json'").Hidden().Default("text").StringVar(&c.format) c.nodeAdd.Alias(AddNodeHelp) c.nodeList = nodes.Command("ls", "List all active SSH nodes within the cluster") c.nodeList.Flag("namespace", "Namespace of the nodes").Default(defaults.Namespace).StringVar(&c.namespace) c.nodeList.Alias(ListNodesHelp) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/node_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/node_command.go#L75-L86
go
train
// TryRun takes the CLI command as an argument (like "nodes ls") and executes it.
func (c *NodeCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
// TryRun takes the CLI command as an argument (like "nodes ls") and executes it. func (c *NodeCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error)
{ switch cmd { case c.nodeAdd.FullCommand(): err = c.Invite(client) case c.nodeList.FullCommand(): err = c.ListActive(client) default: return false, nil } return true, trace.Wrap(err) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/node_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/node_command.go#L113-L166
go
train
// Invite generates a token which can be used to add another SSH node // to a cluster
func (c *NodeCommand) Invite(client auth.ClientI) error
// Invite generates a token which can be used to add another SSH node // to a cluster func (c *NodeCommand) Invite(client auth.ClientI) error
{ // parse --roles flag roles, err := teleport.ParseRoles(c.roles) if err != nil { return trace.Wrap(err) } token, err := client.GenerateToken(auth.GenerateTokenRequest{Roles: roles, TTL: c.ttl, Token: c.token}) if err != nil { return trace.Wrap(err) } // Calculate the CA pin for this cluster. The CA pin is used by the client // to verify the identity of the Auth Server. caPin, err := calculateCAPin(client) if err != nil { return trace.Wrap(err) } authServers, err := client.GetAuthServers() if err != nil { return trace.Wrap(err) } if len(authServers) == 0 { return trace.Errorf("This cluster does not have any auth servers running.") } // output format swtich: if c.format == "text" { if roles.Include(teleport.RoleTrustedCluster) || roles.Include(teleport.LegacyClusterTokenType) { fmt.Printf(trustedClusterMessage, token, int(c.ttl.Minutes())) } else { fmt.Printf(nodeMessage, token, int(c.ttl.Minutes()), strings.ToLower(roles.String()), token, caPin, authServers[0].GetAddr(), int(c.ttl.Minutes()), authServers[0].GetAddr(), ) } } else { // Always return a list, otherwise we'll break users tooling. See #1846 for // more details. tokens := []string{token} out, err := json.Marshal(tokens) if err != nil { return trace.Wrap(err, "failed to marshal token") } fmt.Printf(string(out)) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
tool/tctl/common/node_command.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/node_command.go#L170-L178
go
train
// ListActive retreives the list of nodes who recently sent heartbeats to // to a cluster and prints it to stdout
func (c *NodeCommand) ListActive(client auth.ClientI) error
// ListActive retreives the list of nodes who recently sent heartbeats to // to a cluster and prints it to stdout func (c *NodeCommand) ListActive(client auth.ClientI) error
{ nodes, err := client.GetNodes(c.namespace, services.SkipValidation()) if err != nil { return trace.Wrap(err) } coll := &serverCollection{servers: nodes} coll.writeText(os.Stdout) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/websocketwriter.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/websocketwriter.go#L75-L90
go
train
// Write implements io.WriteCloser for WebSockWriter (that's the reason we're // wrapping the websocket) // // It replaces raw Write() with "Message.Send()"
func (w *WebSockWrapper) Write(data []byte) (n int, err error)
// Write implements io.WriteCloser for WebSockWriter (that's the reason we're // wrapping the websocket) // // It replaces raw Write() with "Message.Send()" func (w *WebSockWrapper) Write(data []byte) (n int, err error)
{ n = len(data) if w.mode == WebSocketBinaryMode { // binary send: err = websocket.Message.Send(w.ws, data) // text send: } else { var utf8 string utf8, err = w.encoder.String(string(data)) err = websocket.Message.Send(w.ws, utf8) } if err != nil { n = 0 } return n, err }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/websocketwriter.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/websocketwriter.go#L95-L119
go
train
// Read does the opposite of write: it replaces websocket's raw "Read" with // // It replaces raw Read() with "Message.Receive()"
func (w *WebSockWrapper) Read(out []byte) (n int, err error)
// Read does the opposite of write: it replaces websocket's raw "Read" with // // It replaces raw Read() with "Message.Receive()" func (w *WebSockWrapper) Read(out []byte) (n int, err error)
{ var data []byte if w.mode == WebSocketBinaryMode { err = websocket.Message.Receive(w.ws, &data) } else { var utf8 string err = websocket.Message.Receive(w.ws, &utf8) switch err { case nil: data, err = w.decoder.Bytes([]byte(utf8)) case io.EOF: return 0, io.EOF default: log.Error(err) } } if err != nil { return 0, trace.Wrap(err) } if len(out) < len(data) { log.Warningf("websocket failed to receive everything: %d vs %d", len(out), len(data)) } return copy(out, data), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/client/hotp_mock.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/client/hotp_mock.go#L73-L87
go
train
// GetTokenFromHOTPMockFile opens HOTPMock from file, gets token value, // increases hotp and saves it to the file. Returns hotp token value.
func GetTokenFromHOTPMockFile(path string) (token string, e error)
// GetTokenFromHOTPMockFile opens HOTPMock from file, gets token value, // increases hotp and saves it to the file. Returns hotp token value. func GetTokenFromHOTPMockFile(path string) (token string, e error)
{ otp, err := LoadHOTPMockFromFile(path) if err != nil { return "", trace.Wrap(err) } token = otp.OTP() err = otp.SaveToFile(path) if err != nil { return "", trace.Wrap(err) } return token, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/proxy/noproxy.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/proxy/noproxy.go#L22-L70
go
train
// useProxy reports whether requests to addr should use a proxy, // according to the NO_PROXY or no_proxy environment variable. // addr is always a canonicalAddr with a host and port.
func useProxy(addr string) bool
// useProxy reports whether requests to addr should use a proxy, // according to the NO_PROXY or no_proxy environment variable. // addr is always a canonicalAddr with a host and port. func useProxy(addr string) bool
{ if len(addr) == 0 { return true } var noProxy string for _, env := range []string{teleport.NoProxy, strings.ToLower(teleport.NoProxy)} { noProxy = os.Getenv(env) if noProxy != "" { break } } if noProxy == "" { return true } if noProxy == "*" { return false } addr = strings.ToLower(strings.TrimSpace(addr)) if hasPort(addr) { addr = addr[:strings.LastIndex(addr, ":")] } for _, p := range strings.Split(noProxy, ",") { p = strings.ToLower(strings.TrimSpace(p)) if len(p) == 0 { continue } if hasPort(p) { p = p[:strings.LastIndex(p, ":")] } if addr == p { return false } if len(p) == 0 { // There is no host part, likely the entry is malformed; ignore. continue } if p[0] == '.' && (strings.HasSuffix(addr, p) || addr == p[1:]) { // no_proxy ".foo.com" matches "bar.foo.com" or "foo.com" return false } if p[0] != '.' && strings.HasSuffix(addr, p) && addr[len(addr)-len(p)-1] == '.' { // no_proxy "foo.com" matches "bar.foo.com" return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L42-L116
go
train
// setupCollections returns a mapping of collections
func setupCollections(c *Cache, watches []services.WatchKind) (map[string]collection, error)
// setupCollections returns a mapping of collections func setupCollections(c *Cache, watches []services.WatchKind) (map[string]collection, error)
{ collections := make(map[string]collection, len(watches)) for _, watch := range watches { switch watch.Kind { case services.KindCertAuthority: if c.Trust == nil { return nil, trace.BadParameter("missing parameter Trust") } collections[watch.Kind] = &certAuthority{watch: watch, Cache: c} case services.KindStaticTokens: if c.ClusterConfig == nil { return nil, trace.BadParameter("missing parameter ClusterConfig") } collections[watch.Kind] = &staticTokens{watch: watch, Cache: c} case services.KindToken: if c.Provisioner == nil { return nil, trace.BadParameter("missing parameter Provisioner") } collections[watch.Kind] = &provisionToken{watch: watch, Cache: c} case services.KindClusterName: if c.ClusterConfig == nil { return nil, trace.BadParameter("missing parameter ClusterConfig") } collections[watch.Kind] = &clusterName{watch: watch, Cache: c} case services.KindClusterConfig: if c.ClusterConfig == nil { return nil, trace.BadParameter("missing parameter ClusterConfig") } collections[watch.Kind] = &clusterConfig{watch: watch, Cache: c} case services.KindUser: if c.Users == nil { return nil, trace.BadParameter("missing parameter Users") } collections[watch.Kind] = &user{watch: watch, Cache: c} case services.KindRole: if c.Access == nil { return nil, trace.BadParameter("missing parameter Access") } collections[watch.Kind] = &role{watch: watch, Cache: c} case services.KindNamespace: if c.Presence == nil { return nil, trace.BadParameter("missing parameter Presence") } collections[watch.Kind] = &namespace{watch: watch, Cache: c} case services.KindNode: if c.Presence == nil { return nil, trace.BadParameter("missing parameter Presence") } collections[watch.Kind] = &node{watch: watch, Cache: c} case services.KindProxy: if c.Presence == nil { return nil, trace.BadParameter("missing parameter Presence") } collections[watch.Kind] = &proxy{watch: watch, Cache: c} case services.KindAuthServer: if c.Presence == nil { return nil, trace.BadParameter("missing parameter Presence") } collections[watch.Kind] = &authServer{watch: watch, Cache: c} case services.KindReverseTunnel: if c.Presence == nil { return nil, trace.BadParameter("missing parameter Presence") } collections[watch.Kind] = &reverseTunnel{watch: watch, Cache: c} case services.KindTunnelConnection: if c.Presence == nil { return nil, trace.BadParameter("missing parameter Presence") } collections[watch.Kind] = &tunnelConnection{watch: watch, Cache: c} default: return nil, trace.BadParameter("resource %q is not supported", watch.Kind) } } return collections, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L124-L131
go
train
// erase erases all data in the collection
func (c *tunnelConnection) erase() error
// erase erases all data in the collection func (c *tunnelConnection) erase() error
{ if err := c.presenceCache.DeleteAllTunnelConnections(); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L187-L194
go
train
// erase erases all data in the collection
func (c *reverseTunnel) erase() error
// erase erases all data in the collection func (c *reverseTunnel) erase() error
{ if err := c.presenceCache.DeleteAllReverseTunnels(); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L251-L258
go
train
// erase erases all data in the collection
func (c *proxy) erase() error
// erase erases all data in the collection func (c *proxy) erase() error
{ if err := c.presenceCache.DeleteAllProxies(); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L317-L324
go
train
// erase erases all data in the collection
func (c *authServer) erase() error
// erase erases all data in the collection func (c *authServer) erase() error
{ if err := c.presenceCache.DeleteAllAuthServers(); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L383-L390
go
train
// erase erases all data in the collection
func (c *node) erase() error
// erase erases all data in the collection func (c *node) erase() error
{ if err := c.presenceCache.DeleteAllNodes(defaults.Namespace); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L447-L454
go
train
// erase erases all data in the collection
func (c *namespace) erase() error
// erase erases all data in the collection func (c *namespace) erase() error
{ if err := c.presenceCache.DeleteAllNamespaces(); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L511-L523
go
train
// erase erases all data in the collection
func (c *certAuthority) erase() error
// erase erases all data in the collection func (c *certAuthority) erase() error
{ if err := c.trustCache.DeleteAllCertAuthorities(services.UserCA); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } if err := c.trustCache.DeleteAllCertAuthorities(services.HostCA); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L595-L603
go
train
// erase erases all data in the collection
func (c *staticTokens) erase() error
// erase erases all data in the collection func (c *staticTokens) erase() error
{ err := c.clusterConfigCache.DeleteStaticTokens() if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L662-L669
go
train
// erase erases all data in the collection
func (c *provisionToken) erase() error
// erase erases all data in the collection func (c *provisionToken) erase() error
{ if err := c.provisionerCache.DeleteAllTokens(); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L726-L734
go
train
// erase erases all data in the collection
func (c *clusterConfig) erase() error
// erase erases all data in the collection func (c *clusterConfig) erase() error
{ err := c.clusterConfigCache.DeleteClusterConfig() if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L794-L802
go
train
// erase erases all data in the collection
func (c *clusterName) erase() error
// erase erases all data in the collection func (c *clusterName) erase() error
{ err := c.clusterConfigCache.DeleteClusterName() if err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L862-L869
go
train
// erase erases all data in the collection
func (c *user) erase() error
// erase erases all data in the collection func (c *user) erase() error
{ if err := c.usersCache.DeleteAllUsers(); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/cache/collections.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/cache/collections.go#L927-L934
go
train
// erase erases all data in the collection
func (c *role) erase() error
// erase erases all data in the collection func (c *role) erase() error
{ if err := c.accessCache.DeleteAllRoles(); err != nil { if !trace.IsNotFound(err) { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/agentconn/agent_windows.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/agentconn/agent_windows.go#L34-L41
go
train
// Dial creates net.Conn to a SSH agent listening on a Windows named pipe. // This is behind a build flag because winio.DialPipe is only available on // Windows.
func Dial(socket string) (net.Conn, error)
// Dial creates net.Conn to a SSH agent listening on a Windows named pipe. // This is behind a build flag because winio.DialPipe is only available on // Windows. func Dial(socket string) (net.Conn, error)
{ conn, err := winio.DialPipe(defaults.WindowsOpenSSHNamedPipe, nil) if err != nil { return nil, trace.Wrap(err) } return conn, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpclog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L54-L58
go
train
// Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println.
func (g *GLogger) Infoln(args ...interface{})
// Infoln logs to INFO log. Arguments are handled in the manner of fmt.Println. func (g *GLogger) Infoln(args ...interface{})
{ // GRPC is very verbose, so this is intentionally // pushes info level statements as Teleport's debug level ones g.Entry.Debug(fmt.Sprintln(args...)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpclog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L61-L65
go
train
// Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf.
func (g *GLogger) Infof(format string, args ...interface{})
// Infof logs to INFO log. Arguments are handled in the manner of fmt.Printf. func (g *GLogger) Infof(format string, args ...interface{})
{ // GRPC is very verbose, so this is intentionally // pushes info level statements as Teleport's debug level ones g.Entry.Debugf(format, args...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpclog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L73-L75
go
train
// Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println.
func (g *GLogger) Warningln(args ...interface{})
// Warningln logs to WARNING log. Arguments are handled in the manner of fmt.Println. func (g *GLogger) Warningln(args ...interface{})
{ g.Entry.Warning(fmt.Sprintln(args...)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpclog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L78-L80
go
train
// Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf.
func (g *GLogger) Warningf(format string, args ...interface{})
// Warningf logs to WARNING log. Arguments are handled in the manner of fmt.Printf. func (g *GLogger) Warningf(format string, args ...interface{})
{ g.Entry.Warningf(format, args...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpclog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L88-L90
go
train
// Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println.
func (g *GLogger) Errorln(args ...interface{})
// Errorln logs to ERROR log. Arguments are handled in the manner of fmt.Println. func (g *GLogger) Errorln(args ...interface{})
{ g.Entry.Error(fmt.Sprintln(args...)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpclog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L109-L113
go
train
// Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println. // gRPC ensures that all Fatal logs will exit with os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code.
func (g *GLogger) Fatalln(args ...interface{})
// Fatalln logs to ERROR log. Arguments are handled in the manner of fmt.Println. // gRPC ensures that all Fatal logs will exit with os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code. func (g *GLogger) Fatalln(args ...interface{})
{ // Teleport can be used as a library, prevent GRPC // from crashing the process g.Entry.Error(fmt.Sprintln(args...)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/grpclog.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/grpclog.go#L118-L122
go
train
// Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. // gRPC ensures that all Fatal logs will exit with os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code.
func (g *GLogger) Fatalf(format string, args ...interface{})
// Fatalf logs to ERROR log. Arguments are handled in the manner of fmt.Printf. // gRPC ensures that all Fatal logs will exit with os.Exit(1). // Implementations may also call os.Exit() with a non-zero exit code. func (g *GLogger) Fatalf(format string, args ...interface{})
{ // Teleport can be used as a library, prevent GRPC // from crashing the process g.Entry.Errorf(format, args...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/marshal.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/marshal.go#L34-L41
go
train
// MarshalAuthorizedKeysFormat returns the certificate authority public key exported as a single // line that can be placed in ~/.ssh/authorized_keys file. The format adheres to the // man sshd (8) authorized_keys format, a space-separated list of: options, keytype, // base64-encoded key, comment. // For example: // // cert-authority AAA... type=user&clustername=cluster-a // // URL encoding is used to pass the CA type and cluster name into the comment field.
func MarshalAuthorizedKeysFormat(clusterName string, keyBytes []byte) (string, error)
// MarshalAuthorizedKeysFormat returns the certificate authority public key exported as a single // line that can be placed in ~/.ssh/authorized_keys file. The format adheres to the // man sshd (8) authorized_keys format, a space-separated list of: options, keytype, // base64-encoded key, comment. // For example: // // cert-authority AAA... type=user&clustername=cluster-a // // URL encoding is used to pass the CA type and cluster name into the comment field. func MarshalAuthorizedKeysFormat(clusterName string, keyBytes []byte) (string, error)
{ comment := url.Values{ "type": []string{"user"}, "clustername": []string{clusterName}, } return fmt.Sprintf("cert-authority %s %s", strings.TrimSpace(string(keyBytes)), comment.Encode()), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/socks/socks.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L49-L87
go
train
// Handshake performs a SOCKS5 handshake with the client and returns // the remote address to proxy the connection to.
func Handshake(conn net.Conn) (string, error)
// Handshake performs a SOCKS5 handshake with the client and returns // the remote address to proxy the connection to. func Handshake(conn net.Conn) (string, error)
{ // Read in the version and reject anything other than SOCKS5. version, err := readByte(conn) if err != nil { return "", trace.Wrap(err) } if version != socks5Version { return "", trace.BadParameter("only SOCKS5 is supported") } // Read in the authentication method requested by the client and write back // the method that was selected. At the moment only "no authentication // required" is supported. authMethods, err := readAuthenticationMethod(conn) if err != nil { return "", trace.Wrap(err) } if !byteSliceContains(authMethods, socks5AuthNotRequired) { return "", trace.BadParameter("only 'no authentication required' is supported") } err = writeMethodSelection(conn) if err != nil { return "", trace.Wrap(err) } // Read in the request from the client and make sure the requested command // is supported and extract the remote address. If everything is good, write // out a success response. remoteAddr, err := readRequest(conn) if err != nil { return "", trace.Wrap(err) } err = writeReply(conn) if err != nil { return "", trace.Wrap(err) } return remoteAddr, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/socks/socks.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L91-L111
go
train
// readAuthenticationMethod reads in the authentication methods the client // supports.
func readAuthenticationMethod(conn net.Conn) ([]byte, error)
// readAuthenticationMethod reads in the authentication methods the client // supports. func readAuthenticationMethod(conn net.Conn) ([]byte, error)
{ // Read in the number of authentication methods supported. nmethods, err := readByte(conn) if err != nil { return nil, trace.Wrap(err) } // Read nmethods number of bytes from the connection return the list of // supported authentication methods to the caller. authMethods := make([]byte, nmethods) for i := byte(0); i < nmethods; i++ { method, err := readByte(conn) if err != nil { return nil, trace.Wrap(err) } authMethods = append(authMethods, method) } return authMethods, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/socks/socks.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L115-L127
go
train
// writeMethodSelection writes out the response to the authentication methods. // Right now, only SOCKS5 and "no authentication methods" is supported.
func writeMethodSelection(conn net.Conn) error
// writeMethodSelection writes out the response to the authentication methods. // Right now, only SOCKS5 and "no authentication methods" is supported. func writeMethodSelection(conn net.Conn) error
{ message := []byte{socks5Version, socks5AuthNotRequired} n, err := conn.Write(message) if err != nil { return trace.Wrap(err) } if n != len(message) { return trace.BadParameter("wrote: %v wanted to write: %v", n, len(message)) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/socks/socks.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L131-L178
go
train
// readRequest reads in the SOCKS5 request from the client and returns the // host:port the client wants to connect to.
func readRequest(conn net.Conn) (string, error)
// readRequest reads in the SOCKS5 request from the client and returns the // host:port the client wants to connect to. func readRequest(conn net.Conn) (string, error)
{ // Read in the version and reject anything other than SOCKS5. version, err := readByte(conn) if err != nil { return "", trace.Wrap(err) } if version != socks5Version { return "", trace.BadParameter("only SOCKS5 is supported") } // Read in the command the client is requesting. Only CONNECT is supported. command, err := readByte(conn) if err != nil { return "", trace.Wrap(err) } if command != socks5CommandConnect { return "", trace.BadParameter("only CONNECT command is supported") } // Read in and throw away the reserved byte. _, err = readByte(conn) if err != nil { return "", trace.Wrap(err) } // Read in the address type and determine how many more bytes need to be // read in to read in the remote host address. addrLen, err := readAddrType(conn) if err != nil { return "", trace.Wrap(err) } // Read in the destination address. destAddr := make([]byte, addrLen) _, err = io.ReadFull(conn, destAddr) if err != nil { return "", trace.Wrap(err) } // Read in the destination port. var destPort uint16 err = binary.Read(conn, binary.BigEndian, &destPort) if err != nil { return "", trace.Wrap(err) } return net.JoinHostPort(string(destAddr), strconv.Itoa(int(destPort))), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/socks/socks.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L182-L206
go
train
// readAddrType reads in the address type and returns the length of the dest // addr field.
func readAddrType(conn net.Conn) (int, error)
// readAddrType reads in the address type and returns the length of the dest // addr field. func readAddrType(conn net.Conn) (int, error)
{ // Read in the type of the remote host. addrType, err := readByte(conn) if err != nil { return 0, trace.Wrap(err) } // Based off the type, determine how many more bytes to read in for the // remote address. For IPv4 it's 4 bytes, for IPv6 it's 16, and for domain // names read in another byte to determine the length of the field. switch addrType { case socks5AddressTypeIPv4: return net.IPv4len, nil case socks5AddressTypeIPv6: return net.IPv6len, nil case socks5AddressTypeDomainName: len, err := readByte(conn) if err != nil { return 0, trace.Wrap(err) } return int(len), nil default: return 0, trace.BadParameter("unsupported address type: %v", addrType) } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/socks/socks.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L209-L238
go
train
// Write the response to the client.
func writeReply(conn net.Conn) error
// Write the response to the client. func writeReply(conn net.Conn) error
{ // Write success reply, similar to OpenSSH only success is written. // https://github.com/openssh/openssh-portable/blob/5d14019/channels.c#L1442-L1452 message := []byte{ socks5Version, socks5Succeeded, socks5Reserved, socks5AddressTypeIPv4, } n, err := conn.Write(message) if err != nil { return trace.Wrap(err) } if n != len(message) { return trace.BadParameter("wrote: %v wanted to write: %v", n, len(message)) } // Reply also requires BND.ADDR and BDN.PORT even though they are ignored // because Teleport only supports CONNECT. message = []byte{0, 0, 0, 0, 0, 0} n, err = conn.Write(message) if err != nil { return trace.Wrap(err) } if n != len(message) { return trace.BadParameter("wrote: %v wanted to write: %v", n, len(message)) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/socks/socks.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L241-L249
go
train
// readByte a single byte from the passed in net.Conn.
func readByte(conn net.Conn) (byte, error)
// readByte a single byte from the passed in net.Conn. func readByte(conn net.Conn) (byte, error)
{ b := make([]byte, 1) _, err := io.ReadFull(conn, b) if err != nil { return 0, trace.Wrap(err) } return b[0], nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/utils/socks/socks.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/socks/socks.go#L252-L260
go
train
// byteSliceContains checks if the slice a contains the byte b.
func byteSliceContains(a []byte, b byte) bool
// byteSliceContains checks if the slice a contains the byte b. func byteSliceContains(a []byte, b byte) bool
{ for _, v := range a { if v == b { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/shell/shell.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/shell/shell.go#L30-L44
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)
{ var err error var shellcmd string shellcmd, err = getLoginShell(username) if err != nil { if !trace.IsNotFound(err) { logrus.Warnf("No shell specified for %v, using default %v.", username, DefaultShell) return DefaultShell, nil } return "", trace.Wrap(err) } return shellcmd, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L157-L228
go
train
// NewInstance creates a new Teleport process instance
func NewInstance(cfg InstanceConfig) *TeleInstance
// NewInstance creates a new Teleport process instance func NewInstance(cfg InstanceConfig) *TeleInstance
{ var err error if len(cfg.Ports) < 5 { fatalIf(fmt.Errorf("not enough free ports given: %v", cfg.Ports)) } if cfg.NodeName == "" { cfg.NodeName, err = os.Hostname() fatalIf(err) } // generate instance secrets (keys): keygen, err := native.New(context.TODO(), native.PrecomputeKeys(0)) fatalIf(err) if cfg.Priv == nil || cfg.Pub == nil { cfg.Priv, cfg.Pub, _ = keygen.GenerateKeyPair("") } rsaKey, err := ssh.ParseRawPrivateKey(cfg.Priv) fatalIf(err) tlsCAKey, tlsCACert, err := tlsca.GenerateSelfSignedCAWithPrivateKey(rsaKey.(*rsa.PrivateKey), pkix.Name{ CommonName: cfg.ClusterName, Organization: []string{cfg.ClusterName}, }, nil, defaults.CATTL) fatalIf(err) cert, err := keygen.GenerateHostCert(services.HostCertParams{ PrivateCASigningKey: cfg.Priv, PublicHostKey: cfg.Pub, HostID: cfg.HostID, NodeName: cfg.NodeName, ClusterName: cfg.ClusterName, Roles: teleport.Roles{teleport.RoleAdmin}, TTL: time.Duration(time.Hour * 24), }) fatalIf(err) tlsCA, err := tlsca.New(tlsCACert, tlsCAKey) fatalIf(err) cryptoPubKey, err := sshutils.CryptoPublicKey(cfg.Pub) identity := tlsca.Identity{ Username: fmt.Sprintf("%v.%v", cfg.HostID, cfg.ClusterName), Groups: []string{string(teleport.RoleAdmin)}, } clock := clockwork.NewRealClock() tlsCert, err := tlsCA.GenerateCertificate(tlsca.CertificateRequest{ Clock: clock, PublicKey: cryptoPubKey, Subject: identity.Subject(), NotAfter: clock.Now().UTC().Add(time.Hour * 24), }) fatalIf(err) i := &TeleInstance{ Ports: cfg.Ports, Hostname: cfg.NodeName, UploadEventsC: make(chan *events.UploadEvent, 100), } secrets := InstanceSecrets{ SiteName: cfg.ClusterName, PrivKey: cfg.Priv, PubKey: cfg.Pub, Cert: cert, TLSCACert: tlsCACert, TLSCert: tlsCert, ListenAddr: net.JoinHostPort(cfg.NodeName, i.GetPortReverseTunnel()), WebProxyAddr: net.JoinHostPort(cfg.NodeName, i.GetPortWeb()), Users: make(map[string]*User), } if cfg.MultiplexProxy { secrets.ListenAddr = secrets.WebProxyAddr } i.Secrets = secrets return i }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L231-L242
go
train
// GetRoles returns a list of roles to initiate for this secret
func (s *InstanceSecrets) GetRoles() []services.Role
// GetRoles returns a list of roles to initiate for this secret func (s *InstanceSecrets) GetRoles() []services.Role
{ var roles []services.Role for _, ca := range s.GetCAs() { if ca.GetType() != services.UserCA { continue } role := services.RoleForCertAuthority(ca) role.SetLogins(services.Allow, s.AllowedLogins()) roles = append(roles, role) } return roles }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L247-L254
go
train
// GetCAs return an array of CAs stored by the secrets object. In i // case we always return hard-coded userCA + hostCA (and they share keys // for simplicity)
func (s *InstanceSecrets) GetCAs() []services.CertAuthority
// GetCAs return an array of CAs stored by the secrets object. In i // case we always return hard-coded userCA + hostCA (and they share keys // for simplicity) func (s *InstanceSecrets) GetCAs() []services.CertAuthority
{ hostCA := services.NewCertAuthority(services.HostCA, s.SiteName, [][]byte{s.PrivKey}, [][]byte{s.PubKey}, []string{}) hostCA.SetTLSKeyPairs([]services.TLSKeyPair{{Cert: s.TLSCACert, Key: s.PrivKey}}) return []services.CertAuthority{ hostCA, services.NewCertAuthority(services.UserCA, s.SiteName, [][]byte{s.PrivKey}, [][]byte{s.PubKey}, []string{services.RoleNameForCertAuthority(s.SiteName)}), } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L323-L335
go
train
// GetSiteAPI() is a helper which returns an API endpoint to a site with // a given name. i endpoint implements HTTP-over-SSH access to the // site's auth server.
func (i *TeleInstance) GetSiteAPI(siteName string) auth.ClientI
// GetSiteAPI() is a helper which returns an API endpoint to a site with // a given name. i endpoint implements HTTP-over-SSH access to the // site's auth server. func (i *TeleInstance) GetSiteAPI(siteName string) auth.ClientI
{ siteTunnel, err := i.Tunnel.GetSite(siteName) if err != nil { log.Warn(err) return nil } siteAPI, err := siteTunnel.GetClient() if err != nil { log.Warn(err) return nil } return siteAPI }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L339-L346
go
train
// Create creates a new instance of Teleport which trusts a lsit of other clusters (other // instances)
func (i *TeleInstance) Create(trustedSecrets []*InstanceSecrets, enableSSH bool, console io.Writer) error
// Create creates a new instance of Teleport which trusts a lsit of other clusters (other // instances) func (i *TeleInstance) Create(trustedSecrets []*InstanceSecrets, enableSSH bool, console io.Writer) error
{ tconf := service.MakeDefaultConfig() tconf.SSH.Enabled = enableSSH tconf.Console = console tconf.Proxy.DisableWebService = true tconf.Proxy.DisableWebInterface = true return i.CreateEx(trustedSecrets, tconf) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L357-L367
go
train
// SetupUserCreds sets up user credentials for client
func SetupUserCreds(tc *client.TeleportClient, proxyHost string, creds UserCreds) error
// SetupUserCreds sets up user credentials for client func SetupUserCreds(tc *client.TeleportClient, proxyHost string, creds UserCreds) error
{ _, err := tc.AddKey(proxyHost, &creds.Key) if err != nil { return trace.Wrap(err) } err = tc.AddTrustedCA(creds.HostCA) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L370-L405
go
train
// SetupUser sets up user in the cluster
func SetupUser(process *service.TeleportProcess, username string, roles []services.Role) error
// SetupUser sets up user in the cluster func SetupUser(process *service.TeleportProcess, username string, roles []services.Role) error
{ auth := process.GetAuthServer() teleUser, err := services.NewUser(username) if err != nil { return trace.Wrap(err) } if len(roles) == 0 { role := services.RoleForUser(teleUser) role.SetLogins(services.Allow, []string{username}) // allow tests to forward agent, still needs to be passed in client roleOptions := role.GetOptions() roleOptions.ForwardAgent = services.NewBool(true) role.SetOptions(roleOptions) err = auth.UpsertRole(role) if err != nil { return trace.Wrap(err) } teleUser.AddRole(role.GetMetadata().Name) roles = append(roles, role) } else { for _, role := range roles { err := auth.UpsertRole(role) if err != nil { return trace.Wrap(err) } teleUser.AddRole(role.GetName()) } } err = auth.UpsertUser(teleUser) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L408-L438
go
train
// GenerateUserCreds generates key to be used by client
func GenerateUserCreds(process *service.TeleportProcess, username string) (*UserCreds, error)
// GenerateUserCreds generates key to be used by client func GenerateUserCreds(process *service.TeleportProcess, username string) (*UserCreds, error)
{ priv, pub, err := testauthority.New().GenerateKeyPair("") if err != nil { return nil, trace.Wrap(err) } a := process.GetAuthServer() sshCert, x509Cert, err := a.GenerateUserCerts(pub, username, time.Hour, teleport.CertificateFormatStandard) if err != nil { return nil, trace.Wrap(err) } clusterName, err := a.GetClusterName() if err != nil { return nil, trace.Wrap(err) } ca, err := a.GetCertAuthority(services.CertAuthID{ Type: services.HostCA, DomainName: clusterName.GetClusterName(), }, false) if err != nil { return nil, trace.Wrap(err) } return &UserCreds{ HostCA: ca, Key: client.Key{ Priv: priv, Pub: pub, Cert: sshCert, TLSCert: x509Cert, }, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L441-L521
go
train
// GenerateConfig generates instance config
func (i *TeleInstance) GenerateConfig(trustedSecrets []*InstanceSecrets, tconf *service.Config) (*service.Config, error)
// GenerateConfig generates instance config func (i *TeleInstance) GenerateConfig(trustedSecrets []*InstanceSecrets, tconf *service.Config) (*service.Config, error)
{ var err error dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName) if err != nil { return nil, trace.Wrap(err) } if tconf == nil { tconf = service.MakeDefaultConfig() } tconf.DataDir = dataDir tconf.UploadEventsC = i.UploadEventsC tconf.CachePolicy.Enabled = true tconf.Auth.ClusterName, err = services.NewClusterName(services.ClusterNameSpecV2{ ClusterName: i.Secrets.SiteName, }) if err != nil { return nil, trace.Wrap(err) } tconf.Auth.StaticTokens, err = services.NewStaticTokens(services.StaticTokensSpecV2{ StaticTokens: []services.ProvisionTokenV1{ { Roles: []teleport.Role{teleport.RoleNode, teleport.RoleProxy, teleport.RoleTrustedCluster}, Token: "token", }, }, }) if err != nil { return nil, trace.Wrap(err) } tconf.Auth.Authorities = append(tconf.Auth.Authorities, i.Secrets.GetCAs()...) tconf.Identities = append(tconf.Identities, i.Secrets.GetIdentity()) for _, trusted := range trustedSecrets { tconf.Auth.Authorities = append(tconf.Auth.Authorities, trusted.GetCAs()...) tconf.Auth.Roles = append(tconf.Auth.Roles, trusted.GetRoles()...) tconf.Identities = append(tconf.Identities, trusted.GetIdentity()) if trusted.ListenAddr != "" { tconf.ReverseTunnels = []services.ReverseTunnel{ services.NewReverseTunnel(trusted.SiteName, []string{trusted.ListenAddr}), } } } tconf.Proxy.ReverseTunnelListenAddr.Addr = i.Secrets.ListenAddr tconf.HostUUID = i.Secrets.GetIdentity().ID.HostUUID tconf.SSH.Addr.Addr = net.JoinHostPort(i.Hostname, i.GetPortSSH()) tconf.SSH.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } tconf.Auth.SSHAddr.Addr = net.JoinHostPort(i.Hostname, i.GetPortAuth()) tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, i.GetPortProxy()) tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, i.GetPortWeb()) tconf.Proxy.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: i.Hostname, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } tconf.AuthServers = append(tconf.AuthServers, tconf.Auth.SSHAddr) tconf.Auth.StorageConfig = backend.Config{ Type: lite.GetName(), Params: backend.Params{"path": dataDir + string(os.PathListSeparator) + defaults.BackendDir, "poll_stream_period": 50 * time.Millisecond}, } tconf.Keygen = testauthority.New() i.Config = tconf return tconf, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L528-L600
go
train
// CreateEx creates a new instance of Teleport which trusts a list of other clusters (other // instances) // // Unlike Create() it allows for greater customization because it accepts // a full Teleport config structure
func (i *TeleInstance) CreateEx(trustedSecrets []*InstanceSecrets, tconf *service.Config) error
// CreateEx creates a new instance of Teleport which trusts a list of other clusters (other // instances) // // Unlike Create() it allows for greater customization because it accepts // a full Teleport config structure func (i *TeleInstance) CreateEx(trustedSecrets []*InstanceSecrets, tconf *service.Config) error
{ tconf, err := i.GenerateConfig(trustedSecrets, tconf) if err != nil { return trace.Wrap(err) } i.Config = tconf i.Process, err = service.NewTeleport(tconf) if err != nil { return trace.Wrap(err) } // if the auth server is not enabled, nothing more to do be done if !tconf.Auth.Enabled { return nil } // if this instance contains an auth server, configure the auth server as well. // create users and roles if they don't exist, or sign their keys if they're // already present auth := i.Process.GetAuthServer() for _, user := range i.Secrets.Users { teleUser, err := services.NewUser(user.Username) if err != nil { return trace.Wrap(err) } var roles []services.Role if len(user.Roles) == 0 { role := services.RoleForUser(teleUser) role.SetLogins(services.Allow, user.AllowedLogins) // allow tests to forward agent, still needs to be passed in client roleOptions := role.GetOptions() roleOptions.ForwardAgent = services.NewBool(true) role.SetOptions(roleOptions) err = auth.UpsertRole(role) if err != nil { return trace.Wrap(err) } teleUser.AddRole(role.GetMetadata().Name) roles = append(roles, role) } else { roles = user.Roles for _, role := range user.Roles { err := auth.UpsertRole(role) if err != nil { return trace.Wrap(err) } teleUser.AddRole(role.GetName()) } } err = auth.UpsertUser(teleUser) if err != nil { return trace.Wrap(err) } // if user keys are not present, auto-geneate keys: if user.Key == nil || len(user.Key.Pub) == 0 { priv, pub, _ := tconf.Keygen.GenerateKeyPair("") user.Key = &client.Key{ Priv: priv, Pub: pub, } } // sign user's keys: ttl := 24 * time.Hour user.Key.Cert, user.Key.TLSCert, err = auth.GenerateUserCerts(user.Key.Pub, teleUser.GetName(), ttl, teleport.CertificateFormatStandard) if err != nil { return err } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L603-L655
go
train
// StartNode starts a SSH node and connects it to the cluster.
func (i *TeleInstance) StartNode(tconf *service.Config) (*service.TeleportProcess, error)
// StartNode starts a SSH node and connects it to the cluster. func (i *TeleInstance) StartNode(tconf *service.Config) (*service.TeleportProcess, error)
{ dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName) if err != nil { return nil, trace.Wrap(err) } tconf.DataDir = dataDir authServer := utils.MustParseAddr(net.JoinHostPort(i.Hostname, i.GetPortAuth())) tconf.AuthServers = append(tconf.AuthServers, *authServer) tconf.Token = "token" tconf.UploadEventsC = i.UploadEventsC var ttl time.Duration tconf.CachePolicy = service.CachePolicy{ Enabled: true, RecentTTL: &ttl, } tconf.SSH.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } tconf.Auth.Enabled = false tconf.Proxy.Enabled = false // Create a new Teleport process and add it to the list of nodes that // compose this "cluster". process, err := service.NewTeleport(tconf) if err != nil { return nil, trace.Wrap(err) } i.Nodes = append(i.Nodes, process) // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{ service.NodeSSHReady, } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(process, expectedEvents) if err != nil { return nil, trace.Wrap(err) } log.Debugf("Teleport node (in instance %v) started: %v/%v events received.", i.Secrets.SiteName, len(expectedEvents), len(receivedEvents)) return process, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L659-L725
go
train
// StartNodeAndProxy starts a SSH node and a Proxy Server and connects it to // the cluster.
func (i *TeleInstance) StartNodeAndProxy(name string, sshPort, proxyWebPort, proxySSHPort int) error
// StartNodeAndProxy starts a SSH node and a Proxy Server and connects it to // the cluster. func (i *TeleInstance) StartNodeAndProxy(name string, sshPort, proxyWebPort, proxySSHPort int) error
{ dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName) if err != nil { return trace.Wrap(err) } tconf := service.MakeDefaultConfig() authServer := utils.MustParseAddr(net.JoinHostPort(i.Hostname, i.GetPortAuth())) tconf.AuthServers = append(tconf.AuthServers, *authServer) tconf.Token = "token" tconf.HostUUID = name tconf.Hostname = name tconf.UploadEventsC = i.UploadEventsC tconf.DataDir = dataDir var ttl time.Duration tconf.CachePolicy = service.CachePolicy{ Enabled: true, RecentTTL: &ttl, } tconf.Auth.Enabled = false tconf.Proxy.Enabled = true tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", proxySSHPort)) tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", proxyWebPort)) tconf.Proxy.DisableReverseTunnel = true tconf.Proxy.DisableWebService = true tconf.SSH.Enabled = true tconf.SSH.Addr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", sshPort)) tconf.SSH.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } // Create a new Teleport process and add it to the list of nodes that // compose this "cluster". process, err := service.NewTeleport(tconf) if err != nil { return trace.Wrap(err) } i.Nodes = append(i.Nodes, process) // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{ service.ProxySSHReady, service.NodeSSHReady, } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(process, expectedEvents) if err != nil { return trace.Wrap(err) } log.Debugf("Teleport node and proxy (in instance %v) started: %v/%v events received.", i.Secrets.SiteName, len(expectedEvents), len(receivedEvents)) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L740-L802
go
train
// StartProxy starts another Proxy Server and connects it to the cluster.
func (i *TeleInstance) StartProxy(cfg ProxyConfig) error
// StartProxy starts another Proxy Server and connects it to the cluster. func (i *TeleInstance) StartProxy(cfg ProxyConfig) error
{ dataDir, err := ioutil.TempDir("", "cluster-"+i.Secrets.SiteName+"-"+cfg.Name) if err != nil { return trace.Wrap(err) } tconf := service.MakeDefaultConfig() authServer := utils.MustParseAddr(net.JoinHostPort(i.Hostname, i.GetPortAuth())) tconf.AuthServers = append(tconf.AuthServers, *authServer) tconf.CachePolicy = service.CachePolicy{Enabled: true} tconf.DataDir = dataDir tconf.UploadEventsC = i.UploadEventsC tconf.HostUUID = cfg.Name tconf.Hostname = cfg.Name tconf.Token = "token" tconf.Auth.Enabled = false tconf.SSH.Enabled = false tconf.Proxy.Enabled = true tconf.Proxy.SSHAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.SSHPort)) tconf.Proxy.PublicAddrs = []utils.NetAddr{ utils.NetAddr{ AddrNetwork: "tcp", Addr: Loopback, }, utils.NetAddr{ AddrNetwork: "tcp", Addr: Host, }, } tconf.Proxy.ReverseTunnelListenAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.ReverseTunnelPort)) tconf.Proxy.WebAddr.Addr = net.JoinHostPort(i.Hostname, fmt.Sprintf("%v", cfg.WebPort)) tconf.Proxy.DisableReverseTunnel = false tconf.Proxy.DisableWebService = true // Create a new Teleport process and add it to the list of nodes that // compose this "cluster". process, err := service.NewTeleport(tconf) if err != nil { return trace.Wrap(err) } i.Nodes = append(i.Nodes, process) // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{ service.ProxyReverseTunnelReady, service.ProxySSHReady, } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(process, expectedEvents) if err != nil { return trace.Wrap(err) } log.Debugf("Teleport proxy (in instance %v) started: %v/%v events received.", i.Secrets.SiteName, len(expectedEvents), len(receivedEvents)) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L806-L812
go
train
// Reset re-creates the teleport instance based on the same configuration // This is needed if you want to stop the instance, reset it and start again
func (i *TeleInstance) Reset() (err error)
// Reset re-creates the teleport instance based on the same configuration // This is needed if you want to stop the instance, reset it and start again func (i *TeleInstance) Reset() (err error)
{ i.Process, err = service.NewTeleport(i.Config) if err != nil { return trace.Wrap(err) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L815-L822
go
train
// AddUserUserWithRole adds user with assigned role
func (i *TeleInstance) AddUserWithRole(username string, role services.Role) *User
// AddUserUserWithRole adds user with assigned role func (i *TeleInstance) AddUserWithRole(username string, role services.Role) *User
{ user := &User{ Username: username, Roles: []services.Role{role}, } i.Secrets.Users[username] = user return user }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L826-L837
go
train
// Adds a new user into i Teleport instance. 'mappings' is a comma-separated // list of OS users
func (i *TeleInstance) AddUser(username string, mappings []string) *User
// Adds a new user into i Teleport instance. 'mappings' is a comma-separated // list of OS users func (i *TeleInstance) AddUser(username string, mappings []string) *User
{ log.Infof("teleInstance.AddUser(%v) mapped to %v", username, mappings) if mappings == nil { mappings = make([]string, 0) } user := &User{ Username: username, AllowedLogins: mappings, } i.Secrets.Users[username] = user return user }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L841-L886
go
train
// Start will start the TeleInstance and then block until it is ready to // process requests based off the passed in configuration.
func (i *TeleInstance) Start() error
// Start will start the TeleInstance and then block until it is ready to // process requests based off the passed in configuration. func (i *TeleInstance) Start() error
{ // Build a list of expected events to wait for before unblocking based off // the configuration passed in. expectedEvents := []string{} if i.Config.Auth.Enabled { expectedEvents = append(expectedEvents, service.AuthTLSReady) } if i.Config.Proxy.Enabled { expectedEvents = append(expectedEvents, service.ProxyReverseTunnelReady) expectedEvents = append(expectedEvents, service.ProxySSHReady) expectedEvents = append(expectedEvents, service.ProxyAgentPoolReady) if !i.Config.Proxy.DisableWebService { expectedEvents = append(expectedEvents, service.ProxyWebServerReady) } } if i.Config.SSH.Enabled { expectedEvents = append(expectedEvents, service.NodeSSHReady) } // Start the process and block until the expected events have arrived. receivedEvents, err := startAndWait(i.Process, expectedEvents) if err != nil { return trace.Wrap(err) } // Extract and set reversetunnel.Server and reversetunnel.AgentPool upon // receipt of a ProxyReverseTunnelReady and ProxyAgentPoolReady respectively. for _, re := range receivedEvents { switch re.Name { case service.ProxyReverseTunnelReady: ts, ok := re.Payload.(reversetunnel.Server) if ok { i.Tunnel = ts } case service.ProxyAgentPoolReady: ap, ok := re.Payload.(*reversetunnel.AgentPool) if ok { i.Pool = ap } } } log.Debugf("Teleport instance %v started: %v/%v events received.", i.Secrets.SiteName, len(receivedEvents), len(expectedEvents)) return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L906-L916
go
train
// NewClientWithCreds creates client with credentials
func (i *TeleInstance) NewClientWithCreds(cfg ClientConfig, creds UserCreds) (tc *client.TeleportClient, err error)
// NewClientWithCreds creates client with credentials func (i *TeleInstance) NewClientWithCreds(cfg ClientConfig, creds UserCreds) (tc *client.TeleportClient, err error)
{ clt, err := i.NewUnauthenticatedClient(cfg) if err != nil { return nil, trace.Wrap(err) } err = SetupUserCreds(clt, i.Config.Proxy.SSHAddr.Addr, creds) if err != nil { return nil, trace.Wrap(err) } return clt, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L920-L957
go
train
// NewUnauthenticatedClient returns a fully configured and pre-authenticated client // (pre-authenticated with server CAs and signed session key)
func (i *TeleInstance) NewUnauthenticatedClient(cfg ClientConfig) (tc *client.TeleportClient, err error)
// NewUnauthenticatedClient returns a fully configured and pre-authenticated client // (pre-authenticated with server CAs and signed session key) func (i *TeleInstance) NewUnauthenticatedClient(cfg ClientConfig) (tc *client.TeleportClient, err error)
{ keyDir, err := ioutil.TempDir(i.Config.DataDir, "tsh") if err != nil { return nil, err } proxyConf := &i.Config.Proxy proxyHost, _, err := net.SplitHostPort(proxyConf.SSHAddr.Addr) if err != nil { return nil, trace.Wrap(err) } var webProxyAddr string var sshProxyAddr string if cfg.Proxy == nil { webProxyAddr = proxyConf.WebAddr.Addr sshProxyAddr = proxyConf.SSHAddr.Addr } else { webProxyAddr = net.JoinHostPort(proxyHost, strconv.Itoa(cfg.Proxy.WebPort)) sshProxyAddr = net.JoinHostPort(proxyHost, strconv.Itoa(cfg.Proxy.SSHPort)) } cconf := &client.Config{ Username: cfg.Login, Host: cfg.Host, HostPort: cfg.Port, HostLogin: cfg.Login, InsecureSkipVerify: true, KeysDir: keyDir, SiteName: cfg.Cluster, ForwardAgent: cfg.ForwardAgent, WebProxyAddr: webProxyAddr, SSHProxyAddr: sshProxyAddr, } return client.NewClient(cconf) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L961-L989
go
train
// NewClient returns a fully configured and pre-authenticated client // (pre-authenticated with server CAs and signed session key)
func (i *TeleInstance) NewClient(cfg ClientConfig) (*client.TeleportClient, error)
// NewClient returns a fully configured and pre-authenticated client // (pre-authenticated with server CAs and signed session key) func (i *TeleInstance) NewClient(cfg ClientConfig) (*client.TeleportClient, error)
{ tc, err := i.NewUnauthenticatedClient(cfg) if err != nil { return nil, trace.Wrap(err) } // configures the client authenticate using the keys from 'secrets': user, ok := i.Secrets.Users[cfg.Login] if !ok { return nil, trace.BadParameter("unknown login %q", cfg.Login) } if user.Key == nil { return nil, trace.BadParameter("user %q has no key", cfg.Login) } _, err = tc.AddKey(cfg.Host, user.Key) if err != nil { return nil, trace.Wrap(err) } // tell the client to trust given CAs (from secrets). this is the // equivalent of 'known hosts' in openssh cas := i.Secrets.GetCAs() for i := range cas { err = tc.AddTrustedCA(cas[i]) if err != nil { return nil, trace.Wrap(err) } } return tc, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L993-L1010
go
train
// StopProxy loops over the extra nodes in a TeleInstance and stops all // nodes where the proxy server is enabled.
func (i *TeleInstance) StopProxy() error
// StopProxy loops over the extra nodes in a TeleInstance and stops all // nodes where the proxy server is enabled. func (i *TeleInstance) StopProxy() error
{ var errors []error for _, p := range i.Nodes { if p.Config.Proxy.Enabled { if err := p.Close(); err != nil { errors = append(errors, err) log.Errorf("Failed closing extra proxy: %v.", err) } if err := p.Wait(); err != nil { errors = append(errors, err) log.Errorf("Failed to stop extra proxy: %v.", err) } } } return trace.NewAggregate(errors...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L1013-L1026
go
train
// StopNodes stops additional nodes
func (i *TeleInstance) StopNodes() error
// StopNodes stops additional nodes func (i *TeleInstance) StopNodes() error
{ var errors []error for _, node := range i.Nodes { if err := node.Close(); err != nil { errors = append(errors, err) log.Errorf("failed closing extra node %v", err) } if err := node.Wait(); err != nil { errors = append(errors, err) log.Errorf("failed stopping extra node %v", err) } } return trace.NewAggregate(errors...) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
integration/helpers.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/integration/helpers.go#L1093-L1149
go
train
// ServeHTTP only accepts the CONNECT verb and will tunnel your connection to // the specified host. Also tracks the number of connections that it proxies for // debugging purposes.
func (p *proxyServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
// ServeHTTP only accepts the CONNECT verb and will tunnel your connection to // the specified host. Also tracks the number of connections that it proxies for // debugging purposes. func (p *proxyServer) ServeHTTP(w http.ResponseWriter, r *http.Request)
{ // Validate http connect parameters. if r.Method != http.MethodConnect { trace.WriteError(w, trace.BadParameter("%v not supported", r.Method)) return } if r.Host == "" { trace.WriteError(w, trace.BadParameter("host not set")) return } // Dial to the target host, this is done before hijacking the connection to // ensure the target host is accessible. dconn, err := net.Dial("tcp", r.Host) if err != nil { trace.WriteError(w, err) return } defer dconn.Close() // Once the client receives 200 OK, the rest of the data will no longer be // http, but whatever protocol is being tunneled. w.WriteHeader(http.StatusOK) // Hijack request so we can get underlying connection. hj, ok := w.(http.Hijacker) if !ok { trace.WriteError(w, trace.AccessDenied("unable to hijack connection")) return } sconn, _, err := hj.Hijack() if err != nil { trace.WriteError(w, err) return } defer sconn.Close() // Success, we're proxying data now. p.Lock() p.count = p.count + 1 p.Unlock() // Copy from src to dst and dst to src. errc := make(chan error, 2) replicate := func(dst io.Writer, src io.Reader) { _, err := io.Copy(dst, src) errc <- err } go replicate(sconn, dconn) go replicate(dconn, sconn) // Wait until done, error, or 10 second. select { case <-time.After(10 * time.Second): case <-errc: } }