repo stringlengths 5 67 | sha stringlengths 40 40 | path stringlengths 4 234 | url stringlengths 85 339 | language stringclasses 6 values | split stringclasses 3 values | doc stringlengths 3 51.2k | sign stringlengths 5 8.01k | problem stringlengths 13 51.2k | output stringlengths 0 3.87M |
|---|---|---|---|---|---|---|---|---|---|
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/authentication.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L277-L285 | go | train | // GetAuthPreferenceSchema returns the schema with optionally injected
// schema for extensions. | func GetAuthPreferenceSchema(extensionSchema string) string | // GetAuthPreferenceSchema returns the schema with optionally injected
// schema for extensions.
func GetAuthPreferenceSchema(extensionSchema string) string | {
var authPreferenceSchema string
if authPreferenceSchema == "" {
authPreferenceSchema = fmt.Sprintf(AuthPreferenceSpecSchemaTemplate, "")
} else {
authPreferenceSchema = fmt.Sprintf(AuthPreferenceSpecSchemaTemplate, ","+extensionSchema)
}
return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, authPreferenceSchema, DefaultDefinitions)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/authentication.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L311-L340 | go | train | // Unmarshal unmarshals role from JSON or YAML. | func (t *TeleportAuthPreferenceMarshaler) Unmarshal(bytes []byte, opts ...MarshalOption) (AuthPreference, error) | // Unmarshal unmarshals role from JSON or YAML.
func (t *TeleportAuthPreferenceMarshaler) Unmarshal(bytes []byte, opts ...MarshalOption) (AuthPreference, error) | {
var authPreference AuthPreferenceV2
if len(bytes) == 0 {
return nil, trace.BadParameter("missing resource data")
}
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
if cfg.SkipValidation {
if err := utils.FastUnmarshal(bytes, &authPreference); err != nil {
return nil, trace.BadParameter(err.Error())
}
} else {
err := utils.UnmarshalWithSchema(GetAuthPreferenceSchema(""), &authPreference, bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
}
if cfg.ID != 0 {
authPreference.SetResourceID(cfg.ID)
}
if !cfg.Expires.IsZero() {
authPreference.SetExpiry(cfg.Expires)
}
return &authPreference, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/authentication.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/authentication.go#L343-L345 | go | train | // Marshal marshals role to JSON or YAML. | func (t *TeleportAuthPreferenceMarshaler) Marshal(c AuthPreference, opts ...MarshalOption) ([]byte, error) | // Marshal marshals role to JSON or YAML.
func (t *TeleportAuthPreferenceMarshaler) Marshal(c AuthPreference, opts ...MarshalOption) ([]byte, error) | {
return json.Marshal(c)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/regular/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/proxy.go#L68-L133 | go | train | // parseProxySubsys looks at the requested subsystem name and returns a fully configured
// proxy subsystem
//
// proxy subsystem name can take the following forms:
// "proxy:host:22" - standard SSH request to connect to host:22 on the 1st cluster
// "proxy:@clustername" - Teleport request to connect to an auth server for cluster with name 'clustername'
// "proxy:host:22@clustername" - Teleport request to connect to host:22 on cluster 'clustername'
// "proxy:host:22@namespace@clustername" | func parseProxySubsys(request string, srv *Server, ctx *srv.ServerContext) (*proxySubsys, error) | // parseProxySubsys looks at the requested subsystem name and returns a fully configured
// proxy subsystem
//
// proxy subsystem name can take the following forms:
// "proxy:host:22" - standard SSH request to connect to host:22 on the 1st cluster
// "proxy:@clustername" - Teleport request to connect to an auth server for cluster with name 'clustername'
// "proxy:host:22@clustername" - Teleport request to connect to host:22 on cluster 'clustername'
// "proxy:host:22@namespace@clustername"
func parseProxySubsys(request string, srv *Server, ctx *srv.ServerContext) (*proxySubsys, error) | {
log.Debugf("parse_proxy_subsys(%q)", request)
var (
clusterName string
targetHost string
targetPort string
paramMessage = fmt.Sprintf("invalid format for proxy request: %q, expected 'proxy:host:port@cluster'", request)
)
const prefix = "proxy:"
// get rid of 'proxy:' prefix:
if strings.Index(request, prefix) != 0 {
return nil, trace.BadParameter(paramMessage)
}
requestBody := strings.TrimPrefix(request, prefix)
namespace := defaults.Namespace
var err error
parts := strings.Split(requestBody, "@")
switch {
case len(parts) == 0: // "proxy:"
return nil, trace.BadParameter(paramMessage)
case len(parts) == 1: // "proxy:host:22"
targetHost, targetPort, err = utils.SplitHostPort(parts[0])
if err != nil {
return nil, trace.BadParameter(paramMessage)
}
case len(parts) == 2: // "proxy:@clustername" or "proxy:host:22@clustername"
if parts[0] != "" {
targetHost, targetPort, err = utils.SplitHostPort(parts[0])
if err != nil {
return nil, trace.BadParameter(paramMessage)
}
}
clusterName = parts[1]
if clusterName == "" && targetHost == "" {
return nil, trace.BadParameter("invalid format for proxy request: missing cluster name or target host in %q", request)
}
case len(parts) >= 3: // "proxy:host:22@namespace@clustername"
clusterName = strings.Join(parts[2:], "@")
namespace = parts[1]
targetHost, targetPort, err = utils.SplitHostPort(parts[0])
if err != nil {
return nil, trace.BadParameter(paramMessage)
}
}
if clusterName != "" && srv.proxyTun != nil {
_, err := srv.proxyTun.GetSite(clusterName)
if err != nil {
return nil, trace.BadParameter("invalid format for proxy request: unknown cluster %q in %q", clusterName, request)
}
}
return &proxySubsys{
log: logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentSubsystemProxy,
trace.ComponentFields: map[string]string{},
}),
namespace: namespace,
srv: srv,
host: targetHost,
port: targetPort,
clusterName: clusterName,
closeC: make(chan struct{}),
agent: ctx.GetAgent(),
agentChannel: ctx.GetAgentChannel(),
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/regular/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/proxy.go#L142-L194 | go | train | // Start is called by Golang's ssh when it needs to engage this sybsystem (typically to establish
// a mapping connection between a client & remote node we're proxying to) | func (t *proxySubsys) Start(sconn *ssh.ServerConn, ch ssh.Channel, req *ssh.Request, ctx *srv.ServerContext) error | // Start is called by Golang's ssh when it needs to engage this sybsystem (typically to establish
// a mapping connection between a client & remote node we're proxying to)
func (t *proxySubsys) Start(sconn *ssh.ServerConn, ch ssh.Channel, req *ssh.Request, ctx *srv.ServerContext) error | {
// once we start the connection, update logger to include component fields
t.log = logrus.WithFields(logrus.Fields{
trace.Component: teleport.ComponentSubsystemProxy,
trace.ComponentFields: map[string]string{
"src": sconn.RemoteAddr().String(),
"dst": sconn.LocalAddr().String(),
},
})
t.log.Debugf("Starting subsystem")
var (
site reversetunnel.RemoteSite
err error
tunnel = t.srv.proxyTun
clientAddr = sconn.RemoteAddr()
)
// did the client pass us a true client IP ahead of time via an environment variable?
// (usually the web client would do that)
ctx.Lock()
trueClientIP, ok := ctx.GetEnv(sshutils.TrueClientAddrVar)
ctx.Unlock()
if ok {
a, err := utils.ParseAddr(trueClientIP)
if err == nil {
clientAddr = a
}
}
// get the cluster by name:
if t.clusterName != "" {
site, err = tunnel.GetSite(t.clusterName)
if err != nil {
t.log.Warn(err)
return trace.Wrap(err)
}
}
// connecting to a specific host:
if t.host != "" {
// no site given? use the 1st one:
if site == nil {
sites := tunnel.GetSites()
if len(sites) == 0 {
t.log.Errorf("Not connected to any remote clusters")
return trace.Errorf("no connected sites")
}
site = sites[0]
t.log.Debugf("Cluster not specified. connecting to default='%s'", site.GetName())
}
return t.proxyToHost(ctx, site, clientAddr, ch)
}
// connect to a site's auth server:
return t.proxyToSite(ctx, site, clientAddr, ch)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/regular/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/proxy.go#L198-L226 | go | train | // proxyToSite establishes a proxy connection from the connected SSH client to the
// auth server of the requested remote site | func (t *proxySubsys) proxyToSite(
ctx *srv.ServerContext, site reversetunnel.RemoteSite, remoteAddr net.Addr, ch ssh.Channel) error | // proxyToSite establishes a proxy connection from the connected SSH client to the
// auth server of the requested remote site
func (t *proxySubsys) proxyToSite(
ctx *srv.ServerContext, site reversetunnel.RemoteSite, remoteAddr net.Addr, ch ssh.Channel) error | {
conn, err := site.DialAuthServer()
if err != nil {
return trace.Wrap(err)
}
t.log.Infof("Connected to auth server: %v", conn.RemoteAddr())
go func() {
var err error
defer func() {
t.close(err)
}()
defer ch.Close()
_, err = io.Copy(ch, conn)
}()
go func() {
var err error
defer func() {
t.close(err)
}()
defer conn.Close()
_, err = io.Copy(conn, srv.NewTrackingReader(ctx, ch))
}()
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/regular/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/proxy.go#L230-L353 | go | train | // proxyToHost establishes a proxy connection from the connected SSH client to the
// requested remote node (t.host:t.port) via the given site | func (t *proxySubsys) proxyToHost(
ctx *srv.ServerContext, site reversetunnel.RemoteSite, remoteAddr net.Addr, ch ssh.Channel) error | // proxyToHost establishes a proxy connection from the connected SSH client to the
// requested remote node (t.host:t.port) via the given site
func (t *proxySubsys) proxyToHost(
ctx *srv.ServerContext, site reversetunnel.RemoteSite, remoteAddr net.Addr, ch ssh.Channel) error | {
//
// first, lets fetch a list of servers at the given site. this allows us to
// match the given "host name" against node configuration (their 'nodename' setting)
//
// but failing to fetch the list of servers is also OK, we'll use standard
// network resolution (by IP or DNS)
//
var (
servers []services.Server
err error
)
localCluster, _ := t.srv.authService.GetClusterName()
// going to "local" CA? lets use the caching 'auth service' directly and avoid
// hitting the reverse tunnel link (it can be offline if the CA is down)
if site.GetName() == localCluster.GetName() {
servers, err = t.srv.authService.GetNodes(t.namespace, services.SkipValidation())
if err != nil {
t.log.Warn(err)
}
} else {
// "remote" CA? use a reverse tunnel to talk to it:
siteClient, err := site.CachingAccessPoint()
if err != nil {
t.log.Warn(err)
} else {
servers, err = siteClient.GetNodes(t.namespace, services.SkipValidation())
if err != nil {
t.log.Warn(err)
}
}
}
// if port is 0, it means the client wants us to figure out
// which port to use
specifiedPort := len(t.port) > 0 && t.port != "0"
ips, _ := net.LookupHost(t.host)
t.log.Debugf("proxy connecting to host=%v port=%v, exact port=%v", t.host, t.port, specifiedPort)
// enumerate and try to find a server with self-registered with a matching name/IP:
var server services.Server
for i := range servers {
ip, port, err := net.SplitHostPort(servers[i].GetAddr())
if err != nil {
t.log.Error(err)
continue
}
if t.host == ip || t.host == servers[i].GetHostname() || utils.SliceContainsStr(ips, ip) {
if !specifiedPort || t.port == port {
server = servers[i]
break
}
}
}
// Create a slice of principals that will be added into the host certificate.
// Here t.host is either an IP address or a DNS name as the user requested.
principals := []string{t.host}
// Resolve the IP address to dial to because the hostname may not be
// DNS resolvable.
var serverAddr string
if server != nil {
serverAddr = server.GetAddr()
// Update the list of principals with the IP address the node self reported
// itself as as well as the hostUUID.clusterName.
host, _, err := net.SplitHostPort(serverAddr)
if err != nil {
return trace.Wrap(err)
}
principals = append(principals, host, fmt.Sprintf("%v.%v", server.GetName(), t.clusterName))
} else {
if !specifiedPort {
t.port = strconv.Itoa(defaults.SSHServerListenPort)
}
serverAddr = net.JoinHostPort(t.host, t.port)
t.log.Warnf("server lookup failed: using default=%v", serverAddr)
}
// Pass the agent along to the site. If the proxy is in recording mode, this
// agent is used to perform user authentication. Pass the DNS name to the
// dialer as well so the forwarding proxy can generate a host certificate
// with the correct hostname).
toAddr := &utils.NetAddr{
AddrNetwork: "tcp",
Addr: serverAddr,
}
conn, err := site.Dial(reversetunnel.DialParams{
From: remoteAddr,
To: toAddr,
UserAgent: t.agent,
Address: t.host,
Principals: principals,
})
if err != nil {
return trace.Wrap(err)
}
// this custom SSH handshake allows SSH proxy to relay the client's IP
// address to the SSH server
t.doHandshake(remoteAddr, ch, conn)
go func() {
var err error
defer func() {
t.close(err)
}()
defer ch.Close()
_, err = io.Copy(ch, conn)
}()
go func() {
var err error
defer func() {
t.close(err)
}()
defer conn.Close()
_, err = io.Copy(conn, srv.NewTrackingReader(ctx, ch))
}()
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/regular/proxy.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/regular/proxy.go#L369-L404 | go | train | // doHandshake allows a proxy server to send additional information (client IP)
// to an SSH server before establishing a bridge | func (t *proxySubsys) doHandshake(clientAddr net.Addr, clientConn io.ReadWriter, serverConn io.ReadWriter) | // doHandshake allows a proxy server to send additional information (client IP)
// to an SSH server before establishing a bridge
func (t *proxySubsys) doHandshake(clientAddr net.Addr, clientConn io.ReadWriter, serverConn io.ReadWriter) | {
// on behalf of a client ask the server for it's version:
buff := make([]byte, sshutils.MaxVersionStringBytes)
n, err := serverConn.Read(buff)
if err != nil {
t.log.Error(err)
return
}
// chop off extra unused bytes at the end of the buffer:
buff = buff[:n]
// is that a Teleport server?
if bytes.HasPrefix(buff, []byte(sshutils.SSHVersionPrefix)) {
// if we're connecting to a Teleport SSH server, send our own "handshake payload"
// message, along with a client's IP:
hp := &sshutils.HandshakePayload{
ClientAddr: clientAddr.String(),
}
payloadJSON, err := json.Marshal(hp)
if err != nil {
t.log.Error(err)
} else {
// send a JSON payload sandwitched between 'teleport proxy signature' and 0x00:
payload := fmt.Sprintf("%s%s\x00", sshutils.ProxyHelloSignature, payloadJSON)
n, err = serverConn.Write([]byte(payload))
if err != nil {
t.log.Error(err)
}
}
}
// forwrd server's response to the client:
_, err = clientConn.Write(buff)
if err != nil {
t.log.Error(err)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/tls.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L41-L47 | go | train | // ListenTLS sets up TLS listener for the http handler, starts listening
// on a TCP socket and returns the socket which is ready to be used
// for http.Serve | func ListenTLS(address string, certFile, keyFile string, cipherSuites []uint16) (net.Listener, error) | // ListenTLS sets up TLS listener for the http handler, starts listening
// on a TCP socket and returns the socket which is ready to be used
// for http.Serve
func ListenTLS(address string, certFile, keyFile string, cipherSuites []uint16) (net.Listener, error) | {
tlsConfig, err := CreateTLSConfiguration(certFile, keyFile, cipherSuites)
if err != nil {
return nil, trace.Wrap(err)
}
return tls.Listen("tcp", address, tlsConfig)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/tls.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L50-L67 | go | train | // TLSConfig returns default TLS configuration strong defaults. | func TLSConfig(cipherSuites []uint16) *tls.Config | // TLSConfig returns default TLS configuration strong defaults.
func TLSConfig(cipherSuites []uint16) *tls.Config | {
config := &tls.Config{}
// If ciphers suites were passed in, use them. Otherwise use the the
// Go defaults.
if len(cipherSuites) > 0 {
config.CipherSuites = cipherSuites
}
// Pick the servers preferred ciphersuite, not the clients.
config.PreferServerCipherSuites = true
config.MinVersion = tls.VersionTLS12
config.SessionTicketsDisabled = false
config.ClientSessionCache = tls.NewLRUClientSessionCache(
DefaultLRUCapacity)
return config
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/tls.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L70-L87 | go | train | // CreateTLSConfiguration sets up default TLS configuration | func CreateTLSConfiguration(certFile, keyFile string, cipherSuites []uint16) (*tls.Config, error) | // CreateTLSConfiguration sets up default TLS configuration
func CreateTLSConfiguration(certFile, keyFile string, cipherSuites []uint16) (*tls.Config, error) | {
config := TLSConfig(cipherSuites)
if _, err := os.Stat(certFile); err != nil {
return nil, trace.BadParameter("certificate is not accessible by '%v'", certFile)
}
if _, err := os.Stat(keyFile); err != nil {
return nil, trace.BadParameter("certificate is not accessible by '%v'", certFile)
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, trace.Wrap(err)
}
config.Certificates = []tls.Certificate{cert}
return config, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/tls.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L100-L153 | go | train | // GenerateSelfSignedCert generates a self signed certificate that
// is valid for given domain names and ips, returns PEM-encoded bytes with key and cert | func GenerateSelfSignedCert(hostNames []string) (*TLSCredentials, error) | // GenerateSelfSignedCert generates a self signed certificate that
// is valid for given domain names and ips, returns PEM-encoded bytes with key and cert
func GenerateSelfSignedCert(hostNames []string) (*TLSCredentials, error) | {
priv, err := rsa.GenerateKey(rand.Reader, teleport.RSAKeySize)
if err != nil {
return nil, trace.Wrap(err)
}
notBefore := time.Now()
notAfter := notBefore.Add(time.Hour * 24 * 365 * 10) // 10 years
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return nil, trace.Wrap(err)
}
entity := pkix.Name{
CommonName: "localhost",
Country: []string{"US"},
Organization: []string{"localhost"},
}
template := x509.Certificate{
SerialNumber: serialNumber,
Issuer: entity,
Subject: entity,
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
IsCA: true,
}
// collect IP addresses localhost resolves to and add them to the cert. template:
template.DNSNames = append(hostNames, "localhost.local")
ips, _ := net.LookupIP("localhost")
if ips != nil {
template.IPAddresses = ips
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, trace.Wrap(err)
}
publicKeyBytes, err := x509.MarshalPKIXPublicKey(priv.Public())
if err != nil {
log.Error(err)
return nil, trace.Wrap(err)
}
return &TLSCredentials{
PublicKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: publicKeyBytes}),
PrivateKey: pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}),
Cert: pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}),
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/tls.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L157-L170 | go | train | // CipherSuiteMapping transforms Teleport formatted cipher suites strings
// into uint16 IDs. | func CipherSuiteMapping(cipherSuites []string) ([]uint16, error) | // CipherSuiteMapping transforms Teleport formatted cipher suites strings
// into uint16 IDs.
func CipherSuiteMapping(cipherSuites []string) ([]uint16, error) | {
out := make([]uint16, 0, len(cipherSuites))
for _, cs := range cipherSuites {
c, ok := cipherSuiteMapping[cs]
if !ok {
return nil, trace.BadParameter("cipher suite not supported: %v", cs)
}
out = append(out, c)
}
return out, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/tls.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/tls.go#L205-L219 | go | train | // DefaultCipherSuites returns the default list of cipher suites that
// Teleport supports. By default Teleport only support modern ciphers
// (Chacha20 and AES GCM). Key exchanges which support perfect forward
// secrecy (ECDHE) have priority over those that do not (RSA). | func DefaultCipherSuites() []uint16 | // DefaultCipherSuites returns the default list of cipher suites that
// Teleport supports. By default Teleport only support modern ciphers
// (Chacha20 and AES GCM). Key exchanges which support perfect forward
// secrecy (ECDHE) have priority over those that do not (RSA).
func DefaultCipherSuites() []uint16 | {
return []uint16{
tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L95-L108 | go | train | // NewTerminal returns a new terminal. Terminal can be local or remote
// depending on cluster configuration. | func NewTerminal(ctx *ServerContext) (Terminal, error) | // NewTerminal returns a new terminal. Terminal can be local or remote
// depending on cluster configuration.
func NewTerminal(ctx *ServerContext) (Terminal, error) | {
// It doesn't matter what mode the cluster is in, if this is a Teleport node
// return a local terminal.
if ctx.srv.Component() == teleport.ComponentNode {
return newLocalTerminal(ctx)
}
// If this is not a Teleport node, find out what mode the cluster is in and
// return the correct terminal.
if ctx.ClusterConfig.GetSessionRecording() == services.RecordAtProxy {
return newRemoteTerminal(ctx)
}
return newLocalTerminal(ctx)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L128-L153 | go | train | // NewLocalTerminal creates and returns a local PTY. | func newLocalTerminal(ctx *ServerContext) (*terminal, error) | // NewLocalTerminal creates and returns a local PTY.
func newLocalTerminal(ctx *ServerContext) (*terminal, error) | {
var err error
t := &terminal{
log: log.WithFields(log.Fields{
trace.Component: teleport.ComponentLocalTerm,
}),
ctx: ctx,
}
// Open PTY and corresponding TTY.
t.pty, t.tty, err = pty.Open()
if err != nil {
log.Warnf("Could not start PTY %v", err)
return nil, err
}
// Set the TTY owner. Failure is not fatal, for example Teleport is running
// on a read-only filesystem, but logging is useful for diagnostic purposes.
err = t.setOwner()
if err != nil {
log.Debugf("Unable to set TTY owner: %v.\n", err)
}
return t, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L162-L183 | go | train | // Run will run the terminal. | func (t *terminal) Run() error | // Run will run the terminal.
func (t *terminal) Run() error | {
defer t.closeTTY()
cmd, err := prepareInteractiveCommand(t.ctx)
if err != nil {
return trace.Wrap(err)
}
t.cmd = cmd
cmd.Stdout = t.tty
cmd.Stdin = t.tty
cmd.Stderr = t.tty
cmd.SysProcAttr.Setctty = true
cmd.SysProcAttr.Setsid = true
err = cmd.Start()
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L186-L205 | go | train | // Wait will block until the terminal is complete. | func (t *terminal) Wait() (*ExecResult, error) | // Wait will block until the terminal is complete.
func (t *terminal) Wait() (*ExecResult, error) | {
err := t.cmd.Wait()
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
status := exitErr.Sys().(syscall.WaitStatus)
return &ExecResult{Code: status.ExitStatus(), Command: t.cmd.Path}, nil
}
return nil, err
}
status, ok := t.cmd.ProcessState.Sys().(syscall.WaitStatus)
if !ok {
return nil, trace.Errorf("unknown exit status: %T(%v)", t.cmd.ProcessState.Sys(), t.cmd.ProcessState.Sys())
}
return &ExecResult{
Code: status.ExitStatus(),
Command: t.cmd.Path,
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L208-L218 | go | train | // Kill will force kill the terminal. | func (t *terminal) Kill() error | // Kill will force kill the terminal.
func (t *terminal) Kill() error | {
if t.cmd.Process != nil {
if err := t.cmd.Process.Kill(); err != nil {
if err.Error() != "os: process already finished" {
return trace.Wrap(err)
}
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L231-L242 | go | train | // Close will free resources associated with the terminal. | func (t *terminal) Close() error | // Close will free resources associated with the terminal.
func (t *terminal) Close() error | {
var err error
// note, pty is closed in the copying goroutine,
// not here to avoid data races
if t.tty != nil {
if e := t.tty.Close(); e != nil {
err = e
}
}
go t.closePTY()
return trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L264-L275 | go | train | // GetWinSize returns the window size of the terminal. | func (t *terminal) GetWinSize() (*term.Winsize, error) | // GetWinSize returns the window size of the terminal.
func (t *terminal) GetWinSize() (*term.Winsize, error) | {
t.mu.Lock()
defer t.mu.Unlock()
if t.pty == nil {
return nil, trace.NotFound("no pty")
}
ws, err := term.GetWinsize(t.pty.Fd())
if err != nil {
return nil, trace.Wrap(err)
}
return ws, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L278-L289 | go | train | // SetWinSize sets the window size of the terminal. | func (t *terminal) SetWinSize(params rsession.TerminalParams) error | // SetWinSize sets the window size of the terminal.
func (t *terminal) SetWinSize(params rsession.TerminalParams) error | {
t.mu.Lock()
defer t.mu.Unlock()
if t.pty == nil {
return trace.NotFound("no pty")
}
if err := term.SetWinsize(t.pty.Fd(), params.Winsize()); err != nil {
return trace.Wrap(err)
}
t.params = params
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L293-L297 | go | train | // GetTerminalParams is a fast call to get cached terminal parameters
// and avoid extra system call. | func (t *terminal) GetTerminalParams() rsession.TerminalParams | // GetTerminalParams is a fast call to get cached terminal parameters
// and avoid extra system call.
func (t *terminal) GetTerminalParams() rsession.TerminalParams | {
t.mu.Lock()
defer t.mu.Unlock()
return t.params
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L305-L310 | go | train | // SetTermType sets the terminal type from "req-pty" request. | func (t *terminal) SetTermType(term string) | // SetTermType sets the terminal type from "req-pty" request.
func (t *terminal) SetTermType(term string) | {
if term == "" {
term = defaultTerm
}
t.termType = term
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L318-L352 | go | train | // getOwner determines the uid, gid, and mode of the TTY similar to OpenSSH:
// https://github.com/openssh/openssh-portable/blob/ddc0f38/sshpty.c#L164-L215 | func getOwner(login string, lookupUser LookupUser, lookupGroup LookupGroup) (int, int, os.FileMode, error) | // getOwner determines the uid, gid, and mode of the TTY similar to OpenSSH:
// https://github.com/openssh/openssh-portable/blob/ddc0f38/sshpty.c#L164-L215
func getOwner(login string, lookupUser LookupUser, lookupGroup LookupGroup) (int, int, os.FileMode, error) | {
var err error
var uid int
var gid int
var mode os.FileMode
// Lookup the Unix login for the UID and fallback GID.
u, err := lookupUser(login)
if err != nil {
return 0, 0, 0, trace.Wrap(err)
}
uid, err = strconv.Atoi(u.Uid)
if err != nil {
return 0, 0, 0, trace.Wrap(err)
}
// If the tty group exists, use that as the gid of the TTY and set mode to
// be u+rw. Otherwise use the group of the user with mode u+rw g+w.
group, err := lookupGroup("tty")
if err != nil {
gid, err = strconv.Atoi(u.Gid)
if err != nil {
return 0, 0, 0, trace.Wrap(err)
}
mode = 0620
} else {
gid, err = strconv.Atoi(group.Gid)
if err != nil {
return 0, 0, 0, trace.Wrap(err)
}
mode = 0600
}
return uid, gid, mode, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L355-L373 | go | train | // setOwner changes the owner and mode of the TTY. | func (t *terminal) setOwner() error | // setOwner changes the owner and mode of the TTY.
func (t *terminal) setOwner() error | {
uid, gid, mode, err := getOwner(t.ctx.Identity.Login, user.Lookup, user.LookupGroup)
if err != nil {
return trace.Wrap(err)
}
err = os.Chown(t.tty.Name(), uid, gid)
if err != nil {
return trace.Wrap(err)
}
err = os.Chmod(t.tty.Name(), mode)
if err != nil {
return trace.Wrap(err)
}
log.Debugf("Set permissions on %v to %v:%v with mode %v.", t.tty.Name(), uid, gid, mode)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/term.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/term.go#L586-L600 | go | train | // prepareRemoteSession prepares the more session for execution. | func (t *remoteTerminal) prepareRemoteSession(session *ssh.Session, ctx *ServerContext) | // prepareRemoteSession prepares the more session for execution.
func (t *remoteTerminal) prepareRemoteSession(session *ssh.Session, ctx *ServerContext) | {
envs := map[string]string{
teleport.SSHTeleportUser: ctx.Identity.TeleportUser,
teleport.SSHSessionWebproxyAddr: ctx.ProxyPublicAddress(),
teleport.SSHTeleportHostUUID: ctx.srv.ID(),
teleport.SSHTeleportClusterName: ctx.ClusterName,
teleport.SSHSessionID: string(ctx.session.id),
}
for k, v := range envs {
if err := session.Setenv(k, v); err != nil {
t.log.Debugf("Unable to set environment variable: %v: %v", k, v)
}
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/system/signal.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/system/signal.go#L29-L34 | go | train | // ResetInterruptSignal will reset the handler for SIGINT back to the default
// handler. We need to do this because when sysvinit launches Teleport on some
// operating systems (like CentOS 6.8) it configures Teleport to ignore SIGINT
// signals. See the following for more details:
//
// http://garethrees.org/2015/08/07/ping/
// https://github.com/openssh/openssh-portable/commit/4e0f5e1ec9b6318ef251180dbca50eaa01f74536 | func ResetInterruptSignalHandler() | // ResetInterruptSignal will reset the handler for SIGINT back to the default
// handler. We need to do this because when sysvinit launches Teleport on some
// operating systems (like CentOS 6.8) it configures Teleport to ignore SIGINT
// signals. See the following for more details:
//
// http://garethrees.org/2015/08/07/ping/
// https://github.com/openssh/openssh-portable/commit/4e0f5e1ec9b6318ef251180dbca50eaa01f74536
func ResetInterruptSignalHandler() | {
_, err := C.resetInterruptSignalHandler()
if err != nil {
log.Warnf("Failed to reset interrupt signal handler: %v.", err)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L62-L125 | go | train | // NewAuthServer creates and configures a new AuthServer instance | func NewAuthServer(cfg *InitConfig, opts ...AuthServerOption) (*AuthServer, error) | // NewAuthServer creates and configures a new AuthServer instance
func NewAuthServer(cfg *InitConfig, opts ...AuthServerOption) (*AuthServer, error) | {
if cfg.Trust == nil {
cfg.Trust = local.NewCAService(cfg.Backend)
}
if cfg.Presence == nil {
cfg.Presence = local.NewPresenceService(cfg.Backend)
}
if cfg.Provisioner == nil {
cfg.Provisioner = local.NewProvisioningService(cfg.Backend)
}
if cfg.Identity == nil {
cfg.Identity = local.NewIdentityService(cfg.Backend)
}
if cfg.Access == nil {
cfg.Access = local.NewAccessService(cfg.Backend)
}
if cfg.ClusterConfiguration == nil {
cfg.ClusterConfiguration = local.NewClusterConfigurationService(cfg.Backend)
}
if cfg.Events == nil {
cfg.Events = local.NewEventsService(cfg.Backend)
}
if cfg.AuditLog == nil {
cfg.AuditLog = events.NewDiscardAuditLog()
}
limiter, err := limiter.NewConnectionsLimiter(limiter.LimiterConfig{
MaxConnections: defaults.LimiterMaxConcurrentSignatures,
})
if err != nil {
return nil, trace.Wrap(err)
}
closeCtx, cancelFunc := context.WithCancel(context.TODO())
as := AuthServer{
bk: cfg.Backend,
limiter: limiter,
Authority: cfg.Authority,
AuthServiceName: cfg.AuthServiceName,
oidcClients: make(map[string]*oidcClient),
samlProviders: make(map[string]*samlProvider),
githubClients: make(map[string]*githubClient),
cancelFunc: cancelFunc,
closeCtx: closeCtx,
AuthServices: AuthServices{
Trust: cfg.Trust,
Presence: cfg.Presence,
Provisioner: cfg.Provisioner,
Identity: cfg.Identity,
Access: cfg.Access,
ClusterConfiguration: cfg.ClusterConfiguration,
IAuditLog: cfg.AuditLog,
Events: cfg.Events,
},
}
for _, o := range opts {
o(&as)
}
if as.clock == nil {
as.clock = clockwork.NewRealClock()
}
return &as, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L212-L216 | go | train | // SetCache sets cache used by auth server | func (a *AuthServer) SetCache(clt AuthCache) | // SetCache sets cache used by auth server
func (a *AuthServer) SetCache(clt AuthCache) | {
a.lock.Lock()
defer a.lock.Unlock()
a.cache = clt
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L219-L226 | go | train | // GetCache returns cache used by auth server | func (a *AuthServer) GetCache() AuthCache | // GetCache returns cache used by auth server
func (a *AuthServer) GetCache() AuthCache | {
a.lock.RLock()
defer a.lock.RUnlock()
if a.cache == nil {
return &a.AuthServices
}
return a.cache
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L230-L255 | go | train | // runPeriodicOperations runs some periodic bookkeeping operations
// performed by auth server | func (a *AuthServer) runPeriodicOperations() | // runPeriodicOperations runs some periodic bookkeeping operations
// performed by auth server
func (a *AuthServer) runPeriodicOperations() | {
// run periodic functions with a semi-random period
// to avoid contention on the database in case if there are multiple
// auth servers running - so they don't compete trying
// to update the same resources.
r := rand.New(rand.NewSource(a.GetClock().Now().UnixNano()))
period := defaults.HighResPollingPeriod + time.Duration(r.Intn(int(defaults.HighResPollingPeriod/time.Second)))*time.Second
log.Debugf("Ticking with period: %v.", period)
ticker := time.NewTicker(period)
defer ticker.Stop()
for {
select {
case <-a.closeCtx.Done():
return
case <-ticker.C:
err := a.autoRotateCertAuthorities()
if err != nil {
if trace.IsCompareFailed(err) {
log.Debugf("Cert authority has been updated concurrently: %v.", err)
} else {
log.Errorf("Failed to perform cert rotation check: %v.", err)
}
}
}
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L272-L276 | go | train | // SetClock sets clock, used in tests | func (a *AuthServer) SetClock(clock clockwork.Clock) | // SetClock sets clock, used in tests
func (a *AuthServer) SetClock(clock clockwork.Clock) | {
a.lock.Lock()
defer a.lock.Unlock()
a.clock = clock
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L284-L286 | go | train | // GetClusterConfig gets ClusterConfig from the backend. | func (a *AuthServer) GetClusterConfig(opts ...services.MarshalOption) (services.ClusterConfig, error) | // GetClusterConfig gets ClusterConfig from the backend.
func (a *AuthServer) GetClusterConfig(opts ...services.MarshalOption) (services.ClusterConfig, error) | {
return a.GetCache().GetClusterConfig(opts...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L290-L292 | go | train | // GetClusterName returns the domain name that identifies this authority server.
// Also known as "cluster name" | func (a *AuthServer) GetClusterName(opts ...services.MarshalOption) (services.ClusterName, error) | // GetClusterName returns the domain name that identifies this authority server.
// Also known as "cluster name"
func (a *AuthServer) GetClusterName(opts ...services.MarshalOption) (services.ClusterName, error) | {
return a.GetCache().GetClusterName(opts...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L296-L302 | go | train | // GetDomainName returns the domain name that identifies this authority server.
// Also known as "cluster name" | func (a *AuthServer) GetDomainName() (string, error) | // GetDomainName returns the domain name that identifies this authority server.
// Also known as "cluster name"
func (a *AuthServer) GetDomainName() (string, error) | {
clusterName, err := a.GetClusterName()
if err != nil {
return "", trace.Wrap(err)
}
return clusterName.GetClusterName(), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L311-L338 | go | train | // GetClusterCACert returns the CAs for the local cluster without signing keys. | func (a *AuthServer) GetClusterCACert() (*LocalCAResponse, error) | // GetClusterCACert returns the CAs for the local cluster without signing keys.
func (a *AuthServer) GetClusterCACert() (*LocalCAResponse, error) | {
clusterName, err := a.GetClusterName()
if err != nil {
return nil, trace.Wrap(err)
}
// Extract the TLS CA for this cluster.
hostCA, err := a.GetCache().GetCertAuthority(services.CertAuthID{
Type: services.HostCA,
DomainName: clusterName.GetClusterName(),
}, false)
if err != nil {
return nil, trace.Wrap(err)
}
tlsCA, err := hostCA.TLSCA()
if err != nil {
return nil, trace.Wrap(err)
}
// Marshal to PEM bytes to send the CA over the wire.
pemBytes, err := tlsca.MarshalCertificatePEM(tlsCA.Cert)
if err != nil {
return nil, trace.Wrap(err)
}
return &LocalCAResponse{
TLSCA: pemBytes,
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L342-L374 | go | train | // GenerateHostCert uses the private key of the CA to sign the public key of the host
// (along with meta data like host ID, node name, roles, and ttl) to generate a host certificate. | func (s *AuthServer) GenerateHostCert(hostPublicKey []byte, hostID, nodeName string, principals []string, clusterName string, roles teleport.Roles, ttl time.Duration) ([]byte, error) | // GenerateHostCert uses the private key of the CA to sign the public key of the host
// (along with meta data like host ID, node name, roles, and ttl) to generate a host certificate.
func (s *AuthServer) GenerateHostCert(hostPublicKey []byte, hostID, nodeName string, principals []string, clusterName string, roles teleport.Roles, ttl time.Duration) ([]byte, error) | {
domainName, err := s.GetDomainName()
if err != nil {
return nil, trace.Wrap(err)
}
// get the certificate authority that will be signing the public key of the host
ca, err := s.Trust.GetCertAuthority(services.CertAuthID{
Type: services.HostCA,
DomainName: domainName,
}, true)
if err != nil {
return nil, trace.BadParameter("failed to load host CA for '%s': %v", domainName, err)
}
// get the private key of the certificate authority
caPrivateKey, err := ca.FirstSigningKey()
if err != nil {
return nil, trace.Wrap(err)
}
// create and sign!
return s.Authority.GenerateHostCert(services.HostCertParams{
PrivateCASigningKey: caPrivateKey,
PublicHostKey: hostPublicKey,
HostID: hostID,
NodeName: nodeName,
Principals: principals,
ClusterName: clusterName,
Roles: roles,
TTL: ttl,
})
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L407-L427 | go | train | // GenerateUserCerts is used to generate user certificate, used internally for tests | func (a *AuthServer) GenerateUserCerts(key []byte, username string, ttl time.Duration, compatibility string) ([]byte, []byte, error) | // GenerateUserCerts is used to generate user certificate, used internally for tests
func (a *AuthServer) GenerateUserCerts(key []byte, username string, ttl time.Duration, compatibility string) ([]byte, []byte, error) | {
user, err := a.Identity.GetUser(username)
if err != nil {
return nil, nil, trace.Wrap(err)
}
checker, err := services.FetchRoles(user.GetRoles(), a.Access, user.GetTraits())
if err != nil {
return nil, nil, trace.Wrap(err)
}
certs, err := a.generateUserCert(certRequest{
user: user,
roles: checker,
ttl: ttl,
compatibility: compatibility,
publicKey: key,
})
if err != nil {
return nil, nil, trace.Wrap(err)
}
return certs.ssh, certs.tls, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L430-L534 | go | train | // generateUserCert generates user certificates | func (s *AuthServer) generateUserCert(req certRequest) (*certs, error) | // generateUserCert generates user certificates
func (s *AuthServer) generateUserCert(req certRequest) (*certs, error) | {
// reuse the same RSA keys for SSH and TLS keys
cryptoPubKey, err := sshutils.CryptoPublicKey(req.publicKey)
if err != nil {
return nil, trace.Wrap(err)
}
// extract the passed in certificate format. if nothing was passed in, fetch
// the certificate format from the role.
certificateFormat, err := utils.CheckCertificateFormatFlag(req.compatibility)
if err != nil {
return nil, trace.Wrap(err)
}
if certificateFormat == teleport.CertificateFormatUnspecified {
certificateFormat = req.roles.CertificateFormat()
}
var sessionTTL time.Duration
var allowedLogins []string
// If the role TTL is ignored, do not restrict session TTL and allowed logins.
// The only caller setting this parameter should be "tctl auth sign".
// Otherwise set the session TTL to the smallest of all roles and
// then only grant access to allowed logins based on that.
if req.overrideRoleTTL {
// Take whatever was passed in. Pass in 0 to CheckLoginDuration so all
// logins are returned for the role set.
sessionTTL = req.ttl
allowedLogins, err = req.roles.CheckLoginDuration(0)
if err != nil {
return nil, trace.Wrap(err)
}
} else {
// Adjust session TTL to the smaller of two values: the session TTL
// requested in tsh or the session TTL for the role.
sessionTTL = req.roles.AdjustSessionTTL(req.ttl)
// Return a list of logins that meet the session TTL limit. This means if
// the requested session TTL is larger than the max session TTL for a login,
// that login will not be included in the list of allowed logins.
allowedLogins, err = req.roles.CheckLoginDuration(sessionTTL)
if err != nil {
return nil, trace.Wrap(err)
}
}
clusterName, err := s.GetDomainName()
if err != nil {
return nil, trace.Wrap(err)
}
ca, err := s.Trust.GetCertAuthority(services.CertAuthID{
Type: services.UserCA,
DomainName: clusterName,
}, true)
if err != nil {
return nil, trace.Wrap(err)
}
privateKey, err := ca.FirstSigningKey()
if err != nil {
return nil, trace.Wrap(err)
}
sshCert, err := s.Authority.GenerateUserCert(services.UserCertParams{
PrivateCASigningKey: privateKey,
PublicUserKey: req.publicKey,
Username: req.user.GetName(),
AllowedLogins: allowedLogins,
TTL: sessionTTL,
Roles: req.user.GetRoles(),
CertificateFormat: certificateFormat,
PermitPortForwarding: req.roles.CanPortForward(),
PermitAgentForwarding: req.roles.CanForwardAgents(),
})
if err != nil {
return nil, trace.Wrap(err)
}
userCA, err := s.Trust.GetCertAuthority(services.CertAuthID{
Type: services.UserCA,
DomainName: clusterName,
}, true)
if err != nil {
return nil, trace.Wrap(err)
}
// generate TLS certificate
tlsAuthority, err := userCA.TLSCA()
if err != nil {
return nil, trace.Wrap(err)
}
identity := tlsca.Identity{
Username: req.user.GetName(),
Groups: req.roles.RoleNames(),
Principals: allowedLogins,
Usage: req.usage,
}
certRequest := tlsca.CertificateRequest{
Clock: s.clock,
PublicKey: cryptoPubKey,
Subject: identity.Subject(),
NotAfter: s.clock.Now().UTC().Add(sessionTTL),
}
tlsCert, err := tlsAuthority.GenerateCertificate(certRequest)
if err != nil {
return nil, trace.Wrap(err)
}
return &certs{ssh: sshCert, tls: tlsCert}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L543-L594 | go | train | // WithUserLock executes function authenticateFn that performs user authentication
// if authenticateFn returns non nil error, the login attempt will be logged in as failed.
// The only exception to this rule is ConnectionProblemError, in case if it occurs
// access will be denied, but login attempt will not be recorded
// this is done to avoid potential user lockouts due to backend failures
// In case if user exceeds defaults.MaxLoginAttempts
// the user account will be locked for defaults.AccountLockInterval | func (s *AuthServer) WithUserLock(username string, authenticateFn func() error) error | // WithUserLock executes function authenticateFn that performs user authentication
// if authenticateFn returns non nil error, the login attempt will be logged in as failed.
// The only exception to this rule is ConnectionProblemError, in case if it occurs
// access will be denied, but login attempt will not be recorded
// this is done to avoid potential user lockouts due to backend failures
// In case if user exceeds defaults.MaxLoginAttempts
// the user account will be locked for defaults.AccountLockInterval
func (s *AuthServer) WithUserLock(username string, authenticateFn func() error) error | {
user, err := s.Identity.GetUser(username)
if err != nil {
return trace.Wrap(err)
}
status := user.GetStatus()
if status.IsLocked && status.LockExpires.After(s.clock.Now().UTC()) {
return trace.AccessDenied("%v exceeds %v failed login attempts, locked until %v",
user.GetName(), defaults.MaxLoginAttempts, utils.HumanTimeFormat(status.LockExpires))
}
fnErr := authenticateFn()
if fnErr == nil {
// upon successful login, reset the failed attempt counter
err = s.DeleteUserLoginAttempts(username)
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
return nil
}
// do not lock user in case if DB is flaky or down
if trace.IsConnectionProblem(err) {
return trace.Wrap(fnErr)
}
// log failed attempt and possibly lock user
attempt := services.LoginAttempt{Time: s.clock.Now().UTC(), Success: false}
err = s.AddUserLoginAttempt(username, attempt, defaults.AttemptTTL)
if err != nil {
log.Error(trace.DebugReport(err))
return trace.Wrap(fnErr)
}
loginAttempts, err := s.Identity.GetUserLoginAttempts(username)
if err != nil {
log.Error(trace.DebugReport(err))
return trace.Wrap(fnErr)
}
if !services.LastFailed(defaults.MaxLoginAttempts, loginAttempts) {
log.Debugf("%v user has less than %v failed login attempts", username, defaults.MaxLoginAttempts)
return trace.Wrap(fnErr)
}
lockUntil := s.clock.Now().UTC().Add(defaults.AccountLockInterval)
message := fmt.Sprintf("%v exceeds %v failed login attempts, locked until %v",
username, defaults.MaxLoginAttempts, utils.HumanTimeFormat(status.LockExpires))
log.Debug(message)
user.SetLocked(lockUntil, "user has exceeded maximum failed login attempts")
err = s.Identity.UpsertUser(user)
if err != nil {
log.Error(trace.DebugReport(err))
return trace.Wrap(fnErr)
}
return trace.AccessDenied(message)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L598-L607 | go | train | // PreAuthenticatedSignIn is for 2-way authentication methods like U2F where the password is
// already checked before issuing the second factor challenge | func (s *AuthServer) PreAuthenticatedSignIn(user string) (services.WebSession, error) | // PreAuthenticatedSignIn is for 2-way authentication methods like U2F where the password is
// already checked before issuing the second factor challenge
func (s *AuthServer) PreAuthenticatedSignIn(user string) (services.WebSession, error) | {
sess, err := s.NewWebSession(user)
if err != nil {
return nil, trace.Wrap(err)
}
if err := s.UpsertWebSession(user, sess); err != nil {
return nil, trace.Wrap(err)
}
return sess.WithoutSecrets(), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L686-L715 | go | train | // ExtendWebSession creates a new web session for a user based on a valid previous sessionID,
// method is used to renew the web session for a user | func (s *AuthServer) ExtendWebSession(user string, prevSessionID string) (services.WebSession, error) | // ExtendWebSession creates a new web session for a user based on a valid previous sessionID,
// method is used to renew the web session for a user
func (s *AuthServer) ExtendWebSession(user string, prevSessionID string) (services.WebSession, error) | {
prevSession, err := s.GetWebSession(user, prevSessionID)
if err != nil {
return nil, trace.Wrap(err)
}
// consider absolute expiry time that may be set for this session
// by some external identity serivce, so we can not renew this session
// any more without extra logic for renewal with external OIDC provider
expiresAt := prevSession.GetExpiryTime()
if !expiresAt.IsZero() && expiresAt.Before(s.clock.Now().UTC()) {
return nil, trace.NotFound("web session has expired")
}
sess, err := s.NewWebSession(user)
if err != nil {
return nil, trace.Wrap(err)
}
sess.SetExpiryTime(expiresAt)
bearerTokenTTL := utils.MinTTL(utils.ToTTL(s.clock, expiresAt), BearerTokenTTL)
sess.SetBearerTokenExpiryTime(s.clock.Now().UTC().Add(bearerTokenTTL))
if err := s.UpsertWebSession(user, sess); err != nil {
return nil, trace.Wrap(err)
}
sess, err = services.GetWebSessionMarshaler().ExtendWebSession(sess)
if err != nil {
return nil, trace.Wrap(err)
}
return sess, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L719-L732 | go | train | // CreateWebSession creates a new web session for user without any
// checks, is used by admins | func (s *AuthServer) CreateWebSession(user string) (services.WebSession, error) | // CreateWebSession creates a new web session for user without any
// checks, is used by admins
func (s *AuthServer) CreateWebSession(user string) (services.WebSession, error) | {
sess, err := s.NewWebSession(user)
if err != nil {
return nil, trace.Wrap(err)
}
if err := s.UpsertWebSession(user, sess); err != nil {
return nil, trace.Wrap(err)
}
sess, err = services.GetWebSessionMarshaler().GenerateWebSession(sess)
if err != nil {
return nil, trace.Wrap(err)
}
return sess, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L745-L762 | go | train | // CheckAndSetDefaults checks and sets default values of request | func (req *GenerateTokenRequest) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets default values of request
func (req *GenerateTokenRequest) CheckAndSetDefaults() error | {
for _, role := range req.Roles {
if err := role.Check(); err != nil {
return trace.Wrap(err)
}
}
if req.TTL == 0 {
req.TTL = defaults.ProvisioningTokenTTL
}
if req.Token == "" {
token, err := utils.CryptoRandomHex(TokenLenBytes)
if err != nil {
return trace.Wrap(err)
}
req.Token = token
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L765-L777 | go | train | // GenerateToken generates multi-purpose authentication token | func (s *AuthServer) GenerateToken(req GenerateTokenRequest) (string, error) | // GenerateToken generates multi-purpose authentication token
func (s *AuthServer) GenerateToken(req GenerateTokenRequest) (string, error) | {
if err := req.CheckAndSetDefaults(); err != nil {
return "", trace.Wrap(err)
}
token, err := services.NewProvisionToken(req.Token, req.Roles, s.clock.Now().UTC().Add(req.TTL))
if err != nil {
return "", trace.Wrap(err)
}
if err := s.Provisioner.UpsertToken(token); err != nil {
return "", trace.Wrap(err)
}
return req.Token, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L780-L786 | go | train | // ExtractHostID returns host id based on the hostname | func ExtractHostID(hostName string, clusterName string) (string, error) | // ExtractHostID returns host id based on the hostname
func ExtractHostID(hostName string, clusterName string) (string, error) | {
suffix := "." + clusterName
if !strings.HasSuffix(hostName, suffix) {
return "", trace.BadParameter("expected suffix %q in %q", suffix, hostName)
}
return strings.TrimSuffix(hostName, suffix), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L828-L836 | go | train | // CheckAndSetDefaults checks and sets default values | func (req *GenerateServerKeysRequest) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and sets default values
func (req *GenerateServerKeysRequest) CheckAndSetDefaults() error | {
if req.HostID == "" {
return trace.BadParameter("missing parameter HostID")
}
if len(req.Roles) != 1 {
return trace.BadParameter("expected only one system role, got %v", len(req.Roles))
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L840-L988 | go | train | // GenerateServerKeys generates new host private keys and certificates (signed
// by the host certificate authority) for a node. | func (s *AuthServer) GenerateServerKeys(req GenerateServerKeysRequest) (*PackedKeys, error) | // GenerateServerKeys generates new host private keys and certificates (signed
// by the host certificate authority) for a node.
func (s *AuthServer) GenerateServerKeys(req GenerateServerKeysRequest) (*PackedKeys, error) | {
if err := req.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
if err := s.limiter.AcquireConnection(req.Roles.String()); err != nil {
generateThrottledRequestsCount.Inc()
log.Debugf("Node %q [%v] is rate limited: %v.", req.NodeName, req.HostID, req.Roles)
return nil, trace.Wrap(err)
}
defer s.limiter.ReleaseConnection(req.Roles.String())
// only observe latencies for non-throttled requests
start := s.clock.Now()
defer generateRequestsLatencies.Observe(time.Since(start).Seconds())
generateRequestsCount.Inc()
generateRequestsCurrent.Inc()
defer generateRequestsCurrent.Dec()
clusterName, err := s.GetClusterName()
if err != nil {
return nil, trace.Wrap(err)
}
// If the request contains 0.0.0.0, this implies an advertise IP was not
// specified on the node. Try and guess what the address by replacing 0.0.0.0
// with the RemoteAddr as known to the Auth Server.
req.AdditionalPrincipals = utils.ReplaceInSlice(
req.AdditionalPrincipals,
defaults.AnyAddress,
req.RemoteAddr)
var cryptoPubKey crypto.PublicKey
var privateKeyPEM, pubSSHKey []byte
if req.PublicSSHKey != nil || req.PublicTLSKey != nil {
_, _, _, _, err := ssh.ParseAuthorizedKey(req.PublicSSHKey)
if err != nil {
return nil, trace.BadParameter("failed to parse SSH public key")
}
pubSSHKey = req.PublicSSHKey
cryptoPubKey, err = tlsca.ParsePublicKeyPEM(req.PublicTLSKey)
if err != nil {
return nil, trace.Wrap(err)
}
} else {
// generate private key
privateKeyPEM, pubSSHKey, err = s.GenerateKeyPair("")
if err != nil {
return nil, trace.Wrap(err)
}
// reuse the same RSA keys for SSH and TLS keys
cryptoPubKey, err = sshutils.CryptoPublicKey(pubSSHKey)
if err != nil {
return nil, trace.Wrap(err)
}
}
// get the certificate authority that will be signing the public key of the host,
client := s.GetCache()
if req.NoCache {
client = &s.AuthServices
}
ca, err := client.GetCertAuthority(services.CertAuthID{
Type: services.HostCA,
DomainName: clusterName.GetClusterName(),
}, true)
if err != nil {
return nil, trace.BadParameter("failed to load host CA for %q: %v", clusterName.GetClusterName(), err)
}
// could be a couple of scenarios, either client data is out of sync,
// or auth server is out of sync, either way, for now check that
// cache is out of sync, this will result in higher read rate
// to the backend, which is a fine tradeoff
if !req.NoCache && req.Rotation != nil && !req.Rotation.Matches(ca.GetRotation()) {
log.Debugf("Client sent rotation state %v, cache state is %v, using state from the DB.", req.Rotation, ca.GetRotation())
ca, err = s.GetCertAuthority(services.CertAuthID{
Type: services.HostCA,
DomainName: clusterName.GetClusterName(),
}, true)
if err != nil {
return nil, trace.BadParameter("failed to load host CA for %q: %v", clusterName.GetClusterName(), err)
}
if !req.Rotation.Matches(ca.GetRotation()) {
return nil, trace.BadParameter("the client expected state is out of sync, server rotation state: %v, client rotation state: %v, re-register the client from scratch to fix the issue.", ca.GetRotation(), req.Rotation)
}
}
tlsAuthority, err := ca.TLSCA()
if err != nil {
return nil, trace.Wrap(err)
}
// get the private key of the certificate authority
caPrivateKey, err := ca.FirstSigningKey()
if err != nil {
return nil, trace.Wrap(err)
}
// generate hostSSH certificate
hostSSHCert, err := s.Authority.GenerateHostCert(services.HostCertParams{
PrivateCASigningKey: caPrivateKey,
PublicHostKey: pubSSHKey,
HostID: req.HostID,
NodeName: req.NodeName,
ClusterName: clusterName.GetClusterName(),
Roles: req.Roles,
Principals: req.AdditionalPrincipals,
})
if err != nil {
return nil, trace.Wrap(err)
}
// generate host TLS certificate
identity := tlsca.Identity{
Username: HostFQDN(req.HostID, clusterName.GetClusterName()),
Groups: req.Roles.StringSlice(),
}
certRequest := tlsca.CertificateRequest{
Clock: s.clock,
PublicKey: cryptoPubKey,
Subject: identity.Subject(),
NotAfter: s.clock.Now().UTC().Add(defaults.CATTL),
DNSNames: append([]string{}, req.AdditionalPrincipals...),
}
// HTTPS requests need to specify DNS name that should be present in the
// certificate as one of the DNS Names. It is not known in advance,
// that is why there is a default one for all certificates
if req.Roles.Include(teleport.RoleAuth) || req.Roles.Include(teleport.RoleAdmin) {
certRequest.DNSNames = append(certRequest.DNSNames, "*."+teleport.APIDomain, teleport.APIDomain)
}
// Unlike additional pricinpals, DNS Names is x509 specific
// and is limited to auth servers and proxies
if req.Roles.Include(teleport.RoleAuth) || req.Roles.Include(teleport.RoleAdmin) || req.Roles.Include(teleport.RoleProxy) {
certRequest.DNSNames = append(certRequest.DNSNames, req.DNSNames...)
}
hostTLSCert, err := tlsAuthority.GenerateCertificate(certRequest)
if err != nil {
return nil, trace.Wrap(err)
}
return &PackedKeys{
Key: privateKeyPEM,
Cert: hostSSHCert,
TLSCert: hostTLSCert,
TLSCACerts: services.TLSCerts(ca),
SSHCACerts: ca.GetCheckingKeys(),
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L993-L1018 | go | train | // ValidateToken takes a provisioning token value and finds if it's valid. Returns
// a list of roles this token allows its owner to assume, or an error if the token
// cannot be found. | func (s *AuthServer) ValidateToken(token string) (roles teleport.Roles, e error) | // ValidateToken takes a provisioning token value and finds if it's valid. Returns
// a list of roles this token allows its owner to assume, or an error if the token
// cannot be found.
func (s *AuthServer) ValidateToken(token string) (roles teleport.Roles, e error) | {
tkns, err := s.GetCache().GetStaticTokens()
if err != nil {
return nil, trace.Wrap(err)
}
// First check if the token is a static token. If it is, return right away.
// Static tokens have no expiration.
for _, st := range tkns.GetStaticTokens() {
if st.GetName() == token {
return st.GetRoles(), nil
}
}
// If it's not a static token, check if it's a ephemeral token in the backend.
// If a ephemeral token is found, make sure it's still valid.
tok, err := s.GetCache().GetToken(token)
if err != nil {
return nil, trace.Wrap(err)
}
if !s.checkTokenTTL(tok) {
return nil, trace.AccessDenied("token expired")
}
return tok.GetRoles(), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1022-L1034 | go | train | // checkTokenTTL checks if the token is still valid. If it is not, the token
// is removed from the backend and returns false. Otherwise returns true. | func (s *AuthServer) checkTokenTTL(tok services.ProvisionToken) bool | // checkTokenTTL checks if the token is still valid. If it is not, the token
// is removed from the backend and returns false. Otherwise returns true.
func (s *AuthServer) checkTokenTTL(tok services.ProvisionToken) bool | {
now := s.clock.Now().UTC()
if tok.Expiry().Before(now) {
err := s.DeleteToken(tok.GetName())
if err != nil {
if !trace.IsNotFound(err) {
log.Warnf("Unable to delete token from backend: %v.", err)
}
}
return false
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1064-L1075 | go | train | // CheckAndSetDefaults checks for errors and sets defaults | func (r *RegisterUsingTokenRequest) CheckAndSetDefaults() error | // CheckAndSetDefaults checks for errors and sets defaults
func (r *RegisterUsingTokenRequest) CheckAndSetDefaults() error | {
if r.HostID == "" {
return trace.BadParameter("missing parameter HostID")
}
if r.Token == "" {
return trace.BadParameter("missing parameter Token")
}
if err := r.Role.Check(); err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1084-L1121 | go | train | // RegisterUsingToken adds a new node to the Teleport cluster using previously issued token.
// A node must also request a specific role (and the role must match one of the roles
// the token was generated for).
//
// If a token was generated with a TTL, it gets enforced (can't register new nodes after TTL expires)
// If a token was generated with a TTL=0, it means it's a single-use token and it gets destroyed
// after a successful registration. | func (s *AuthServer) RegisterUsingToken(req RegisterUsingTokenRequest) (*PackedKeys, error) | // RegisterUsingToken adds a new node to the Teleport cluster using previously issued token.
// A node must also request a specific role (and the role must match one of the roles
// the token was generated for).
//
// If a token was generated with a TTL, it gets enforced (can't register new nodes after TTL expires)
// If a token was generated with a TTL=0, it means it's a single-use token and it gets destroyed
// after a successful registration.
func (s *AuthServer) RegisterUsingToken(req RegisterUsingTokenRequest) (*PackedKeys, error) | {
log.Infof("Node %q [%v] is trying to join with role: %v.", req.NodeName, req.HostID, req.Role)
if err := req.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
// make sure the token is valid
roles, err := s.ValidateToken(req.Token)
if err != nil {
log.Warningf("%q [%v] can not join the cluster with role %s, token error: %v", req.NodeName, req.HostID, req.Role, err)
return nil, trace.AccessDenied(fmt.Sprintf("%q [%v] can not join the cluster with role %s, the token is not valid", req.NodeName, req.HostID, req.Role))
}
// make sure the caller is requested the role allowed by the token
if !roles.Include(req.Role) {
msg := fmt.Sprintf("node %q [%v] can not join the cluster, the token does not allow %q role", req.NodeName, req.HostID, req.Role)
log.Warn(msg)
return nil, trace.BadParameter(msg)
}
// generate and return host certificate and keys
keys, err := s.GenerateServerKeys(GenerateServerKeysRequest{
HostID: req.HostID,
NodeName: req.NodeName,
Roles: teleport.Roles{req.Role},
AdditionalPrincipals: req.AdditionalPrincipals,
PublicTLSKey: req.PublicTLSKey,
PublicSSHKey: req.PublicSSHKey,
RemoteAddr: req.RemoteAddr,
DNSNames: req.DNSNames,
})
if err != nil {
return nil, trace.Wrap(err)
}
log.Infof("Node %q [%v] has joined the cluster.", req.NodeName, req.HostID)
return keys, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1162-L1191 | go | train | // GetTokens returns all tokens (machine provisioning ones and user invitation tokens). Machine
// tokens usually have "node roles", like auth,proxy,node and user invitation tokens have 'signup' role | func (s *AuthServer) GetTokens(opts ...services.MarshalOption) (tokens []services.ProvisionToken, err error) | // GetTokens returns all tokens (machine provisioning ones and user invitation tokens). Machine
// tokens usually have "node roles", like auth,proxy,node and user invitation tokens have 'signup' role
func (s *AuthServer) GetTokens(opts ...services.MarshalOption) (tokens []services.ProvisionToken, err error) | {
// get node tokens:
tokens, err = s.Provisioner.GetTokens()
if err != nil {
return nil, trace.Wrap(err)
}
// get static tokens:
tkns, err := s.GetStaticTokens()
if err != nil && !trace.IsNotFound(err) {
return nil, trace.Wrap(err)
}
if err == nil {
tokens = append(tokens, tkns.GetStaticTokens()...)
}
// get user tokens:
userTokens, err := s.Identity.GetSignupTokens()
if err != nil {
return nil, trace.Wrap(err)
}
// convert user tokens to machine tokens:
for _, t := range userTokens {
roles := teleport.Roles{teleport.RoleSignup}
tok, err := services.NewProvisionToken(t.Token, roles, t.Expires)
if err != nil {
return nil, trace.Wrap(err)
}
tokens = append(tokens, tok)
}
return tokens, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1274-L1276 | go | train | // NewWatcher returns a new event watcher. In case of an auth server
// this watcher will return events as seen by the auth server's
// in memory cache, not the backend. | func (a *AuthServer) NewWatcher(ctx context.Context, watch services.Watch) (services.Watcher, error) | // NewWatcher returns a new event watcher. In case of an auth server
// this watcher will return events as seen by the auth server's
// in memory cache, not the backend.
func (a *AuthServer) NewWatcher(ctx context.Context, watch services.Watch) (services.Watcher, error) | {
return a.GetCache().NewWatcher(ctx, watch)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1308-L1318 | go | train | // NewKeepAliver returns a new instance of keep aliver | func (a *AuthServer) NewKeepAliver(ctx context.Context) (services.KeepAliver, error) | // NewKeepAliver returns a new instance of keep aliver
func (a *AuthServer) NewKeepAliver(ctx context.Context) (services.KeepAliver, error) | {
cancelCtx, cancel := context.WithCancel(ctx)
k := &authKeepAliver{
a: a,
ctx: cancelCtx,
cancel: cancel,
keepAlivesC: make(chan services.KeepAlive),
}
go k.forwardKeepAlives()
return k, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1322-L1324 | go | train | // GetCertAuthority returns certificate authority by given id. Parameter loadSigningKeys
// controls if signing keys are loaded | func (a *AuthServer) GetCertAuthority(id services.CertAuthID, loadSigningKeys bool, opts ...services.MarshalOption) (services.CertAuthority, error) | // GetCertAuthority returns certificate authority by given id. Parameter loadSigningKeys
// controls if signing keys are loaded
func (a *AuthServer) GetCertAuthority(id services.CertAuthID, loadSigningKeys bool, opts ...services.MarshalOption) (services.CertAuthority, error) | {
return a.GetCache().GetCertAuthority(id, loadSigningKeys, opts...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1328-L1330 | go | train | // GetCertAuthorities returns a list of authorities of a given type
// loadSigningKeys controls whether signing keys should be loaded or not | func (a *AuthServer) GetCertAuthorities(caType services.CertAuthType, loadSigningKeys bool, opts ...services.MarshalOption) ([]services.CertAuthority, error) | // GetCertAuthorities returns a list of authorities of a given type
// loadSigningKeys controls whether signing keys should be loaded or not
func (a *AuthServer) GetCertAuthorities(caType services.CertAuthType, loadSigningKeys bool, opts ...services.MarshalOption) ([]services.CertAuthority, error) | {
return a.GetCache().GetCertAuthorities(caType, loadSigningKeys, opts...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1338-L1340 | go | train | // GetToken finds and returns token by ID | func (a *AuthServer) GetToken(token string) (services.ProvisionToken, error) | // GetToken finds and returns token by ID
func (a *AuthServer) GetToken(token string) (services.ProvisionToken, error) | {
return a.GetCache().GetToken(token)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1348-L1350 | go | train | // GetRole is a part of auth.AccessPoint implementation | func (a *AuthServer) GetRole(name string) (services.Role, error) | // GetRole is a part of auth.AccessPoint implementation
func (a *AuthServer) GetRole(name string) (services.Role, error) | {
return a.GetCache().GetRole(name)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1353-L1355 | go | train | // GetNamespace returns namespace | func (a *AuthServer) GetNamespace(name string) (*services.Namespace, error) | // GetNamespace returns namespace
func (a *AuthServer) GetNamespace(name string) (*services.Namespace, error) | {
return a.GetCache().GetNamespace(name)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1363-L1365 | go | train | // GetNodes is a part of auth.AccessPoint implementation | func (a *AuthServer) GetNodes(namespace string, opts ...services.MarshalOption) ([]services.Server, error) | // GetNodes is a part of auth.AccessPoint implementation
func (a *AuthServer) GetNodes(namespace string, opts ...services.MarshalOption) ([]services.Server, error) | {
return a.GetCache().GetNodes(namespace, opts...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1368-L1370 | go | train | // GetReverseTunnels is a part of auth.AccessPoint implementation | func (a *AuthServer) GetReverseTunnels(opts ...services.MarshalOption) ([]services.ReverseTunnel, error) | // GetReverseTunnels is a part of auth.AccessPoint implementation
func (a *AuthServer) GetReverseTunnels(opts ...services.MarshalOption) ([]services.ReverseTunnel, error) | {
return a.GetCache().GetReverseTunnels(opts...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1378-L1380 | go | train | // GetUser is a part of auth.AccessPoint implementation. | func (a *AuthServer) GetUser(name string) (user services.User, err error) | // GetUser is a part of auth.AccessPoint implementation.
func (a *AuthServer) GetUser(name string) (user services.User, err error) | {
return a.GetCache().GetUser(name)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1383-L1385 | go | train | // GetUsers is a part of auth.AccessPoint implementation | func (a *AuthServer) GetUsers() (users []services.User, err error) | // GetUsers is a part of auth.AccessPoint implementation
func (a *AuthServer) GetUsers() (users []services.User, err error) | {
return a.GetCache().GetUsers()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1390-L1392 | go | train | // GetTunnelConnections is a part of auth.AccessPoint implementation
// GetTunnelConnections are not using recent cache as they are designed
// to be called periodically and always return fresh data | func (a *AuthServer) GetTunnelConnections(clusterName string, opts ...services.MarshalOption) ([]services.TunnelConnection, error) | // GetTunnelConnections is a part of auth.AccessPoint implementation
// GetTunnelConnections are not using recent cache as they are designed
// to be called periodically and always return fresh data
func (a *AuthServer) GetTunnelConnections(clusterName string, opts ...services.MarshalOption) ([]services.TunnelConnection, error) | {
return a.GetCache().GetTunnelConnections(clusterName, opts...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1397-L1399 | go | train | // GetAllTunnelConnections is a part of auth.AccessPoint implementation
// GetAllTunnelConnections are not using recent cache, as they are designed
// to be called periodically and always return fresh data | func (a *AuthServer) GetAllTunnelConnections(opts ...services.MarshalOption) (conns []services.TunnelConnection, err error) | // GetAllTunnelConnections is a part of auth.AccessPoint implementation
// GetAllTunnelConnections are not using recent cache, as they are designed
// to be called periodically and always return fresh data
func (a *AuthServer) GetAllTunnelConnections(opts ...services.MarshalOption) (conns []services.TunnelConnection, err error) | {
return a.GetCache().GetAllTunnelConnections(opts...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1443-L1447 | go | train | // Error returns the error if keep aliver
// has been closed | func (k *authKeepAliver) Error() error | // Error returns the error if keep aliver
// has been closed
func (k *authKeepAliver) Error() error | {
k.RLock()
defer k.RUnlock()
return k.err
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1488-L1507 | go | train | // oidcConfigsEqual returns true if the provided OIDC configs are equal | func oidcConfigsEqual(a, b oidc.ClientConfig) bool | // oidcConfigsEqual returns true if the provided OIDC configs are equal
func oidcConfigsEqual(a, b oidc.ClientConfig) bool | {
if a.RedirectURL != b.RedirectURL {
return false
}
if a.Credentials.ID != b.Credentials.ID {
return false
}
if a.Credentials.Secret != b.Credentials.Secret {
return false
}
if len(a.Scope) != len(b.Scope) {
return false
}
for i := range a.Scope {
if a.Scope[i] != b.Scope[i] {
return false
}
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1510-L1538 | go | train | // oauth2ConfigsEqual returns true if the provided OAuth2 configs are equal | func oauth2ConfigsEqual(a, b oauth2.Config) bool | // oauth2ConfigsEqual returns true if the provided OAuth2 configs are equal
func oauth2ConfigsEqual(a, b oauth2.Config) bool | {
if a.Credentials.ID != b.Credentials.ID {
return false
}
if a.Credentials.Secret != b.Credentials.Secret {
return false
}
if a.RedirectURL != b.RedirectURL {
return false
}
if len(a.Scope) != len(b.Scope) {
return false
}
for i := range a.Scope {
if a.Scope[i] != b.Scope[i] {
return false
}
}
if a.AuthURL != b.AuthURL {
return false
}
if a.TokenURL != b.TokenURL {
return false
}
if a.AuthMethod != b.AuthMethod {
return false
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/auth.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/auth.go#L1541-L1551 | go | train | // isHTTPS checks if the scheme for a URL is https or not. | func isHTTPS(u string) error | // isHTTPS checks if the scheme for a URL is https or not.
func isHTTPS(u string) error | {
earl, err := url.Parse(u)
if err != nil {
return trace.Wrap(err)
}
if earl.Scheme != "https" {
return trace.BadParameter("expected scheme https, got %q", earl.Scheme)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L92-L102 | go | train | // NewOIDCConnector returns a new OIDCConnector based off a name and OIDCConnectorSpecV2. | func NewOIDCConnector(name string, spec OIDCConnectorSpecV2) OIDCConnector | // NewOIDCConnector returns a new OIDCConnector based off a name and OIDCConnectorSpecV2.
func NewOIDCConnector(name string, spec OIDCConnectorSpecV2) OIDCConnector | {
return &OIDCConnectorV2{
Kind: KindOIDCConnector,
Version: V2,
Metadata: Metadata{
Name: name,
Namespace: defaults.Namespace,
},
Spec: spec,
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L137-L180 | go | train | // UnmarshalOIDCConnector unmarshals connector from | func (*TeleportOIDCConnectorMarshaler) UnmarshalOIDCConnector(bytes []byte, opts ...MarshalOption) (OIDCConnector, error) | // UnmarshalOIDCConnector unmarshals connector from
func (*TeleportOIDCConnectorMarshaler) UnmarshalOIDCConnector(bytes []byte, opts ...MarshalOption) (OIDCConnector, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
var h ResourceHeader
err = utils.FastUnmarshal(bytes, &h)
if err != nil {
return nil, trace.Wrap(err)
}
switch h.Version {
case "":
var c OIDCConnectorV1
err := json.Unmarshal(bytes, &c)
if err != nil {
return nil, trace.Wrap(err)
}
return c.V2(), nil
case V2:
var c OIDCConnectorV2
if cfg.SkipValidation {
if err := utils.FastUnmarshal(bytes, &c); err != nil {
return nil, trace.BadParameter(err.Error())
}
} else {
if err := utils.UnmarshalWithSchema(GetOIDCConnectorSchema(), &c, bytes); err != nil {
return nil, trace.BadParameter(err.Error())
}
}
if err := c.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
if cfg.ID != 0 {
c.SetResourceID(cfg.ID)
}
if !cfg.Expires.IsZero() {
c.SetExpiry(cfg.Expires)
}
return &c, nil
}
return nil, trace.BadParameter("OIDC connector resource version %v is not supported", h.Version)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L183-L220 | go | train | // MarshalUser marshals OIDC connector into JSON | func (*TeleportOIDCConnectorMarshaler) MarshalOIDCConnector(c OIDCConnector, opts ...MarshalOption) ([]byte, error) | // MarshalUser marshals OIDC connector into JSON
func (*TeleportOIDCConnectorMarshaler) MarshalOIDCConnector(c OIDCConnector, opts ...MarshalOption) ([]byte, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
type connv1 interface {
V1() *OIDCConnectorV1
}
type connv2 interface {
V2() *OIDCConnectorV2
}
version := cfg.GetVersion()
switch version {
case V1:
v, ok := c.(connv1)
if !ok {
return nil, trace.BadParameter("don't know how to marshal %v", V1)
}
return json.Marshal(v.V1())
case V2:
v, ok := c.(connv2)
if !ok {
return nil, trace.BadParameter("don't know how to marshal %v", V2)
}
v2 := v.V2()
if !cfg.PreserveResourceID {
// avoid modifying the original object
// to prevent unexpected data races
copy := *v2
copy.SetResourceID(0)
v2 = ©
}
return utils.FastMarshal(v2)
default:
return nil, trace.BadParameter("version %v is not supported", version)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L272-L283 | go | train | // V1 converts OIDCConnectorV2 to OIDCConnectorV1 format | func (o *OIDCConnectorV2) V1() *OIDCConnectorV1 | // V1 converts OIDCConnectorV2 to OIDCConnectorV1 format
func (o *OIDCConnectorV2) V1() *OIDCConnectorV1 | {
return &OIDCConnectorV1{
ID: o.Metadata.Name,
IssuerURL: o.Spec.IssuerURL,
ClientID: o.Spec.ClientID,
ClientSecret: o.Spec.ClientSecret,
RedirectURL: o.Spec.RedirectURL,
Display: o.Spec.Display,
Scope: o.Spec.Scope,
ClaimsToRoles: o.Spec.ClaimsToRoles,
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L296-L298 | go | train | // SetExpiry sets expiry time for the object | func (o *OIDCConnectorV2) SetExpiry(expires time.Time) | // SetExpiry sets expiry time for the object
func (o *OIDCConnectorV2) SetExpiry(expires time.Time) | {
o.Metadata.SetExpiry(expires)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L306-L308 | go | train | // SetTTL sets Expires header using realtime clock | func (o *OIDCConnectorV2) SetTTL(clock clockwork.Clock, ttl time.Duration) | // SetTTL sets Expires header using realtime clock
func (o *OIDCConnectorV2) SetTTL(clock clockwork.Clock, ttl time.Duration) | {
o.Metadata.SetTTL(clock, ttl)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L394-L399 | go | train | // Display - Friendly name for this provider. | func (o *OIDCConnectorV2) GetDisplay() string | // Display - Friendly name for this provider.
func (o *OIDCConnectorV2) GetDisplay() string | {
if o.Spec.Display != "" {
return o.Spec.Display
}
return o.GetName()
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L412-L418 | go | train | // GetClaims returns list of claims expected by mappings | func (o *OIDCConnectorV2) GetClaims() []string | // GetClaims returns list of claims expected by mappings
func (o *OIDCConnectorV2) GetClaims() []string | {
var out []string
for _, mapping := range o.Spec.ClaimsToRoles {
out = append(out, mapping.Claim)
}
return utils.Deduplicate(out)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L421-L456 | go | train | // MapClaims maps claims to roles | func (o *OIDCConnectorV2) MapClaims(claims jose.Claims) []string | // MapClaims maps claims to roles
func (o *OIDCConnectorV2) MapClaims(claims jose.Claims) []string | {
var roles []string
for _, mapping := range o.Spec.ClaimsToRoles {
for claimName := range claims {
if claimName != mapping.Claim {
continue
}
var claimValues []string
claimValue, ok, _ := claims.StringClaim(claimName)
if ok {
claimValues = []string{claimValue}
} else {
claimValues, _, _ = claims.StringsClaim(claimName)
}
claimLoop:
for _, claimValue := range claimValues {
for _, role := range mapping.Roles {
outRole, err := utils.ReplaceRegexp(mapping.Value, role, claimValue)
switch {
case err != nil:
if trace.IsNotFound(err) {
log.Debugf("Failed to match expression %v, replace with: %v input: %v, err: %v", mapping.Value, role, claimValue, err)
}
// this claim value clearly did not match, move on to another
continue claimLoop
// skip empty replacement or empty role
case outRole == "":
case outRole != "":
roles = append(roles, outRole)
}
}
}
}
}
return utils.Deduplicate(roles)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L493-L529 | go | train | // Check returns nil if all parameters are great, err otherwise | func (o *OIDCConnectorV2) Check() error | // Check returns nil if all parameters are great, err otherwise
func (o *OIDCConnectorV2) Check() error | {
if o.Metadata.Name == "" {
return trace.BadParameter("ID: missing connector name")
}
if o.Metadata.Name == teleport.Local {
return trace.BadParameter("ID: invalid connector name %v is a reserved name", teleport.Local)
}
if _, err := url.Parse(o.Spec.IssuerURL); err != nil {
return trace.BadParameter("IssuerURL: bad url: '%v'", o.Spec.IssuerURL)
}
if _, err := url.Parse(o.Spec.RedirectURL); err != nil {
return trace.BadParameter("RedirectURL: bad url: '%v'", o.Spec.RedirectURL)
}
if o.Spec.ClientID == "" {
return trace.BadParameter("ClientID: missing client id")
}
// make sure claim mappings have either roles or a role template
for _, v := range o.Spec.ClaimsToRoles {
hasRoles := false
if len(v.Roles) > 0 {
hasRoles = true
}
hasRoleTemplate := false
if v.RoleTemplate != nil {
hasRoleTemplate = true
}
// we either need to have roles or role templates not both or neither
// ! ( hasRoles XOR hasRoleTemplate )
if hasRoles == hasRoleTemplate {
return trace.BadParameter("need roles or role template (not both or none)")
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L532-L544 | go | train | // CheckAndSetDefaults checks and set default values for any missing fields. | func (o *OIDCConnectorV2) CheckAndSetDefaults() error | // CheckAndSetDefaults checks and set default values for any missing fields.
func (o *OIDCConnectorV2) CheckAndSetDefaults() error | {
err := o.Metadata.CheckAndSetDefaults()
if err != nil {
return trace.Wrap(err)
}
err = o.Check()
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L613-L619 | go | train | // GetClaimNames returns a list of claim names from the claim values | func GetClaimNames(claims jose.Claims) []string | // GetClaimNames returns a list of claim names from the claim values
func GetClaimNames(claims jose.Claims) []string | {
var out []string
for claim := range claims {
out = append(out, claim)
}
return out
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/oidc.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/oidc.go#L682-L699 | go | train | // V2 returns V2 version of the connector | func (o *OIDCConnectorV1) V2() *OIDCConnectorV2 | // V2 returns V2 version of the connector
func (o *OIDCConnectorV1) V2() *OIDCConnectorV2 | {
return &OIDCConnectorV2{
Kind: KindOIDCConnector,
Version: V2,
Metadata: Metadata{
Name: o.ID,
},
Spec: OIDCConnectorSpecV2{
IssuerURL: o.IssuerURL,
ClientID: o.ClientID,
ClientSecret: o.ClientSecret,
RedirectURL: o.RedirectURL,
Display: o.Display,
Scope: o.Scope,
ClaimsToRoles: o.ClaimsToRoles,
},
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/checker.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/checker.go#L43-L55 | go | train | // Authenticate checks the validity of a user certificate.
// a value for ServerConfig.PublicKeyCallback. | func (c *CertChecker) Authenticate(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) | // Authenticate checks the validity of a user certificate.
// a value for ServerConfig.PublicKeyCallback.
func (c *CertChecker) Authenticate(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) | {
err := validate(key)
if err != nil {
return nil, trace.Wrap(err)
}
perms, err := c.CertChecker.Authenticate(conn, key)
if err != nil {
return nil, trace.Wrap(err)
}
return perms, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/checker.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/checker.go#L58-L65 | go | train | // CheckCert checks certificate metadata and signature. | func (c *CertChecker) CheckCert(principal string, cert *ssh.Certificate) error | // CheckCert checks certificate metadata and signature.
func (c *CertChecker) CheckCert(principal string, cert *ssh.Certificate) error | {
err := validate(cert)
if err != nil {
return trace.Wrap(err)
}
return c.CertChecker.CheckCert(principal, cert)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/checker.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/checker.go#L68-L75 | go | train | // CheckHostKey checks the validity of a host certificate. | func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key ssh.PublicKey) error | // CheckHostKey checks the validity of a host certificate.
func (c *CertChecker) CheckHostKey(addr string, remote net.Addr, key ssh.PublicKey) error | {
err := validate(key)
if err != nil {
return trace.Wrap(err)
}
return c.CertChecker.CheckHostKey(addr, remote, key)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/checker.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/checker.go#L111-L128 | go | train | // CreateCertificate creates a valid 2048-bit RSA certificate. | func CreateCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error) | // CreateCertificate creates a valid 2048-bit RSA certificate.
func CreateCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error) | {
// Create RSA key for CA and certificate to be signed by CA.
caKey, err := rsa.GenerateKey(rand.Reader, teleport.RSAKeySize)
if err != nil {
return nil, nil, trace.Wrap(err)
}
key, err := rsa.GenerateKey(rand.Reader, teleport.RSAKeySize)
if err != nil {
return nil, nil, trace.Wrap(err)
}
cert, certSigner, err := createCertificate(principal, certType, caKey, key)
if err != nil {
return nil, nil, trace.Wrap(err)
}
return cert, certSigner, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/checker.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/checker.go#L133-L150 | go | train | // CreateEllipticCertificate creates a valid, but not supported, ECDSA
// SSH certificate. This certificate is used to make sure Teleport rejects
// such certificates. | func CreateEllipticCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error) | // CreateEllipticCertificate creates a valid, but not supported, ECDSA
// SSH certificate. This certificate is used to make sure Teleport rejects
// such certificates.
func CreateEllipticCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error) | {
// Create ECDSA key for CA and certificate to be signed by CA.
caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, trace.Wrap(err)
}
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return nil, nil, trace.Wrap(err)
}
cert, certSigner, err := createCertificate(principal, certType, caKey, key)
if err != nil {
return nil, nil, trace.Wrap(err)
}
return cert, certSigner, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/checker.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/checker.go#L155-L196 | go | train | // createCertificate creates a SSH certificate for the given key signed by the
// given CA key. This function exists here to allow easy key generation for
// some of the more core packages like "sshutils". | func createCertificate(principal string, certType uint32, caKey crypto.Signer, key crypto.Signer) (*ssh.Certificate, ssh.Signer, error) | // createCertificate creates a SSH certificate for the given key signed by the
// given CA key. This function exists here to allow easy key generation for
// some of the more core packages like "sshutils".
func createCertificate(principal string, certType uint32, caKey crypto.Signer, key crypto.Signer) (*ssh.Certificate, ssh.Signer, error) | {
// Create CA.
caPublicKey, err := ssh.NewPublicKey(caKey.Public())
if err != nil {
return nil, nil, trace.Wrap(err)
}
caSigner, err := ssh.NewSignerFromKey(caKey)
if err != nil {
return nil, nil, trace.Wrap(err)
}
// Create key.
publicKey, err := ssh.NewPublicKey(key.Public())
if err != nil {
return nil, nil, trace.Wrap(err)
}
keySigner, err := ssh.NewSignerFromKey(key)
if err != nil {
return nil, nil, trace.Wrap(err)
}
// Create certificate and signer.
cert := &ssh.Certificate{
KeyId: principal,
ValidPrincipals: []string{principal},
Key: publicKey,
SignatureKey: caPublicKey,
ValidAfter: uint64(time.Now().UTC().Add(-1 * time.Minute).Unix()),
ValidBefore: uint64(time.Now().UTC().Add(1 * time.Minute).Unix()),
CertType: certType,
}
err = cert.SignCert(rand.Reader, caSigner)
if err != nil {
return nil, nil, trace.Wrap(err)
}
certSigner, err := ssh.NewCertSigner(cert, keySigner)
if err != nil {
return nil, nil, trace.Wrap(err)
}
return cert, certSigner, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/apiserver.go#L57-L234 | go | train | // NewAPIServer returns a new instance of APIServer HTTP handler | func NewAPIServer(config *APIConfig) http.Handler | // NewAPIServer returns a new instance of APIServer HTTP handler
func NewAPIServer(config *APIConfig) http.Handler | {
srv := APIServer{
APIConfig: *config,
Clock: clockwork.NewRealClock(),
}
srv.Router = *httprouter.New()
// Kubernetes extensions
srv.POST("/:version/kube/csr", srv.withAuth(srv.processKubeCSR))
// Operations on certificate authorities
srv.GET("/:version/domain", srv.withAuth(srv.getDomainName))
srv.GET("/:version/cacert", srv.withAuth(srv.getClusterCACert))
srv.POST("/:version/authorities/:type", srv.withAuth(srv.upsertCertAuthority))
srv.POST("/:version/authorities/:type/rotate", srv.withAuth(srv.rotateCertAuthority))
srv.POST("/:version/authorities/:type/rotate/external", srv.withAuth(srv.rotateExternalCertAuthority))
srv.DELETE("/:version/authorities/:type/:domain", srv.withAuth(srv.deleteCertAuthority))
srv.GET("/:version/authorities/:type/:domain", srv.withAuth(srv.getCertAuthority))
srv.GET("/:version/authorities/:type", srv.withAuth(srv.getCertAuthorities))
// Generating certificates for user and host authorities
srv.POST("/:version/ca/host/certs", srv.withAuth(srv.generateHostCert))
srv.POST("/:version/ca/user/certs", srv.withAuth(srv.generateUserCert))
// Operations on users
srv.GET("/:version/users", srv.withAuth(srv.getUsers))
srv.GET("/:version/users/:user", srv.withAuth(srv.getUser))
srv.DELETE("/:version/users/:user", srv.withAuth(srv.deleteUser))
// Generating keypairs
srv.POST("/:version/keypair", srv.withAuth(srv.generateKeyPair))
// Passwords and sessions
srv.POST("/:version/users", srv.withAuth(srv.upsertUser))
srv.PUT("/:version/users/:user/web/password", srv.withAuth(srv.changePassword))
srv.POST("/:version/users/:user/web/password", srv.withAuth(srv.upsertPassword))
srv.POST("/:version/users/:user/web/password/check", srv.withAuth(srv.checkPassword))
srv.POST("/:version/users/:user/web/sessions", srv.withAuth(srv.createWebSession))
srv.POST("/:version/users/:user/web/authenticate", srv.withAuth(srv.authenticateWebUser))
srv.POST("/:version/users/:user/ssh/authenticate", srv.withAuth(srv.authenticateSSHUser))
srv.GET("/:version/users/:user/web/sessions/:sid", srv.withAuth(srv.getWebSession))
srv.DELETE("/:version/users/:user/web/sessions/:sid", srv.withAuth(srv.deleteWebSession))
srv.GET("/:version/signuptokens/:token", srv.withAuth(srv.getSignupTokenData))
srv.POST("/:version/signuptokens/users", srv.withAuth(srv.createUserWithToken))
srv.POST("/:version/signuptokens", srv.withAuth(srv.createSignupToken))
// Servers and presence heartbeat
srv.POST("/:version/namespaces/:namespace/nodes", srv.withAuth(srv.upsertNode))
srv.POST("/:version/namespaces/:namespace/nodes/keepalive", srv.withAuth(srv.keepAliveNode))
srv.PUT("/:version/namespaces/:namespace/nodes", srv.withAuth(srv.upsertNodes))
srv.GET("/:version/namespaces/:namespace/nodes", srv.withAuth(srv.getNodes))
srv.DELETE("/:version/namespaces/:namespace/nodes", srv.withAuth(srv.deleteAllNodes))
srv.DELETE("/:version/namespaces/:namespace/nodes/:name", srv.withAuth(srv.deleteNode))
srv.POST("/:version/authservers", srv.withAuth(srv.upsertAuthServer))
srv.GET("/:version/authservers", srv.withAuth(srv.getAuthServers))
srv.POST("/:version/proxies", srv.withAuth(srv.upsertProxy))
srv.GET("/:version/proxies", srv.withAuth(srv.getProxies))
srv.DELETE("/:version/proxies", srv.withAuth(srv.deleteAllProxies))
srv.DELETE("/:version/proxies/:name", srv.withAuth(srv.deleteProxy))
srv.POST("/:version/tunnelconnections", srv.withAuth(srv.upsertTunnelConnection))
srv.GET("/:version/tunnelconnections/:cluster", srv.withAuth(srv.getTunnelConnections))
srv.GET("/:version/tunnelconnections", srv.withAuth(srv.getAllTunnelConnections))
srv.DELETE("/:version/tunnelconnections/:cluster/:conn", srv.withAuth(srv.deleteTunnelConnection))
srv.DELETE("/:version/tunnelconnections/:cluster", srv.withAuth(srv.deleteTunnelConnections))
srv.DELETE("/:version/tunnelconnections", srv.withAuth(srv.deleteAllTunnelConnections))
// Server Credentials
srv.POST("/:version/server/credentials", srv.withAuth(srv.generateServerKeys))
srv.POST("/:version/remoteclusters", srv.withAuth(srv.createRemoteCluster))
srv.GET("/:version/remoteclusters/:cluster", srv.withAuth(srv.getRemoteCluster))
srv.GET("/:version/remoteclusters", srv.withAuth(srv.getRemoteClusters))
srv.DELETE("/:version/remoteclusters/:cluster", srv.withAuth(srv.deleteRemoteCluster))
srv.DELETE("/:version/remoteclusters", srv.withAuth(srv.deleteAllRemoteClusters))
// Reverse tunnels
srv.POST("/:version/reversetunnels", srv.withAuth(srv.upsertReverseTunnel))
srv.GET("/:version/reversetunnels", srv.withAuth(srv.getReverseTunnels))
srv.DELETE("/:version/reversetunnels/:domain", srv.withAuth(srv.deleteReverseTunnel))
// trusted clusters
srv.POST("/:version/trustedclusters", srv.withAuth(srv.upsertTrustedCluster))
srv.POST("/:version/trustedclusters/validate", srv.withAuth(srv.validateTrustedCluster))
srv.GET("/:version/trustedclusters", srv.withAuth(srv.getTrustedClusters))
srv.GET("/:version/trustedclusters/:name", srv.withAuth(srv.getTrustedCluster))
srv.DELETE("/:version/trustedclusters/:name", srv.withAuth(srv.deleteTrustedCluster))
// Tokens
srv.POST("/:version/tokens", srv.withAuth(srv.generateToken))
srv.POST("/:version/tokens/register", srv.withAuth(srv.registerUsingToken))
srv.POST("/:version/tokens/register/auth", srv.withAuth(srv.registerNewAuthServer))
// active sesssions
srv.POST("/:version/namespaces/:namespace/sessions", srv.withAuth(srv.createSession))
srv.PUT("/:version/namespaces/:namespace/sessions/:id", srv.withAuth(srv.updateSession))
srv.GET("/:version/namespaces/:namespace/sessions", srv.withAuth(srv.getSessions))
srv.GET("/:version/namespaces/:namespace/sessions/:id", srv.withAuth(srv.getSession))
srv.POST("/:version/namespaces/:namespace/sessions/:id/slice", srv.withAuth(srv.postSessionSlice))
srv.POST("/:version/namespaces/:namespace/sessions/:id/recording", srv.withAuth(srv.uploadSessionRecording))
srv.GET("/:version/namespaces/:namespace/sessions/:id/stream", srv.withAuth(srv.getSessionChunk))
srv.GET("/:version/namespaces/:namespace/sessions/:id/events", srv.withAuth(srv.getSessionEvents))
// Namespaces
srv.POST("/:version/namespaces", srv.withAuth(srv.upsertNamespace))
srv.GET("/:version/namespaces", srv.withAuth(srv.getNamespaces))
srv.GET("/:version/namespaces/:namespace", srv.withAuth(srv.getNamespace))
srv.DELETE("/:version/namespaces/:namespace", srv.withAuth(srv.deleteNamespace))
// Roles
srv.POST("/:version/roles", srv.withAuth(srv.upsertRole))
srv.GET("/:version/roles", srv.withAuth(srv.getRoles))
srv.GET("/:version/roles/:role", srv.withAuth(srv.getRole))
srv.DELETE("/:version/roles/:role", srv.withAuth(srv.deleteRole))
// cluster configuration
srv.GET("/:version/configuration", srv.withAuth(srv.getClusterConfig))
srv.POST("/:version/configuration", srv.withAuth(srv.setClusterConfig))
srv.GET("/:version/configuration/name", srv.withAuth(srv.getClusterName))
srv.POST("/:version/configuration/name", srv.withAuth(srv.setClusterName))
srv.GET("/:version/configuration/static_tokens", srv.withAuth(srv.getStaticTokens))
srv.DELETE("/:version/configuration/static_tokens", srv.withAuth(srv.deleteStaticTokens))
srv.POST("/:version/configuration/static_tokens", srv.withAuth(srv.setStaticTokens))
srv.GET("/:version/authentication/preference", srv.withAuth(srv.getClusterAuthPreference))
srv.POST("/:version/authentication/preference", srv.withAuth(srv.setClusterAuthPreference))
// OIDC
srv.POST("/:version/oidc/connectors", srv.withAuth(srv.upsertOIDCConnector))
srv.GET("/:version/oidc/connectors", srv.withAuth(srv.getOIDCConnectors))
srv.GET("/:version/oidc/connectors/:id", srv.withAuth(srv.getOIDCConnector))
srv.DELETE("/:version/oidc/connectors/:id", srv.withAuth(srv.deleteOIDCConnector))
srv.POST("/:version/oidc/requests/create", srv.withAuth(srv.createOIDCAuthRequest))
srv.POST("/:version/oidc/requests/validate", srv.withAuth(srv.validateOIDCAuthCallback))
// SAML handlers
srv.POST("/:version/saml/connectors", srv.withAuth(srv.createSAMLConnector))
srv.PUT("/:version/saml/connectors", srv.withAuth(srv.upsertSAMLConnector))
srv.GET("/:version/saml/connectors", srv.withAuth(srv.getSAMLConnectors))
srv.GET("/:version/saml/connectors/:id", srv.withAuth(srv.getSAMLConnector))
srv.DELETE("/:version/saml/connectors/:id", srv.withAuth(srv.deleteSAMLConnector))
srv.POST("/:version/saml/requests/create", srv.withAuth(srv.createSAMLAuthRequest))
srv.POST("/:version/saml/requests/validate", srv.withAuth(srv.validateSAMLResponse))
// Github connector
srv.POST("/:version/github/connectors", srv.withAuth(srv.createGithubConnector))
srv.PUT("/:version/github/connectors", srv.withAuth(srv.upsertGithubConnector))
srv.GET("/:version/github/connectors", srv.withAuth(srv.getGithubConnectors))
srv.GET("/:version/github/connectors/:id", srv.withAuth(srv.getGithubConnector))
srv.DELETE("/:version/github/connectors/:id", srv.withAuth(srv.deleteGithubConnector))
srv.POST("/:version/github/requests/create", srv.withAuth(srv.createGithubAuthRequest))
srv.POST("/:version/github/requests/validate", srv.withAuth(srv.validateGithubAuthCallback))
// U2F
srv.GET("/:version/u2f/signuptokens/:token", srv.withAuth(srv.getSignupU2FRegisterRequest))
srv.POST("/:version/u2f/users", srv.withAuth(srv.createUserWithU2FToken))
srv.POST("/:version/u2f/users/:user/sign", srv.withAuth(srv.u2fSignRequest))
srv.GET("/:version/u2f/appid", srv.withAuth(srv.getU2FAppID))
// Provisioning tokens
srv.GET("/:version/tokens", srv.withAuth(srv.getTokens))
srv.GET("/:version/tokens/:token", srv.withAuth(srv.getToken))
srv.DELETE("/:version/tokens/:token", srv.withAuth(srv.deleteToken))
// Audit logs AKA events
srv.POST("/:version/events", srv.withAuth(srv.emitAuditEvent))
srv.GET("/:version/events", srv.withAuth(srv.searchEvents))
srv.GET("/:version/events/session", srv.withAuth(srv.searchSessionEvents))
if plugin := GetPlugin(); plugin != nil {
plugin.AddHandlers(&srv)
}
return httplib.RewritePaths(&srv.Router,
httplib.Rewrite("/v1/nodes", "/v1/namespaces/default/nodes"),
httplib.Rewrite("/v1/sessions", "/v1/namespaces/default/sessions"),
httplib.Rewrite("/v1/sessions/([^/]+)/(.*)", "/v1/namespaces/default/sessions/$1/$2"),
)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/apiserver.go#L279-L325 | go | train | // upsertServer is a common utility function | func (s *APIServer) upsertServer(auth ClientI, role teleport.Role, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | // upsertServer is a common utility function
func (s *APIServer) upsertServer(auth ClientI, role teleport.Role, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | {
var req upsertServerRawReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
var kind string
switch role {
case teleport.RoleNode:
kind = services.KindNode
case teleport.RoleAuth:
kind = services.KindAuthServer
case teleport.RoleProxy:
kind = services.KindProxy
}
server, err := services.GetServerMarshaler().UnmarshalServer(req.Server, kind)
if err != nil {
return nil, trace.Wrap(err)
}
// if server sent "local" IP address to us, replace the ip/host part with the remote address we see
// on the socket, but keep the original port:
server.SetAddr(utils.ReplaceLocalhost(server.GetAddr(), r.RemoteAddr))
if req.TTL != 0 {
server.SetTTL(s, req.TTL)
}
switch role {
case teleport.RoleNode:
namespace := p.ByName("namespace")
if !services.IsValidNamespace(namespace) {
return nil, trace.BadParameter("invalid namespace %q", namespace)
}
server.SetNamespace(namespace)
handle, err := auth.UpsertNode(server)
if err != nil {
return nil, trace.Wrap(err)
}
return handle, nil
case teleport.RoleAuth:
if err := auth.UpsertAuthServer(server); err != nil {
return nil, trace.Wrap(err)
}
case teleport.RoleProxy:
if err := auth.UpsertProxy(server); err != nil {
return nil, trace.Wrap(err)
}
}
return message("ok"), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/apiserver.go#L328-L337 | go | train | // keepAliveNode updates node TTL in the backend | func (s *APIServer) keepAliveNode(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | // keepAliveNode updates node TTL in the backend
func (s *APIServer) keepAliveNode(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | {
var handle services.KeepAlive
if err := httplib.ReadJSON(r, &handle); err != nil {
return nil, trace.Wrap(err)
}
if err := auth.KeepAliveNode(r.Context(), handle); err != nil {
return nil, trace.Wrap(err)
}
return message("ok"), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/apiserver.go#L345-L365 | go | train | // upsertNodes is used to bulk insert nodes into the backend. | func (s *APIServer) upsertNodes(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | // upsertNodes is used to bulk insert nodes into the backend.
func (s *APIServer) upsertNodes(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | {
var req upsertNodesReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
if !services.IsValidNamespace(req.Namespace) {
return nil, trace.BadParameter("invalid namespace %q", req.Namespace)
}
nodes, err := services.GetServerMarshaler().UnmarshalServers(req.Nodes)
if err != nil {
return nil, trace.Wrap(err)
}
err = auth.UpsertNodes(req.Namespace, nodes)
if err != nil {
return nil, trace.Wrap(err)
}
return message("ok"), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/apiserver.go#L373-L392 | go | train | // getNodes returns registered SSH nodes | func (s *APIServer) getNodes(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | // getNodes returns registered SSH nodes
func (s *APIServer) getNodes(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | {
namespace := p.ByName("namespace")
if !services.IsValidNamespace(namespace) {
return nil, trace.BadParameter("invalid namespace %q", namespace)
}
skipValidation, _, err := httplib.ParseBool(r.URL.Query(), "skip_validation")
if err != nil {
return nil, trace.Wrap(err)
}
var opts []services.MarshalOption
if skipValidation {
opts = append(opts, services.SkipValidation())
}
servers, err := auth.GetNodes(namespace, opts...)
if err != nil {
return nil, trace.Wrap(err)
}
return marshalServers(servers, version)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/apiserver.go#L448-L458 | go | train | // deleteProxy deletes proxy | func (s *APIServer) deleteProxy(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | // deleteProxy deletes proxy
func (s *APIServer) deleteProxy(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | {
name := p.ByName("name")
if name == "" {
return nil, trace.BadParameter("missing proxy name")
}
err := auth.DeleteProxy(name)
if err != nil {
return nil, trace.Wrap(err)
}
return message("ok"), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/apiserver.go#L461-L463 | go | train | // upsertAuthServer is called by remote Auth servers when they ping back into the auth service | func (s *APIServer) upsertAuthServer(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | // upsertAuthServer is called by remote Auth servers when they ping back into the auth service
func (s *APIServer) upsertAuthServer(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | {
return s.upsertServer(auth, teleport.RoleAuth, w, r, p, version)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/apiserver.go#L466-L472 | go | train | // getAuthServers returns registered auth servers | func (s *APIServer) getAuthServers(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | // getAuthServers returns registered auth servers
func (s *APIServer) getAuthServers(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | {
servers, err := auth.GetAuthServers()
if err != nil {
return nil, trace.Wrap(err)
}
return marshalServers(servers, version)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/apiserver.go#L492-L508 | go | train | // upsertReverseTunnel is called by admin to create a reverse tunnel to remote proxy | func (s *APIServer) upsertReverseTunnel(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | // upsertReverseTunnel is called by admin to create a reverse tunnel to remote proxy
func (s *APIServer) upsertReverseTunnel(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | {
var req upsertReverseTunnelRawReq
if err := httplib.ReadJSON(r, &req); err != nil {
return nil, trace.Wrap(err)
}
tun, err := services.GetReverseTunnelMarshaler().UnmarshalReverseTunnel(req.ReverseTunnel)
if err != nil {
return nil, trace.Wrap(err)
}
if req.TTL != 0 {
tun.SetTTL(s, req.TTL)
}
if err := auth.UpsertReverseTunnel(tun); err != nil {
return nil, trace.Wrap(err)
}
return message("ok"), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/apiserver.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/apiserver.go#L511-L525 | go | train | // getReverseTunnels returns a list of reverse tunnels | func (s *APIServer) getReverseTunnels(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | // getReverseTunnels returns a list of reverse tunnels
func (s *APIServer) getReverseTunnels(auth ClientI, w http.ResponseWriter, r *http.Request, p httprouter.Params, version string) (interface{}, error) | {
reverseTunnels, err := auth.GetReverseTunnels()
if err != nil {
return nil, trace.Wrap(err)
}
items := make([]json.RawMessage, len(reverseTunnels))
for i, tunnel := range reverseTunnels {
data, err := services.GetReverseTunnelMarshaler().MarshalReverseTunnel(tunnel, services.WithVersion(version), services.PreserveResourceID())
if err != nil {
return nil, trace.Wrap(err)
}
items[i] = data
}
return items, nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.