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/auth/register.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L205-L237
go
train
// insecureRegisterClient attempts to connects to the Auth Server using the // CA on disk. If no CA is found on disk, Teleport will not verify the Auth // Server it is connecting to.
func insecureRegisterClient(params RegisterParams) (*Client, error)
// insecureRegisterClient attempts to connects to the Auth Server using the // CA on disk. If no CA is found on disk, Teleport will not verify the Auth // Server it is connecting to. func insecureRegisterClient(params RegisterParams) (*Client, error)
{ tlsConfig := utils.TLSConfig(params.CipherSuites) cert, err := readCA(params) if err != nil && !trace.IsNotFound(err) { return nil, trace.Wrap(err) } // If no CA was found, then create a insecure connection to the Auth Server, // otherwise use the CA on disk to validate the Auth Server. if trace.IsNotFound(err) { tlsConfig.InsecureSkipVerify = true log.Warnf("Joining cluster without validating the identity of the Auth " + "Server. This may open you up to a Man-In-The-Middle (MITM) attack if an " + "attacker can gain privileged network access. To remedy this, use the CA pin " + "value provided when join token was generated to validate the identity of " + "the Auth Server.") } else { certPool := x509.NewCertPool() certPool.AddCert(cert) tlsConfig.RootCAs = certPool log.Infof("Joining remote cluster %v, validating connection with certificate on disk.", cert.Subject.CommonName) } client, err := NewTLSClient(ClientConfig{Addrs: params.Servers, TLS: tlsConfig}) if err != nil { return nil, trace.Wrap(err) } return client, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/register.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L241-L251
go
train
// readCA will read in CA that will be used to validate the certificate that // the Auth Server presents.
func readCA(params RegisterParams) (*x509.Certificate, error)
// readCA will read in CA that will be used to validate the certificate that // the Auth Server presents. func readCA(params RegisterParams) (*x509.Certificate, error)
{ certBytes, err := utils.ReadPath(params.CAPath) if err != nil { return nil, trace.Wrap(err) } cert, err := tlsca.ParseCertificatePEM(certBytes) if err != nil { return nil, trace.Wrap(err, "failed to parse certificate at %v", params.CAPath) } return cert, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/register.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L258-L303
go
train
// pinRegisterClient first connects to the Auth Server using a insecure // connection to fetch the root CA. If the root CA matches the provided CA // pin, a connection will be re-established and the root CA will be used to // validate the certificate presented. If both conditions hold true, then we // know we are connecting to the expected Auth Server.
func pinRegisterClient(params RegisterParams) (*Client, error)
// pinRegisterClient first connects to the Auth Server using a insecure // connection to fetch the root CA. If the root CA matches the provided CA // pin, a connection will be re-established and the root CA will be used to // validate the certificate presented. If both conditions hold true, then we // know we are connecting to the expected Auth Server. func pinRegisterClient(params RegisterParams) (*Client, error)
{ // Build a insecure client to the Auth Server. This is safe because even if // an attacker were to MITM this connection the CA pin will not match below. tlsConfig := utils.TLSConfig(params.CipherSuites) tlsConfig.InsecureSkipVerify = true client, err := NewTLSClient(ClientConfig{Addrs: params.Servers, TLS: tlsConfig}) if err != nil { return nil, trace.Wrap(err) } defer client.Close() // Fetch the root CA from the Auth Server. The NOP role has access to the // GetClusterCACert endpoint. localCA, err := client.GetClusterCACert() if err != nil { return nil, trace.Wrap(err) } tlsCA, err := tlsca.ParseCertificatePEM(localCA.TLSCA) if err != nil { return nil, trace.Wrap(err) } // Check that the SPKI pin matches the CA we fetched over a insecure // connection. This makes sure the CA fetched over a insecure connection is // in-fact the expected CA. err = utils.CheckSPKI(params.CAPin, tlsCA) if err != nil { return nil, trace.Wrap(err) } log.Infof("Joining remote cluster %v with CA pin.", tlsCA.Subject.CommonName) // Create another client, but this time with the CA provided to validate // that the Auth Server was issued a certificate by the same CA. tlsConfig = utils.TLSConfig(params.CipherSuites) certPool := x509.NewCertPool() certPool.AddCert(tlsCA) tlsConfig.RootCAs = certPool client, err = NewTLSClient(ClientConfig{Addrs: params.Servers, TLS: tlsConfig}) if err != nil { return nil, trace.Wrap(err) } return client, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/register.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/register.go#L327-L348
go
train
// ReRegister renews the certificates and private keys based on the client's existing identity.
func ReRegister(params ReRegisterParams) (*Identity, error)
// ReRegister renews the certificates and private keys based on the client's existing identity. func ReRegister(params ReRegisterParams) (*Identity, error)
{ hostID, err := params.ID.HostID() if err != nil { return nil, trace.Wrap(err) } keys, err := params.Client.GenerateServerKeys(GenerateServerKeysRequest{ HostID: hostID, NodeName: params.ID.NodeName, Roles: teleport.Roles{params.ID.Role}, AdditionalPrincipals: params.AdditionalPrincipals, DNSNames: params.DNSNames, PublicTLSKey: params.PublicTLSKey, PublicSSHKey: params.PublicSSHKey, Rotation: &params.Rotation, }) if err != nil { return nil, trace.Wrap(err) } keys.Key = params.PrivateKey return ReadIdentityFromKeyPair(keys) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L170-L177
go
train
// ReadFromFile reads Teleport configuration from a file. Currently only YAML // format is supported
func ReadFromFile(filePath string) (*FileConfig, error)
// ReadFromFile reads Teleport configuration from a file. Currently only YAML // format is supported func ReadFromFile(filePath string) (*FileConfig, error)
{ f, err := os.Open(filePath) if err != nil { return nil, trace.Wrap(err, fmt.Sprintf("failed to open file: %v", filePath)) } defer f.Close() return ReadConfig(f) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L180-L187
go
train
// ReadFromString reads values from base64 encoded byte string
func ReadFromString(configString string) (*FileConfig, error)
// ReadFromString reads values from base64 encoded byte string func ReadFromString(configString string) (*FileConfig, error)
{ data, err := base64.StdEncoding.DecodeString(configString) if err != nil { return nil, trace.BadParameter( "confiugraion should be base64 encoded: %v", err) } return ReadConfig(bytes.NewBuffer(data)) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L190-L235
go
train
// ReadConfig reads Teleport configuration from reader in YAML format
func ReadConfig(reader io.Reader) (*FileConfig, error)
// ReadConfig reads Teleport configuration from reader in YAML format func ReadConfig(reader io.Reader) (*FileConfig, error)
{ // read & parse YAML config: bytes, err := ioutil.ReadAll(reader) if err != nil { return nil, trace.Wrap(err, "failed reading Teleport configuration") } var fc FileConfig if err = yaml.Unmarshal(bytes, &fc); err != nil { return nil, trace.BadParameter("failed to parse Teleport configuration: %v", err) } // don't start Teleport with invalid ciphers, kex algorithms, or mac algorithms. err = fc.Check() if err != nil { return nil, trace.BadParameter("failed to parse Teleport configuration: %v", err) } // now check for unknown (misspelled) config keys: var validateKeys func(m YAMLMap) error validateKeys = func(m YAMLMap) error { var recursive, ok bool var key string for k, v := range m { if key, ok = k.(string); ok { if recursive, ok = validKeys[key]; !ok { return trace.BadParameter("unrecognized configuration key: '%v'", key) } if recursive { if m2, ok := v.(YAMLMap); ok { if err := validateKeys(m2); err != nil { return err } } } } } return nil } // validate configuration keys: var tmp YAMLMap if err = yaml.Unmarshal(bytes, &tmp); err != nil { return nil, trace.BadParameter("error parsing YAML config") } if err = validateKeys(tmp); err != nil { return nil, trace.Wrap(err) } return &fc, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L239-L297
go
train
// MakeSampleFileConfig returns a sample config structure populated by defaults, // useful to generate sample configuration files
func MakeSampleFileConfig() (fc *FileConfig)
// MakeSampleFileConfig returns a sample config structure populated by defaults, // useful to generate sample configuration files func MakeSampleFileConfig() (fc *FileConfig)
{ conf := service.MakeDefaultConfig() // sample global config: var g Global g.NodeName = conf.Hostname g.AuthToken = "cluster-join-token" g.Logger.Output = "stderr" g.Logger.Severity = "INFO" g.AuthServers = []string{defaults.AuthListenAddr().Addr} g.Limits.MaxConnections = defaults.LimiterMaxConnections g.Limits.MaxUsers = defaults.LimiterMaxConcurrentUsers g.DataDir = defaults.DataDir g.PIDFile = "/var/run/teleport.pid" // sample SSH config: var s SSH s.EnabledFlag = "yes" s.ListenAddress = conf.SSH.Addr.Addr s.Commands = []CommandLabel{ { Name: "hostname", Command: []string{"/usr/bin/hostname"}, Period: time.Minute, }, { Name: "arch", Command: []string{"/usr/bin/uname", "-p"}, Period: time.Hour, }, } s.Labels = map[string]string{ "db_type": "postgres", "db_role": "master", } // sample Auth config: var a Auth a.ListenAddress = conf.Auth.SSHAddr.Addr a.EnabledFlag = "yes" a.StaticTokens = []StaticToken{"proxy,node:cluster-join-token"} // sample proxy config: var p Proxy p.EnabledFlag = "yes" p.ListenAddress = conf.Proxy.SSHAddr.Addr p.WebAddr = conf.Proxy.WebAddr.Addr p.TunAddr = conf.Proxy.ReverseTunnelListenAddr.Addr p.CertFile = "/var/lib/teleport/webproxy_cert.pem" p.KeyFile = "/var/lib/teleport/webproxy_key.pem" fc = &FileConfig{ Global: g, Proxy: p, SSH: s, Auth: a, } return fc }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L300-L306
go
train
// DebugDumpToYAML allows for quick YAML dumping of the config
func (conf *FileConfig) DebugDumpToYAML() string
// DebugDumpToYAML allows for quick YAML dumping of the config func (conf *FileConfig) DebugDumpToYAML() string
{ bytes, err := yaml.Marshal(&conf) if err != nil { panic(err) } return string(bytes) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L311-L332
go
train
// Check ensures that the ciphers, kex algorithms, and mac algorithms set // are supported by golang.org/x/crypto/ssh. This ensures we don't start // Teleport with invalid configuration.
func (conf *FileConfig) Check() error
// Check ensures that the ciphers, kex algorithms, and mac algorithms set // are supported by golang.org/x/crypto/ssh. This ensures we don't start // Teleport with invalid configuration. func (conf *FileConfig) Check() error
{ var sc ssh.Config sc.SetDefaults() for _, c := range conf.Ciphers { if utils.SliceContainsStr(sc.Ciphers, c) == false { return trace.BadParameter("cipher %q not supported", c) } } for _, k := range conf.KEXAlgorithms { if utils.SliceContainsStr(sc.KeyExchanges, k) == false { return trace.BadParameter("KEX %q not supported", k) } } for _, m := range conf.MACAlgorithms { if utils.SliceContainsStr(sc.MACs, m) == false { return trace.BadParameter("MAC %q not supported", m) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L408-L414
go
train
// Enabled determines if a given "_service" section has been set to 'true'
func (c *CachePolicy) Enabled() bool
// Enabled determines if a given "_service" section has been set to 'true' func (c *CachePolicy) Enabled() bool
{ if c.EnabledFlag == "" { return true } enabled, _ := utils.ParseBool(c.EnabledFlag) return enabled }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L425-L441
go
train
// Parse parses cache policy from Teleport config
func (c *CachePolicy) Parse() (*service.CachePolicy, error)
// Parse parses cache policy from Teleport config func (c *CachePolicy) Parse() (*service.CachePolicy, error)
{ out := service.CachePolicy{ Enabled: c.Enabled(), NeverExpires: c.NeverExpires(), } if out.NeverExpires { return &out, nil } var err error if c.TTL != "" { out.TTL, err = time.ParseDuration(c.TTL) if err != nil { return nil, trace.BadParameter("cache.ttl invalid duration: %v, accepted format '10h'", c.TTL) } } return &out, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L455-L464
go
train
// Enabled determines if a given "_service" section has been set to 'true'
func (s *Service) Enabled() bool
// Enabled determines if a given "_service" section has been set to 'true' func (s *Service) Enabled() bool
{ if s.EnabledFlag == "" { return true } v, err := utils.ParseBool(s.EnabledFlag) if err != nil { return false } return v }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L603-L619
go
train
// Parse is applied to a string in "role,role,role:token" format. It breaks it // apart and constructs a services.ProvisionToken which contains the token, // role, and expiry (infinite).
func (t StaticToken) Parse() (*services.ProvisionTokenV1, error)
// Parse is applied to a string in "role,role,role:token" format. It breaks it // apart and constructs a services.ProvisionToken which contains the token, // role, and expiry (infinite). func (t StaticToken) Parse() (*services.ProvisionTokenV1, error)
{ parts := strings.Split(string(t), ":") if len(parts) != 2 { return nil, trace.BadParameter("invalid static token spec: %q", t) } roles, err := teleport.ParseRoles(parts[0]) if err != nil { return nil, trace.Wrap(err) } return &services.ProvisionTokenV1{ Token: parts[1], Roles: roles, Expires: time.Unix(0, 0).UTC(), }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L635-L667
go
train
// Parse returns the Authentication Configuration in two parts: AuthPreference // (type, second factor, u2f) and OIDCConnector.
func (a *AuthenticationConfig) Parse() (services.AuthPreference, services.OIDCConnector, error)
// Parse returns the Authentication Configuration in two parts: AuthPreference // (type, second factor, u2f) and OIDCConnector. func (a *AuthenticationConfig) Parse() (services.AuthPreference, services.OIDCConnector, error)
{ var err error var u services.U2F if a.U2F != nil { u = a.U2F.Parse() } ap, err := services.NewAuthPreference(services.AuthPreferenceSpecV2{ Type: a.Type, SecondFactor: a.SecondFactor, ConnectorName: a.ConnectorName, U2F: &u, }) if err != nil { return nil, nil, trace.Wrap(err) } // check to make sure the configuration is valid err = ap.CheckAndSetDefaults() if err != nil { return nil, nil, trace.Wrap(err) } var oidcConnector services.OIDCConnector if a.OIDC != nil { oidcConnector, err = a.OIDC.Parse() if err != nil { return nil, nil, trace.Wrap(err) } } return ap, oidcConnector, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L710-L720
go
train
// Parse returns a parsed pam.Config.
func (p *PAM) Parse() *pam.Config
// Parse returns a parsed pam.Config. func (p *PAM) Parse() *pam.Config
{ serviceName := p.ServiceName if serviceName == "" { serviceName = defaults.ServiceName } enabled, _ := utils.ParseBool(p.Enabled) return &pam.Config{ Enabled: enabled, ServiceName: serviceName, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L778-L792
go
train
// ConvertAndValidate returns validated services.ReverseTunnel or nil and error otherwize
func (t *ReverseTunnel) ConvertAndValidate() (services.ReverseTunnel, error)
// ConvertAndValidate returns validated services.ReverseTunnel or nil and error otherwize func (t *ReverseTunnel) ConvertAndValidate() (services.ReverseTunnel, error)
{ for i := range t.Addresses { addr, err := utils.ParseHostPortAddr(t.Addresses[i], defaults.SSHProxyTunnelListenPort) if err != nil { return nil, trace.Wrap(err, "Invalid address for tunnel %v", t.DomainName) } t.Addresses[i] = addr.String() } out := services.NewReverseTunnel(t.DomainName, t.Addresses) if err := out.Check(); err != nil { return nil, trace.Wrap(err) } return out, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L818-L851
go
train
// Parse reads values and returns parsed CertAuthority
func (a *Authority) Parse() (services.CertAuthority, services.Role, error)
// Parse reads values and returns parsed CertAuthority func (a *Authority) Parse() (services.CertAuthority, services.Role, error)
{ ca := &services.CertAuthorityV1{ AllowedLogins: a.AllowedLogins, DomainName: a.DomainName, Type: a.Type, } for _, path := range a.CheckingKeyFiles { keyBytes, err := utils.ReadPath(path) if err != nil { return nil, nil, trace.Wrap(err) } ca.CheckingKeys = append(ca.CheckingKeys, keyBytes) } for _, val := range a.CheckingKeys { ca.CheckingKeys = append(ca.CheckingKeys, []byte(val)) } for _, path := range a.SigningKeyFiles { keyBytes, err := utils.ReadPath(path) if err != nil { return nil, nil, trace.Wrap(err) } ca.SigningKeys = append(ca.SigningKeys, keyBytes) } for _, val := range a.SigningKeys { ca.SigningKeys = append(ca.SigningKeys, []byte(val)) } new, role := services.ConvertV1CertAuthority(ca) return new, role, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L898-L935
go
train
// Parse parses config struct into services connector and checks if it's valid
func (o *OIDCConnector) Parse() (services.OIDCConnector, error)
// Parse parses config struct into services connector and checks if it's valid func (o *OIDCConnector) Parse() (services.OIDCConnector, error)
{ if o.Display == "" { o.Display = o.ID } var mappings []services.ClaimMapping for _, c := range o.ClaimsToRoles { var roles []string if len(c.Roles) > 0 { roles = append(roles, c.Roles...) } mappings = append(mappings, services.ClaimMapping{ Claim: c.Claim, Value: c.Value, Roles: roles, RoleTemplate: c.RoleTemplate, }) } other := &services.OIDCConnectorV1{ ID: o.ID, Display: o.Display, IssuerURL: o.IssuerURL, ClientID: o.ClientID, ClientSecret: o.ClientSecret, RedirectURL: o.RedirectURL, Scope: o.Scope, ClaimsToRoles: mappings, } v2 := other.V2() v2.SetACR(o.ACR) v2.SetProvider(o.Provider) if err := v2.Check(); err != nil { return nil, trace.Wrap(err) } return v2, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/config/fileconf.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/config/fileconf.go#L943-L964
go
train
// Parse parses values in the U2F configuration section and validates its content.
func (u *U2F) Parse() (*services.U2F, error)
// Parse parses values in the U2F configuration section and validates its content. func (u *U2F) Parse() (*services.U2F, error)
{ // If no appID specified, default to hostname appID := u.AppID if appID == "" { hostname, err := os.Hostname() if err != nil { return nil, trace.Wrap(err, "failed to automatically determine U2F AppID from hostname") } appID = fmt.Sprintf("https://%s:%d", strings.ToLower(hostname), defaults.HTTPListenPort) } // If no facets specified, default to AppID facets := u.Facets if len(facets) == 0 { facets = []string{appID} } return &services.U2F{ AppID: appID, Facets: facets, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/signer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/signer.go#L29-L46
go
train
// NewSigner returns new ssh Signer from private key + certificate pair. The // signer can be used to create "auth methods" i.e. login into Teleport SSH // servers.
func NewSigner(keyBytes, certBytes []byte) (ssh.Signer, error)
// NewSigner returns new ssh Signer from private key + certificate pair. The // signer can be used to create "auth methods" i.e. login into Teleport SSH // servers. func NewSigner(keyBytes, certBytes []byte) (ssh.Signer, error)
{ keySigner, err := ssh.ParsePrivateKey(keyBytes) if err != nil { return nil, trace.Wrap(err, "failed to parse SSH private key") } pubkey, _, _, _, err := ssh.ParseAuthorizedKey(certBytes) if err != nil { return nil, trace.Wrap(err, "failed to parse SSH certificate") } cert, ok := pubkey.(*ssh.Certificate) if !ok { return nil, trace.BadParameter("expected SSH certificate, got %T ", pubkey) } return ssh.NewCertSigner(cert, keySigner) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/sshutils/signer.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/sshutils/signer.go#L49-L60
go
train
// CryptoPublicKey extracts public key from RSA public key in authorized_keys format
func CryptoPublicKey(publicKey []byte) (crypto.PublicKey, error)
// CryptoPublicKey extracts public key from RSA public key in authorized_keys format func CryptoPublicKey(publicKey []byte) (crypto.PublicKey, error)
{ // reuse the same RSA keys for SSH and TLS keys pubKey, _, _, _, err := ssh.ParseAuthorizedKey(publicKey) if err != nil { return nil, trace.Wrap(err) } cryptoPubKey, ok := pubKey.(ssh.CryptoPublicKey) if !ok { return nil, trace.BadParameter("expected ssh.CryptoPublicKey, got %T", pubKey) } return cryptoPubKey.CryptoPublicKey(), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/parsegen.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/parsegen.go#L36-L41
go
train
// ClusterName returns cluster name from organization
func ClusterName(subject pkix.Name) (string, error)
// ClusterName returns cluster name from organization func ClusterName(subject pkix.Name) (string, error)
{ if len(subject.Organization) == 0 { return "", trace.BadParameter("missing subject organization") } return subject.Organization[0], nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/parsegen.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/parsegen.go#L44-L50
go
train
// GenerateRSAPrivateKeyPEM generates new RSA private key and returns PEM encoded bytes
func GenerateRSAPrivateKeyPEM() ([]byte, error)
// GenerateRSAPrivateKeyPEM generates new RSA private key and returns PEM encoded bytes func GenerateRSAPrivateKeyPEM() ([]byte, error)
{ priv, err := rsa.GenerateKey(rand.Reader, teleport.RSAKeySize) if err != nil { return nil, trace.Wrap(err) } return pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/parsegen.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/parsegen.go#L53-L87
go
train
// GenerateSelfSignedCA generates self-signed certificate authority used for internal inter-node communications
func GenerateSelfSignedCAWithPrivateKey(priv *rsa.PrivateKey, entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)
// GenerateSelfSignedCA generates self-signed certificate authority used for internal inter-node communications func GenerateSelfSignedCAWithPrivateKey(priv *rsa.PrivateKey, entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)
{ notBefore := time.Now() notAfter := notBefore.Add(ttl) serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, nil, trace.Wrap(err) } // this is important, otherwise go will accept certificate authorities // signed by the same private key and having the same subject (happens in tests) entity.SerialNumber = serialNumber.String() template := x509.Certificate{ SerialNumber: serialNumber, Issuer: entity, Subject: entity, NotBefore: notBefore, NotAfter: notAfter, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, BasicConstraintsValid: true, IsCA: true, DNSNames: dnsNames, } derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) if err != nil { return nil, nil, trace.Wrap(err) } keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(priv)}) certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) return keyPEM, certPEM, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/parsegen.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/parsegen.go#L90-L96
go
train
// GenerateSelfSignedCA generates self-signed certificate authority used for internal inter-node communications
func GenerateSelfSignedCA(entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)
// GenerateSelfSignedCA generates self-signed certificate authority used for internal inter-node communications func GenerateSelfSignedCA(entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)
{ priv, err := rsa.GenerateKey(rand.Reader, teleport.RSAKeySize) if err != nil { return nil, nil, trace.Wrap(err) } return GenerateSelfSignedCAWithPrivateKey(priv, entity, dnsNames, ttl) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/parsegen.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/parsegen.go#L160-L166
go
train
// ParsePublicKeyPEM parses public key PEM
func ParsePublicKeyPEM(bytes []byte) (interface{}, error)
// ParsePublicKeyPEM parses public key PEM func ParsePublicKeyPEM(bytes []byte) (interface{}, error)
{ block, _ := pem.Decode(bytes) if block == nil { return nil, trace.BadParameter("expected PEM-encoded block") } return ParsePublicKeyDER(block.Bytes) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/parsegen.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/parsegen.go#L169-L175
go
train
// ParsePublicKeyDER parses unencrypted DER-encoded publice key
func ParsePublicKeyDER(der []byte) (crypto.PublicKey, error)
// ParsePublicKeyDER parses unencrypted DER-encoded publice key func ParsePublicKeyDER(der []byte) (crypto.PublicKey, error)
{ generalKey, err := x509.ParsePKIXPublicKey(der) if err != nil { return nil, trace.Wrap(err) } return generalKey, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/parsegen.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/parsegen.go#L179-L190
go
train
// MarshalPublicKeyFromPrivateKeyPEM extracts public key from private key // and returns PEM marshalled key
func MarshalPublicKeyFromPrivateKeyPEM(privateKey crypto.PrivateKey) ([]byte, error)
// MarshalPublicKeyFromPrivateKeyPEM extracts public key from private key // and returns PEM marshalled key func MarshalPublicKeyFromPrivateKeyPEM(privateKey crypto.PrivateKey) ([]byte, error)
{ rsaPrivateKey, ok := privateKey.(*rsa.PrivateKey) if !ok { return nil, trace.BadParameter("expected RSA key") } rsaPublicKey := rsaPrivateKey.Public() derBytes, err := x509.MarshalPKIXPublicKey(rsaPublicKey) if err != nil { return nil, trace.Wrap(err) } return pem.EncodeToMemory(&pem.Block{Type: "RSA PUBLIC KEY", Bytes: derBytes}), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/tlsca/parsegen.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/tlsca/parsegen.go#L194-L203
go
train
// MarshalCertificatePEM takes a *x509.Certificate and returns the PEM // encoded bytes.
func MarshalCertificatePEM(cert *x509.Certificate) ([]byte, error)
// MarshalCertificatePEM takes a *x509.Certificate and returns the PEM // encoded bytes. func MarshalCertificatePEM(cert *x509.Certificate) ([]byte, error)
{ var buf bytes.Buffer err := pem.Encode(&buf, &pem.Block{Type: "CERTIFICATE", Bytes: cert.Raw}) if err != nil { return nil, trace.Wrap(err) } return buf.Bytes(), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L136-L405
go
train
// Init instantiates and configures an instance of AuthServer
func Init(cfg InitConfig, opts ...AuthServerOption) (*AuthServer, error)
// Init instantiates and configures an instance of AuthServer func Init(cfg InitConfig, opts ...AuthServerOption) (*AuthServer, error)
{ if cfg.DataDir == "" { return nil, trace.BadParameter("DataDir: data dir can not be empty") } if cfg.HostUUID == "" { return nil, trace.BadParameter("HostUUID: host UUID can not be empty") } domainName := cfg.ClusterName.GetClusterName() err := backend.AcquireLock(context.TODO(), cfg.Backend, domainName, 30*time.Second) if err != nil { return nil, trace.Wrap(err) } defer backend.ReleaseLock(context.TODO(), cfg.Backend, domainName) // check that user CA and host CA are present and set the certs if needed asrv, err := NewAuthServer(&cfg, opts...) if err != nil { return nil, trace.Wrap(err) } // Set the ciphersuites that this auth server supports. asrv.cipherSuites = cfg.CipherSuites // INTERNAL: Authorities (plus Roles) and ReverseTunnels don't follow the // same pattern as the rest of the configuration (they are not configuration // singletons). However, we need to keep them around while Telekube uses them. for _, role := range cfg.Roles { if err := asrv.UpsertRole(role); err != nil { return nil, trace.Wrap(err) } log.Infof("Created role: %v.", role) } for i := range cfg.Authorities { ca := cfg.Authorities[i] ca, err = services.GetCertAuthorityMarshaler().GenerateCertAuthority(ca) if err != nil { return nil, trace.Wrap(err) } // Don't re-create CA if it already exists, otherwise // the existing cluster configuration will be corrupted; // this part of code is only used in tests. if err := asrv.Trust.CreateCertAuthority(ca); err != nil { if !trace.IsAlreadyExists(err) { return nil, trace.Wrap(err) } } else { log.Infof("Created trusted certificate authority: %q, type: %q.", ca.GetName(), ca.GetType()) } } for _, tunnel := range cfg.ReverseTunnels { if err := asrv.UpsertReverseTunnel(tunnel); err != nil { return nil, trace.Wrap(err) } log.Infof("Created reverse tunnel: %v.", tunnel) } // set cluster level config on the backend and then force a sync of the cache. clusterConfig, err := asrv.GetClusterConfig() if err != nil && !trace.IsNotFound(err) { return nil, trace.Wrap(err) } // init a unique cluster ID, it must be set once only during the first // start so if it's already there, reuse it if clusterConfig != nil && clusterConfig.GetClusterID() != "" { cfg.ClusterConfig.SetClusterID(clusterConfig.GetClusterID()) } else { cfg.ClusterConfig.SetClusterID(uuid.New()) } err = asrv.SetClusterConfig(cfg.ClusterConfig) if err != nil { return nil, trace.Wrap(err) } // The first Auth Server that starts gets to set the name of the cluster. err = asrv.SetClusterName(cfg.ClusterName) if err != nil && !trace.IsAlreadyExists(err) { return nil, trace.Wrap(err) } // If the cluster name has already been set, log a warning if the user // is trying to change the name. if trace.IsAlreadyExists(err) { // Get current name of cluster from the backend. cn, err := asrv.ClusterConfiguration.GetClusterName() if err != nil { return nil, trace.Wrap(err) } if cn.GetClusterName() != cfg.ClusterName.GetClusterName() { warnMessage := "Cannot rename cluster to %q: continuing with %q. Teleport " + "clusters can not be renamed once they are created. You are seeing this " + "warning for one of two reasons. Either you have not set \"cluster_name\" in " + "Teleport configuration and changed the hostname of the auth server or you " + "are trying to change the value of \"cluster_name\"." log.Warnf(warnMessage, cfg.ClusterName.GetClusterName(), cn.GetClusterName()) // Override user passed in cluster name with what is in the backend. cfg.ClusterName = cn } } log.Debugf("Cluster configuration: %v.", cfg.ClusterName) err = asrv.SetStaticTokens(cfg.StaticTokens) if err != nil { return nil, trace.Wrap(err) } log.Infof("Updating cluster configuration: %v.", cfg.StaticTokens) err = asrv.SetAuthPreference(cfg.AuthPreference) if err != nil { return nil, trace.Wrap(err) } log.Infof("Updating cluster configuration: %v.", cfg.AuthPreference) // always create the default namespace err = asrv.UpsertNamespace(services.NewNamespace(defaults.Namespace)) if err != nil { return nil, trace.Wrap(err) } log.Infof("Created namespace: %q.", defaults.Namespace) // always create a default admin role defaultRole := services.NewAdminRole() err = asrv.CreateRole(defaultRole) if err != nil && !trace.IsAlreadyExists(err) { return nil, trace.Wrap(err) } if !trace.IsAlreadyExists(err) { log.Infof("Created default admin role: %q.", defaultRole.GetName()) } // generate a user certificate authority if it doesn't exist userCA, err := asrv.GetCertAuthority(services.CertAuthID{DomainName: cfg.ClusterName.GetClusterName(), Type: services.UserCA}, true) if err != nil { if !trace.IsNotFound(err) { return nil, trace.Wrap(err) } log.Infof("First start: generating user certificate authority.") priv, pub, err := asrv.GenerateKeyPair("") if err != nil { return nil, trace.Wrap(err) } keyPEM, certPEM, err := tlsca.GenerateSelfSignedCA(pkix.Name{ CommonName: cfg.ClusterName.GetClusterName(), Organization: []string{cfg.ClusterName.GetClusterName()}, }, nil, defaults.CATTL) if err != nil { return nil, trace.Wrap(err) } userCA := &services.CertAuthorityV2{ Kind: services.KindCertAuthority, Version: services.V2, Metadata: services.Metadata{ Name: cfg.ClusterName.GetClusterName(), Namespace: defaults.Namespace, }, Spec: services.CertAuthoritySpecV2{ ClusterName: cfg.ClusterName.GetClusterName(), Type: services.UserCA, SigningKeys: [][]byte{priv}, CheckingKeys: [][]byte{pub}, TLSKeyPairs: []services.TLSKeyPair{{Cert: certPEM, Key: keyPEM}}, }, } if err := asrv.Trust.UpsertCertAuthority(userCA); err != nil { return nil, trace.Wrap(err) } } else if len(userCA.GetTLSKeyPairs()) == 0 { log.Infof("Migrate: generating TLS CA for existing user CA.") keyPEM, certPEM, err := tlsca.GenerateSelfSignedCA(pkix.Name{ CommonName: cfg.ClusterName.GetClusterName(), Organization: []string{cfg.ClusterName.GetClusterName()}, }, nil, defaults.CATTL) if err != nil { return nil, trace.Wrap(err) } userCA.SetTLSKeyPairs([]services.TLSKeyPair{{Cert: certPEM, Key: keyPEM}}) if err := asrv.Trust.UpsertCertAuthority(userCA); err != nil { return nil, trace.Wrap(err) } } // generate a host certificate authority if it doesn't exist hostCA, err := asrv.GetCertAuthority(services.CertAuthID{DomainName: cfg.ClusterName.GetClusterName(), Type: services.HostCA}, true) if err != nil { if !trace.IsNotFound(err) { return nil, trace.Wrap(err) } log.Infof("First start: generating host certificate authority.") priv, pub, err := asrv.GenerateKeyPair("") if err != nil { return nil, trace.Wrap(err) } keyPEM, certPEM, err := tlsca.GenerateSelfSignedCA(pkix.Name{ CommonName: cfg.ClusterName.GetClusterName(), Organization: []string{cfg.ClusterName.GetClusterName()}, }, nil, defaults.CATTL) if err != nil { return nil, trace.Wrap(err) } hostCA = &services.CertAuthorityV2{ Kind: services.KindCertAuthority, Version: services.V2, Metadata: services.Metadata{ Name: cfg.ClusterName.GetClusterName(), Namespace: defaults.Namespace, }, Spec: services.CertAuthoritySpecV2{ ClusterName: cfg.ClusterName.GetClusterName(), Type: services.HostCA, SigningKeys: [][]byte{priv}, CheckingKeys: [][]byte{pub}, TLSKeyPairs: []services.TLSKeyPair{{Cert: certPEM, Key: keyPEM}}, }, } if err := asrv.Trust.UpsertCertAuthority(hostCA); err != nil { return nil, trace.Wrap(err) } } else if len(hostCA.GetTLSKeyPairs()) == 0 { log.Infof("Migrate: generating TLS CA for existing host CA.") privateKey, err := ssh.ParseRawPrivateKey(hostCA.GetSigningKeys()[0]) if err != nil { return nil, trace.Wrap(err) } privateKeyRSA, ok := privateKey.(*rsa.PrivateKey) if !ok { return nil, trace.BadParameter("expected RSA private key, got %T", privateKey) } keyPEM, certPEM, err := tlsca.GenerateSelfSignedCAWithPrivateKey(privateKeyRSA, pkix.Name{ CommonName: cfg.ClusterName.GetClusterName(), Organization: []string{cfg.ClusterName.GetClusterName()}, }, nil, defaults.CATTL) if err != nil { return nil, trace.Wrap(err) } hostCA.SetTLSKeyPairs([]services.TLSKeyPair{{Cert: certPEM, Key: keyPEM}}) if err := asrv.Trust.UpsertCertAuthority(hostCA); err != nil { return nil, trace.Wrap(err) } } if lib.IsInsecureDevMode() { warningMessage := "Starting teleport in insecure mode. This is " + "dangerous! Sensitive information will be logged to console and " + "certificates will not be verified. Proceed with caution!" log.Warn(warningMessage) } // Migrate any legacy resources to new format. err = migrateLegacyResources(cfg, asrv) if err != nil { return nil, trace.Wrap(err) } if !cfg.SkipPeriodicOperations { log.Infof("Auth server is running periodic operations.") go asrv.runPeriodicOperations() } else { log.Infof("Auth server is skipping periodic operations.") } return asrv, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L424-L458
go
train
// DELETE IN: 4.1 // migrateRoleRules adds missing permissions to roles. // // Currently it adds read-only permissions for audit events to all roles that // have read-only session permissions to make sure audit log tab will work.
func migrateRoleRules(asrv *AuthServer) error
// DELETE IN: 4.1 // migrateRoleRules adds missing permissions to roles. // // Currently it adds read-only permissions for audit events to all roles that // have read-only session permissions to make sure audit log tab will work. func migrateRoleRules(asrv *AuthServer) error
{ roles, err := asrv.GetRoles() if err != nil { return trace.Wrap(err) } for _, role := range roles { allowRules := role.GetRules(services.Allow) denyRules := role.GetRules(services.Deny) // First make sure access to events hasn't been explicitly denied. if checkRules(denyRules, services.KindEvent, services.RO()) { log.Debugf("Role %q explicitly denies events access.", role.GetName()) continue } // Next see if the role already has access to events. if checkRules(allowRules, services.KindEvent, services.RO()) { log.Debugf("Role %q already has events access.", role.GetName()) continue } // See if the role has access to sessions. if !checkRules(allowRules, services.KindSession, services.RO()) { log.Debugf("Role %q does not have sessions access.", role.GetName()) continue } // If we got here, the role does not yet have events access and // has session access so add a rule for events as well. log.Infof("Adding events access to role %q.", role.GetName()) allowRules = append(allowRules, services.NewRule(services.KindEvent, services.RO())) role.SetRules(services.Allow, allowRules) err := asrv.UpsertRole(role) if err != nil { return trace.Wrap(err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L461-L472
go
train
// checkRules returns true if any of the provided rules contain specified resource/verbs.
func checkRules(rules []services.Rule, kind string, verbs []string) bool
// checkRules returns true if any of the provided rules contain specified resource/verbs. func checkRules(rules []services.Rule, kind string, verbs []string) bool
{ for _, rule := range rules { if rule.HasResource(kind) || rule.HasResource(services.Wildcard) { for _, verb := range verbs { if rule.HasVerb(verb) || rule.HasVerb(services.Wildcard) { return true } } } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L476-L491
go
train
// isFirstStart returns 'true' if the auth server is starting for the 1st time // on this server.
func isFirstStart(authServer *AuthServer, cfg InitConfig) (bool, error)
// isFirstStart returns 'true' if the auth server is starting for the 1st time // on this server. func isFirstStart(authServer *AuthServer, cfg InitConfig) (bool, error)
{ // check if the CA exists? _, err := authServer.GetCertAuthority( services.CertAuthID{ DomainName: cfg.ClusterName.GetClusterName(), Type: services.HostCA, }, false) if err != nil { if !trace.IsNotFound(err) { return false, trace.Wrap(err) } // CA not found? --> first start! return true, nil } return false, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L494-L506
go
train
// GenerateIdentity generates identity for the auth server
func GenerateIdentity(a *AuthServer, id IdentityID, additionalPrincipals, dnsNames []string) (*Identity, error)
// GenerateIdentity generates identity for the auth server func GenerateIdentity(a *AuthServer, id IdentityID, additionalPrincipals, dnsNames []string) (*Identity, error)
{ keys, err := a.GenerateServerKeys(GenerateServerKeysRequest{ HostID: id.HostUUID, NodeName: id.NodeName, Roles: teleport.Roles{id.Role}, AdditionalPrincipals: additionalPrincipals, DNSNames: dnsNames, }) if err != nil { return nil, trace.Wrap(err) } return ReadIdentityFromKeyPair(keys) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L534-L548
go
train
// String returns user-friendly representation of the identity.
func (i *Identity) String() string
// String returns user-friendly representation of the identity. func (i *Identity) String() string
{ var out []string if i.XCert != nil { out = append(out, fmt.Sprintf("cert(%v issued by %v:%v)", i.XCert.Subject.CommonName, i.XCert.Issuer.CommonName, i.XCert.Issuer.SerialNumber)) } for j := range i.TLSCACertsBytes { cert, err := tlsca.ParseCertificatePEM(i.TLSCACertsBytes[j]) if err != nil { out = append(out, err.Error()) } else { out = append(out, fmt.Sprintf("trust root(%v:%v)", cert.Subject.CommonName, cert.Subject.SerialNumber)) } } return fmt.Sprintf("Identity(%v, %v)", i.ID.Role, strings.Join(out, ",")) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L551-L553
go
train
// CertInfo returns diagnostic information about certificate
func CertInfo(cert *x509.Certificate) string
// CertInfo returns diagnostic information about certificate func CertInfo(cert *x509.Certificate) string
{ return fmt.Sprintf("cert(%v issued by %v:%v)", cert.Subject.CommonName, cert.Issuer.CommonName, cert.Issuer.SerialNumber) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L556-L562
go
train
// TLSCertInfo returns diagnostic information about certificate
func TLSCertInfo(cert *tls.Certificate) string
// TLSCertInfo returns diagnostic information about certificate func TLSCertInfo(cert *tls.Certificate) string
{ x509cert, err := x509.ParseCertificate(cert.Certificate[0]) if err != nil { return err.Error() } return CertInfo(x509cert) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L565-L576
go
train
// CertAuthorityInfo returns debugging information about certificate authority
func CertAuthorityInfo(ca services.CertAuthority) string
// CertAuthorityInfo returns debugging information about certificate authority func CertAuthorityInfo(ca services.CertAuthority) string
{ var out []string for _, keyPair := range ca.GetTLSKeyPairs() { cert, err := tlsca.ParseCertificatePEM(keyPair.Cert) if err != nil { out = append(out, err.Error()) } else { out = append(out, fmt.Sprintf("trust root(%v:%v)", cert.Subject.CommonName, cert.Subject.SerialNumber)) } } return fmt.Sprintf("cert authority(state: %v, phase: %v, roots: %v)", ca.GetRotation().State, ca.GetRotation().Phase, strings.Join(out, ", ")) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L579-L581
go
train
// HasTSLConfig returns true if this identity has TLS certificate and private key
func (i *Identity) HasTLSConfig() bool
// HasTSLConfig returns true if this identity has TLS certificate and private key func (i *Identity) HasTLSConfig() bool
{ return len(i.TLSCACertsBytes) != 0 && len(i.TLSCertBytes) != 0 }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L584-L592
go
train
// HasPrincipals returns whether identity has principals
func (i *Identity) HasPrincipals(additionalPrincipals []string) bool
// HasPrincipals returns whether identity has principals func (i *Identity) HasPrincipals(additionalPrincipals []string) bool
{ set := utils.StringsSet(i.Cert.ValidPrincipals) for _, principal := range additionalPrincipals { if _, ok := set[principal]; !ok { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L595-L606
go
train
// HasDNSNames returns true if TLS certificate has required DNS names
func (i *Identity) HasDNSNames(dnsNames []string) bool
// HasDNSNames returns true if TLS certificate has required DNS names func (i *Identity) HasDNSNames(dnsNames []string) bool
{ if i.XCert == nil { return false } set := utils.StringsSet(i.XCert.DNSNames) for _, dnsName := range dnsNames { if _, ok := set[dnsName]; !ok { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L610-L632
go
train
// TLSConfig returns TLS config for mutual TLS authentication // can return NotFound error if there are no TLS credentials setup for identity
func (i *Identity) TLSConfig(cipherSuites []uint16) (*tls.Config, error)
// TLSConfig returns TLS config for mutual TLS authentication // can return NotFound error if there are no TLS credentials setup for identity func (i *Identity) TLSConfig(cipherSuites []uint16) (*tls.Config, error)
{ tlsConfig := utils.TLSConfig(cipherSuites) if !i.HasTLSConfig() { return nil, trace.NotFound("no TLS credentials setup for this identity") } tlsCert, err := tls.X509KeyPair(i.TLSCertBytes, i.KeyBytes) if err != nil { return nil, trace.BadParameter("failed to parse private key: %v", err) } certPool := x509.NewCertPool() for j := range i.TLSCACertsBytes { parsedCert, err := tlsca.ParseCertificatePEM(i.TLSCACertsBytes[j]) if err != nil { return nil, trace.Wrap(err, "failed to parse CA certificate") } certPool.AddCert(parsedCert) } tlsConfig.Certificates = []tls.Certificate{tlsCert} tlsConfig.RootCAs = certPool tlsConfig.ClientCAs = certPool tlsConfig.ServerName = EncodeClusterName(i.ClusterName) return tlsConfig, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L636-L645
go
train
// SSHClientConfig returns a ssh.ClientConfig used by nodes to connect to // the reverse tunnel server.
func (i *Identity) SSHClientConfig() *ssh.ClientConfig
// SSHClientConfig returns a ssh.ClientConfig used by nodes to connect to // the reverse tunnel server. func (i *Identity) SSHClientConfig() *ssh.ClientConfig
{ return &ssh.ClientConfig{ User: i.ID.HostUUID, Auth: []ssh.AuthMethod{ ssh.PublicKeys(i.KeySigner), }, HostKeyCallback: i.hostKeyCallback, Timeout: defaults.DefaultDialTimeout, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L649-L667
go
train
// hostKeyCallback checks if the host certificate was signed by any of the // known CAs.
func (i *Identity) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error
// hostKeyCallback checks if the host certificate was signed by any of the // known CAs. func (i *Identity) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error
{ cert, ok := key.(*ssh.Certificate) if !ok { return trace.BadParameter("only host certificates supported") } // Loop over all CAs and see if any of them signed the certificate. for _, k := range i.SSHCACertBytes { pubkey, _, _, _, err := ssh.ParseAuthorizedKey(k) if err != nil { return trace.Wrap(err) } if sshutils.KeysEqual(cert.SignatureKey, pubkey) { return nil } } return trace.BadParameter("no matching keys found") }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L677-L683
go
train
// HostID is host ID part of the host UUID that consists cluster name
func (id *IdentityID) HostID() (string, error)
// HostID is host ID part of the host UUID that consists cluster name func (id *IdentityID) HostID() (string, error)
{ parts := strings.Split(id.HostUUID, ".") if len(parts) < 2 { return "", trace.BadParameter("expected 2 parts in %q", id.HostUUID) } return parts[0], nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L686-L688
go
train
// Equals returns true if two identities are equal
func (id *IdentityID) Equals(other IdentityID) bool
// Equals returns true if two identities are equal func (id *IdentityID) Equals(other IdentityID) bool
{ return id.Role == other.Role && id.HostUUID == other.HostUUID }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L691-L693
go
train
// String returns debug friendly representation of this identity
func (id *IdentityID) String() string
// String returns debug friendly representation of this identity func (id *IdentityID) String() string
{ return fmt.Sprintf("Identity(hostuuid=%v, role=%v)", id.HostUUID, id.Role) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L696-L718
go
train
// ReadIdentityFromKeyPair reads SSH and TLS identity from key pair.
func ReadIdentityFromKeyPair(keys *PackedKeys) (*Identity, error)
// ReadIdentityFromKeyPair reads SSH and TLS identity from key pair. func ReadIdentityFromKeyPair(keys *PackedKeys) (*Identity, error)
{ identity, err := ReadSSHIdentityFromKeyPair(keys.Key, keys.Cert) if err != nil { return nil, trace.Wrap(err) } if len(keys.SSHCACerts) != 0 { identity.SSHCACertBytes = keys.SSHCACerts } if len(keys.TLSCACerts) != 0 { // Parse the key pair to verify that identity parses properly for future use. i, err := ReadTLSIdentityFromKeyPair(keys.Key, keys.TLSCert, keys.TLSCACerts) if err != nil { return nil, trace.Wrap(err) } identity.XCert = i.XCert identity.TLSCertBytes = keys.TLSCert identity.TLSCACertsBytes = keys.TLSCACerts } return identity, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L721-L763
go
train
// ReadTLSIdentityFromKeyPair reads TLS identity from key pair
func ReadTLSIdentityFromKeyPair(keyBytes, certBytes []byte, caCertsBytes [][]byte) (*Identity, error)
// ReadTLSIdentityFromKeyPair reads TLS identity from key pair func ReadTLSIdentityFromKeyPair(keyBytes, certBytes []byte, caCertsBytes [][]byte) (*Identity, error)
{ if len(keyBytes) == 0 { return nil, trace.BadParameter("missing private key") } if len(certBytes) == 0 { return nil, trace.BadParameter("missing certificate") } cert, err := tlsca.ParseCertificatePEM(certBytes) if err != nil { return nil, trace.Wrap(err, "failed to parse TLS certificate") } id, err := tlsca.FromSubject(cert.Subject) if err != nil { return nil, trace.Wrap(err) } if len(cert.Issuer.Organization) == 0 { return nil, trace.BadParameter("missing CA organization") } clusterName := cert.Issuer.Organization[0] if clusterName == "" { return nil, trace.BadParameter("misssing cluster name") } identity := &Identity{ ID: IdentityID{HostUUID: id.Username, Role: teleport.Role(id.Groups[0])}, ClusterName: clusterName, KeyBytes: keyBytes, TLSCertBytes: certBytes, TLSCACertsBytes: caCertsBytes, XCert: cert, } // The passed in ciphersuites don't appear to matter here since the returned // *tls.Config is never actually used? _, err = identity.TLSConfig(utils.DefaultCipherSuites()) if err != nil { return nil, trace.Wrap(err) } return identity, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L766-L837
go
train
// ReadSSHIdentityFromKeyPair reads identity from initialized keypair
func ReadSSHIdentityFromKeyPair(keyBytes, certBytes []byte) (*Identity, error)
// ReadSSHIdentityFromKeyPair reads identity from initialized keypair func ReadSSHIdentityFromKeyPair(keyBytes, certBytes []byte) (*Identity, error)
{ if len(keyBytes) == 0 { return nil, trace.BadParameter("PrivateKey: missing private key") } if len(certBytes) == 0 { return nil, trace.BadParameter("Cert: missing parameter") } pubKey, _, _, _, err := ssh.ParseAuthorizedKey(certBytes) if err != nil { return nil, trace.BadParameter("failed to parse server certificate: %v", err) } cert, ok := pubKey.(*ssh.Certificate) if !ok { return nil, trace.BadParameter("expected ssh.Certificate, got %v", pubKey) } signer, err := ssh.ParsePrivateKey(keyBytes) if err != nil { return nil, trace.BadParameter("failed to parse private key: %v", err) } // this signer authenticates using certificate signed by the cert authority // not only by the public key certSigner, err := ssh.NewCertSigner(cert, signer) if err != nil { return nil, trace.BadParameter("unsupported private key: %v", err) } // check principals on certificate if len(cert.ValidPrincipals) < 1 { return nil, trace.BadParameter("valid principals: at least one valid principal is required") } for _, validPrincipal := range cert.ValidPrincipals { if validPrincipal == "" { return nil, trace.BadParameter("valid principal can not be empty: %q", cert.ValidPrincipals) } } // check permissions on certificate if len(cert.Permissions.Extensions) == 0 { return nil, trace.BadParameter("extensions: misssing needed extensions for host roles") } roleString := cert.Permissions.Extensions[utils.CertExtensionRole] if roleString == "" { return nil, trace.BadParameter("misssing cert extension %v", utils.CertExtensionRole) } roles, err := teleport.ParseRoles(roleString) if err != nil { return nil, trace.Wrap(err) } foundRoles := len(roles) if foundRoles != 1 { return nil, trace.Errorf("expected one role per certificate. found %d: '%s'", foundRoles, roles.String()) } role := roles[0] clusterName := cert.Permissions.Extensions[utils.CertExtensionAuthority] if clusterName == "" { return nil, trace.BadParameter("missing cert extension %v", utils.CertExtensionAuthority) } return &Identity{ ID: IdentityID{HostUUID: cert.ValidPrincipals[0], Role: role}, ClusterName: clusterName, KeyBytes: keyBytes, CertBytes: certBytes, KeySigner: certSigner, Cert: cert, }, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L841-L848
go
train
// ReadLocalIdentity reads, parses and returns the given pub/pri key + cert from the // key storage (dataDir).
func ReadLocalIdentity(dataDir string, id IdentityID) (*Identity, error)
// ReadLocalIdentity reads, parses and returns the given pub/pri key + cert from the // key storage (dataDir). func ReadLocalIdentity(dataDir string, id IdentityID) (*Identity, error)
{ storage, err := NewProcessStorage(context.TODO(), dataDir) if err != nil { return nil, trace.Wrap(err) } defer storage.Close() return storage.ReadIdentity(IdentityCurrent, id.Role) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/auth/init.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/init.go#L858-L906
go
train
// DELETE IN: 2.7.0 // NOTE: Sadly, our integration tests depend on this logic // because they create remote cluster resource. Our integration // tests should be migrated to use trusted clusters instead of manually // creating tunnels. // This migration adds remote cluster resource migrating from 2.5.0 // where the presence of remote cluster was identified only by presence // of host certificate authority with cluster name not equal local cluster name
func migrateRemoteClusters(asrv *AuthServer) error
// DELETE IN: 2.7.0 // NOTE: Sadly, our integration tests depend on this logic // because they create remote cluster resource. Our integration // tests should be migrated to use trusted clusters instead of manually // creating tunnels. // This migration adds remote cluster resource migrating from 2.5.0 // where the presence of remote cluster was identified only by presence // of host certificate authority with cluster name not equal local cluster name func migrateRemoteClusters(asrv *AuthServer) error
{ clusterName, err := asrv.GetClusterName() if err != nil { return trace.Wrap(err) } certAuthorities, err := asrv.GetCertAuthorities(services.HostCA, false) if err != nil { return trace.Wrap(err) } // loop over all roles and make sure any v3 roles have permit port // forward and forward agent allowed for _, certAuthority := range certAuthorities { if certAuthority.GetName() == clusterName.GetClusterName() { log.Debugf("Migrations: skipping local cluster cert authority %q.", certAuthority.GetName()) continue } // remote cluster already exists _, err = asrv.GetRemoteCluster(certAuthority.GetName()) if err == nil { log.Debugf("Migrations: remote cluster already exists for cert authority %q.", certAuthority.GetName()) continue } if !trace.IsNotFound(err) { return trace.Wrap(err) } // the cert authority is associated with trusted cluster _, err = asrv.GetTrustedCluster(certAuthority.GetName()) if err == nil { log.Debugf("Migrations: trusted cluster resource exists for cert authority %q.", certAuthority.GetName()) continue } if !trace.IsNotFound(err) { return trace.Wrap(err) } remoteCluster, err := services.NewRemoteCluster(certAuthority.GetName()) if err != nil { return trace.Wrap(err) } err = asrv.CreateRemoteCluster(remoteCluster) if err != nil { if !trace.IsAlreadyExists(err) { return trace.Wrap(err) } } log.Infof("Migrations: added remote cluster resource for cert authority %q.", certAuthority.GetName()) } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L86-L111
go
train
// NewAdminRole is the default admin role for all local users if another role // is not explicitly assigned (Enterprise only).
func NewAdminRole() Role
// NewAdminRole is the default admin role for all local users if another role // is not explicitly assigned (Enterprise only). func NewAdminRole() Role
{ role := &RoleV3{ Kind: KindRole, Version: V3, Metadata: Metadata{ Name: teleport.AdminRoleName, Namespace: defaults.Namespace, }, Spec: RoleSpecV3{ Options: RoleOptions{ CertificateFormat: teleport.CertificateFormatStandard, MaxSessionTTL: NewDuration(defaults.MaxCertDuration), PortForwarding: NewBoolOption(true), ForwardAgent: NewBool(true), }, Allow: RoleConditions{ Namespaces: []string{defaults.Namespace}, NodeLabels: Labels{Wildcard: []string{Wildcard}}, Rules: CopyRulesSlice(AdminUserRules), }, }, } role.SetLogins(Allow, modules.GetModules().DefaultAllowedLogins()) role.SetKubeGroups(Allow, modules.GetModules().DefaultKubeGroups()) return role }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L115-L133
go
train
// NewImplicitRole is the default implicit role that gets added to all // RoleSets.
func NewImplicitRole() Role
// NewImplicitRole is the default implicit role that gets added to all // RoleSets. func NewImplicitRole() Role
{ return &RoleV3{ Kind: KindRole, Version: V3, Metadata: Metadata{ Name: teleport.DefaultImplicitRole, Namespace: defaults.Namespace, }, Spec: RoleSpecV3{ Options: RoleOptions{ MaxSessionTTL: MaxDuration(), }, Allow: RoleConditions{ Namespaces: []string{defaults.Namespace}, Rules: CopyRulesSlice(DefaultImplicitRules), }, }, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L136-L158
go
train
// RoleForUser creates an admin role for a services.User.
func RoleForUser(u User) Role
// RoleForUser creates an admin role for a services.User. func RoleForUser(u User) Role
{ return &RoleV3{ Kind: KindRole, Version: V3, Metadata: Metadata{ Name: RoleNameForUser(u.GetName()), Namespace: defaults.Namespace, }, Spec: RoleSpecV3{ Options: RoleOptions{ CertificateFormat: teleport.CertificateFormatStandard, MaxSessionTTL: NewDuration(defaults.MaxCertDuration), PortForwarding: NewBoolOption(true), ForwardAgent: NewBool(true), }, Allow: RoleConditions{ Namespaces: []string{defaults.Namespace}, NodeLabels: Labels{Wildcard: []string{Wildcard}}, Rules: CopyRulesSlice(AdminUserRules), }, }, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L161-L180
go
train
// RoleForCertauthority creates role using services.CertAuthority.
func RoleForCertAuthority(ca CertAuthority) Role
// RoleForCertauthority creates role using services.CertAuthority. func RoleForCertAuthority(ca CertAuthority) Role
{ return &RoleV3{ Kind: KindRole, Version: V3, Metadata: Metadata{ Name: RoleNameForCertAuthority(ca.GetClusterName()), Namespace: defaults.Namespace, }, Spec: RoleSpecV3{ Options: RoleOptions{ MaxSessionTTL: NewDuration(defaults.MaxCertDuration), }, Allow: RoleConditions{ Namespaces: []string{defaults.Namespace}, NodeLabels: Labels{Wildcard: []string{Wildcard}}, Rules: CopyRulesSlice(DefaultCertAuthorityRules), }, }, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L183-L189
go
train
// ConvertV1CertAuthority converts V1 cert authority for new CA and Role
func ConvertV1CertAuthority(v1 *CertAuthorityV1) (CertAuthority, Role)
// ConvertV1CertAuthority converts V1 cert authority for new CA and Role func ConvertV1CertAuthority(v1 *CertAuthorityV1) (CertAuthority, Role)
{ ca := v1.V2() role := RoleForCertAuthority(ca) role.SetLogins(Allow, v1.AllowedLogins) ca.AddRole(role.GetName()) return ca, role }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L268-L342
go
train
// ApplyTraits applies the passed in traits to any variables within the role // and returns itself.
func ApplyTraits(r Role, traits map[string][]string) Role
// ApplyTraits applies the passed in traits to any variables within the role // and returns itself. func ApplyTraits(r Role, traits map[string][]string) Role
{ for _, condition := range []RoleConditionType{Allow, Deny} { inLogins := r.GetLogins(condition) var outLogins []string for _, login := range inLogins { variableValues, err := applyValueTraits(login, traits) if err != nil { if !trace.IsNotFound(err) { log.Debugf("Skipping login %v: %v.", login, err) } continue } // Filter out logins that come from variables that are not valid Unix logins. for _, variableValue := range variableValues { if !cstrings.IsValidUnixUser(variableValue) { log.Debugf("Skipping login %v, not a valid Unix login.", variableValue) continue } // A valid variable was found in the traits, append it to the list of logins. outLogins = append(outLogins, variableValue) } } r.SetLogins(condition, utils.Deduplicate(outLogins)) // apply templates to kubernetes groups inKubeGroups := r.GetKubeGroups(condition) var outKubeGroups []string for _, group := range inKubeGroups { variableValues, err := applyValueTraits(group, traits) if err != nil { if !trace.IsNotFound(err) { log.Debugf("Skipping kube group %v: %v.", group, err) } continue } outKubeGroups = append(outKubeGroups, variableValues...) } r.SetKubeGroups(condition, utils.Deduplicate(outKubeGroups)) inLabels := r.GetNodeLabels(condition) // to avoid unnecessary allocations if inLabels != nil { outLabels := make(Labels, len(inLabels)) // every key will be mapped to the first value for key, vals := range inLabels { keyVars, err := applyValueTraits(key, traits) if err != nil { // empty key will not match anything log.Debugf("Setting empty node label pair %q -> %q: %v", key, vals, err) keyVars = []string{""} } var values []string for _, val := range vals { valVars, err := applyValueTraits(val, traits) if err != nil { log.Debugf("Setting empty node label value %q -> %q: %v", key, val, err) // empty value will not match anything valVars = []string{""} } values = append(values, valVars...) } outLabels[keyVars[0]] = utils.Deduplicate(values) } r.SetNodeLabels(condition, outLabels) } } return r }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L349-L374
go
train
// applyValueTraits applies the passed in traits to the variable, // returns BadParameter in case if referenced variable is unsupported, // returns NotFound in case if referenced trait is missing, // mapped list of values otherwise, the function guarantees to return // at least one value in case if return value is nil
func applyValueTraits(val string, traits map[string][]string) ([]string, error)
// applyValueTraits applies the passed in traits to the variable, // returns BadParameter in case if referenced variable is unsupported, // returns NotFound in case if referenced trait is missing, // mapped list of values otherwise, the function guarantees to return // at least one value in case if return value is nil func applyValueTraits(val string, traits map[string][]string) ([]string, error)
{ // Extract the variablePrefix and variableName from the role variable. variablePrefix, variableName, err := parse.IsRoleVariable(val) if err != nil { if !trace.IsNotFound(err) { return nil, trace.Wrap(err) } return []string{val}, nil } // For internal traits, only internal.logins and internal.kubernetes_groups is supported at the moment. if variablePrefix == teleport.TraitInternalPrefix { if variableName != teleport.TraitLogins && variableName != teleport.TraitKubeGroups { return nil, trace.BadParameter("unsupported variable %q", variableName) } } // If the variable is not found in the traits, skip it. variableValues, ok := traits[variableName] if !ok || len(variableValues) == 0 { return nil, trace.NotFound("variable %q not found in traits", variableName) } return append([]string{}, variableValues...), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L408-L429
go
train
// Equals returns true if the roles are equal. Roles are equal if options, // namespaces, logins, labels, and conditions match.
func (r *RoleV3) Equals(other Role) bool
// Equals returns true if the roles are equal. Roles are equal if options, // namespaces, logins, labels, and conditions match. func (r *RoleV3) Equals(other Role) bool
{ if !r.GetOptions().Equals(other.GetOptions()) { return false } for _, condition := range []RoleConditionType{Allow, Deny} { if !utils.StringSlicesEqual(r.GetLogins(condition), other.GetLogins(condition)) { return false } if !utils.StringSlicesEqual(r.GetNamespaces(condition), other.GetNamespaces(condition)) { return false } if !r.GetNodeLabels(condition).Equals(other.GetNodeLabels(condition)) { return false } if !RuleSlicesEqual(r.GetRules(condition), other.GetRules(condition)) { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L433-L435
go
train
// ApplyTraits applies the passed in traits to any variables within the role // and returns itself.
func (r *RoleV3) ApplyTraits(traits map[string][]string) Role
// ApplyTraits applies the passed in traits to any variables within the role // and returns itself. func (r *RoleV3) ApplyTraits(traits map[string][]string) Role
{ return ApplyTraits(r, traits) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L438-L440
go
train
// SetExpiry sets expiry time for the object.
func (r *RoleV3) SetExpiry(expires time.Time)
// SetExpiry sets expiry time for the object. func (r *RoleV3) SetExpiry(expires time.Time)
{ r.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L478-L483
go
train
// GetLogins gets system logins for allow or deny condition.
func (r *RoleV3) GetLogins(rct RoleConditionType) []string
// GetLogins gets system logins for allow or deny condition. func (r *RoleV3) GetLogins(rct RoleConditionType) []string
{ if rct == Allow { return r.Spec.Allow.Logins } return r.Spec.Deny.Logins }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L486-L494
go
train
// SetLogins sets system logins for allow or deny condition.
func (r *RoleV3) SetLogins(rct RoleConditionType, logins []string)
// SetLogins sets system logins for allow or deny condition. func (r *RoleV3) SetLogins(rct RoleConditionType, logins []string)
{ lcopy := utils.CopyStrings(logins) if rct == Allow { r.Spec.Allow.Logins = lcopy } else { r.Spec.Deny.Logins = lcopy } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L497-L502
go
train
// GetKubeGroups returns kubernetes groups
func (r *RoleV3) GetKubeGroups(rct RoleConditionType) []string
// GetKubeGroups returns kubernetes groups func (r *RoleV3) GetKubeGroups(rct RoleConditionType) []string
{ if rct == Allow { return r.Spec.Allow.KubeGroups } return r.Spec.Deny.KubeGroups }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L505-L513
go
train
// SetKubeGroups sets kubernetes groups for allow or deny condition.
func (r *RoleV3) SetKubeGroups(rct RoleConditionType, groups []string)
// SetKubeGroups sets kubernetes groups for allow or deny condition. func (r *RoleV3) SetKubeGroups(rct RoleConditionType, groups []string)
{ lcopy := utils.CopyStrings(groups) if rct == Allow { r.Spec.Allow.KubeGroups = lcopy } else { r.Spec.Deny.KubeGroups = lcopy } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L516-L521
go
train
// GetNamespaces gets a list of namespaces this role is allowed or denied access to.
func (r *RoleV3) GetNamespaces(rct RoleConditionType) []string
// GetNamespaces gets a list of namespaces this role is allowed or denied access to. func (r *RoleV3) GetNamespaces(rct RoleConditionType) []string
{ if rct == Allow { return r.Spec.Allow.Namespaces } return r.Spec.Deny.Namespaces }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L524-L532
go
train
// GetNamespaces sets a list of namespaces this role is allowed or denied access to.
func (r *RoleV3) SetNamespaces(rct RoleConditionType, namespaces []string)
// GetNamespaces sets a list of namespaces this role is allowed or denied access to. func (r *RoleV3) SetNamespaces(rct RoleConditionType, namespaces []string)
{ ncopy := utils.CopyStrings(namespaces) if rct == Allow { r.Spec.Allow.Namespaces = ncopy } else { r.Spec.Deny.Namespaces = ncopy } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L535-L540
go
train
// GetNodeLabels gets the map of node labels this role is allowed or denied access to.
func (r *RoleV3) GetNodeLabels(rct RoleConditionType) Labels
// GetNodeLabels gets the map of node labels this role is allowed or denied access to. func (r *RoleV3) GetNodeLabels(rct RoleConditionType) Labels
{ if rct == Allow { return r.Spec.Allow.NodeLabels } return r.Spec.Deny.NodeLabels }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L543-L549
go
train
// SetNodeLabels sets the map of node labels this role is allowed or denied access to.
func (r *RoleV3) SetNodeLabels(rct RoleConditionType, labels Labels)
// SetNodeLabels sets the map of node labels this role is allowed or denied access to. func (r *RoleV3) SetNodeLabels(rct RoleConditionType, labels Labels)
{ if rct == Allow { r.Spec.Allow.NodeLabels = labels.Clone() } else { r.Spec.Deny.NodeLabels = labels.Clone() } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L552-L557
go
train
// GetRules gets all allow or deny rules.
func (r *RoleV3) GetRules(rct RoleConditionType) []Rule
// GetRules gets all allow or deny rules. func (r *RoleV3) GetRules(rct RoleConditionType) []Rule
{ if rct == Allow { return r.Spec.Allow.Rules } return r.Spec.Deny.Rules }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L560-L568
go
train
// SetRules sets an allow or deny rule.
func (r *RoleV3) SetRules(rct RoleConditionType, in []Rule)
// SetRules sets an allow or deny rule. func (r *RoleV3) SetRules(rct RoleConditionType, in []Rule)
{ rcopy := CopyRulesSlice(in) if rct == Allow { r.Spec.Allow.Rules = rcopy } else { r.Spec.Deny.Rules = rcopy } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L571-L638
go
train
// Check checks validity of all parameters and sets defaults
func (r *RoleV3) CheckAndSetDefaults() error
// Check checks validity of all parameters and sets defaults func (r *RoleV3) CheckAndSetDefaults() error
{ err := r.Metadata.CheckAndSetDefaults() if err != nil { return trace.Wrap(err) } // make sure we have defaults for all fields if r.Spec.Options.CertificateFormat == "" { r.Spec.Options.CertificateFormat = teleport.CertificateFormatStandard } if r.Spec.Options.MaxSessionTTL.Value() == 0 { r.Spec.Options.MaxSessionTTL = NewDuration(defaults.MaxCertDuration) } if r.Spec.Options.PortForwarding == nil { r.Spec.Options.PortForwarding = NewBoolOption(true) } if r.Spec.Allow.Namespaces == nil { r.Spec.Allow.Namespaces = []string{defaults.Namespace} } if r.Spec.Allow.NodeLabels == nil { r.Spec.Allow.NodeLabels = Labels{Wildcard: []string{Wildcard}} } if r.Spec.Deny.Namespaces == nil { r.Spec.Deny.Namespaces = []string{defaults.Namespace} } // if we find {{ or }} but the syntax is invalid, the role is invalid for _, condition := range []RoleConditionType{Allow, Deny} { for _, login := range r.GetLogins(condition) { if strings.Contains(login, "{{") || strings.Contains(login, "}}") { _, _, err := parse.IsRoleVariable(login) if err != nil { return trace.BadParameter("invalid login found: %v", login) } } } } // check and correct the session ttl if r.Spec.Options.MaxSessionTTL.Value() <= 0 { r.Spec.Options.MaxSessionTTL = NewDuration(defaults.MaxCertDuration) } // restrict wildcards for _, login := range r.Spec.Allow.Logins { if login == Wildcard { return trace.BadParameter("wildcard matcher is not allowed in logins") } } for key, val := range r.Spec.Allow.NodeLabels { if key == Wildcard && !(len(val) == 1 && val[0] == Wildcard) { return trace.BadParameter("selector *:<val> is not supported") } } for i := range r.Spec.Allow.Rules { err := r.Spec.Allow.Rules[i].CheckAndSetDefaults() if err != nil { return trace.BadParameter("failed to process 'allow' rule %v: %v", i, err) } } for i := range r.Spec.Deny.Rules { err := r.Spec.Deny.Rules[i].CheckAndSetDefaults() if err != nil { return trace.BadParameter("failed to process 'deny' rule %v: %v", i, err) } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L641-L644
go
train
// String returns the human readable representation of a role.
func (r *RoleV3) String() string
// String returns the human readable representation of a role. func (r *RoleV3) String() string
{ return fmt.Sprintf("Role(Name=%v,Options=%v,Allow=%+v,Deny=%+v)", r.GetName(), r.Spec.Options, r.Spec.Allow, r.Spec.Deny) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L647-L654
go
train
// Equals checks if all the key/values in the RoleOptions map match.
func (o RoleOptions) Equals(other RoleOptions) bool
// Equals checks if all the key/values in the RoleOptions map match. func (o RoleOptions) Equals(other RoleOptions) bool
{ return (o.ForwardAgent.Value() == other.ForwardAgent.Value() && o.MaxSessionTTL.Value() == other.MaxSessionTTL.Value() && BoolDefaultTrue(o.PortForwarding) == BoolDefaultTrue(other.PortForwarding) && o.CertificateFormat == other.CertificateFormat && o.ClientIdleTimeout.Value() == other.ClientIdleTimeout.Value() && o.DisconnectExpiredCert.Value() == other.DisconnectExpiredCert.Value()) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L658-L677
go
train
// Equals returns true if the role conditions (logins, namespaces, labels, // and rules) are equal and false if they are not.
func (r *RoleConditions) Equals(o RoleConditions) bool
// Equals returns true if the role conditions (logins, namespaces, labels, // and rules) are equal and false if they are not. func (r *RoleConditions) Equals(o RoleConditions) bool
{ if !utils.StringSlicesEqual(r.Logins, o.Logins) { return false } if !utils.StringSlicesEqual(r.Namespaces, o.Namespaces) { return false } if !r.NodeLabels.Equals(o.NodeLabels) { return false } if len(r.Rules) != len(o.Rules) { return false } for i := range r.Rules { if !r.Rules[i].Equals(o.Rules[i]) { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L680-L685
go
train
// NewRule creates a rule based on a resource name and a list of verbs
func NewRule(resource string, verbs []string) Rule
// NewRule creates a rule based on a resource name and a list of verbs func NewRule(resource string, verbs []string) Rule
{ return Rule{ Resources: []string{resource}, Verbs: verbs, } }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L688-L718
go
train
// CheckAndSetDefaults checks and sets defaults for this rule
func (r *Rule) CheckAndSetDefaults() error
// CheckAndSetDefaults checks and sets defaults for this rule func (r *Rule) CheckAndSetDefaults() error
{ if len(r.Resources) == 0 { return trace.BadParameter("missing resources to match") } if len(r.Verbs) == 0 { return trace.BadParameter("missing verbs") } if len(r.Where) != 0 { parser, err := GetWhereParserFn()(&Context{}) if err != nil { return trace.Wrap(err) } _, err = parser.Parse(r.Where) if err != nil { return trace.BadParameter("could not parse 'where' rule: %q, error: %v", r.Where, err) } } if len(r.Actions) != 0 { parser, err := GetActionsParserFn()(&Context{}) if err != nil { return trace.Wrap(err) } for i, action := range r.Actions { _, err = parser.Parse(action) if err != nil { return trace.BadParameter("could not parse action %v %q, error: %v", i, action, err) } } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L722-L748
go
train
// score is a sorting score of the rule, the more the score, the more // specific the rule is
func (r *Rule) score() int
// score is a sorting score of the rule, the more the score, the more // specific the rule is func (r *Rule) score() int
{ score := 0 // wilcard rules are less specific if utils.SliceContainsStr(r.Resources, Wildcard) { score -= 4 } else if len(r.Resources) == 1 { // rules that match specific resource are more specific than // fields that match several resources score += 2 } // rules that have wilcard verbs are less specific if utils.SliceContainsStr(r.Verbs, Wildcard) { score -= 2 } // rules that supply 'where' or 'actions' are more specific // having 'where' or 'actions' is more important than // whether the rules are wildcard or not, so here we have +8 vs // -4 and -2 score penalty for wildcards in resources and verbs if len(r.Where) > 0 { score += 8 } // rules featuring actions are more specific if len(r.Actions) > 0 { score += 8 } return score }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L760-L762
go
train
// IsMoreSpecificThan returns true if the rule is more specific than the other. // // * nRule matching wildcard resource is less specific // than same rule matching specific resource. // * Rule that has wildcard verbs is less specific // than the same rules matching specific verb. // * Rule that has where section is more specific // than the same rule without where section. // * Rule that has actions list is more specific than // rule without actions list.
func (r *Rule) IsMoreSpecificThan(o Rule) bool
// IsMoreSpecificThan returns true if the rule is more specific than the other. // // * nRule matching wildcard resource is less specific // than same rule matching specific resource. // * Rule that has wildcard verbs is less specific // than the same rules matching specific verb. // * Rule that has where section is more specific // than the same rule without where section. // * Rule that has actions list is more specific than // rule without actions list. func (r *Rule) IsMoreSpecificThan(o Rule) bool
{ return r.score() > o.score() }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L766-L779
go
train
// MatchesWhere returns true if Where rule matches // Empty Where block always matches
func (r *Rule) MatchesWhere(parser predicate.Parser) (bool, error)
// MatchesWhere returns true if Where rule matches // Empty Where block always matches func (r *Rule) MatchesWhere(parser predicate.Parser) (bool, error)
{ if r.Where == "" { return true, nil } ifn, err := parser.Parse(r.Where) if err != nil { return false, trace.Wrap(err) } fn, ok := ifn.(predicate.BoolPredicate) if !ok { return false, trace.BadParameter("unsupported type: %T", ifn) } return fn(), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L782-L795
go
train
// ProcessActions processes actions specified for this rule
func (r *Rule) ProcessActions(parser predicate.Parser) error
// ProcessActions processes actions specified for this rule func (r *Rule) ProcessActions(parser predicate.Parser) error
{ for _, action := range r.Actions { ifn, err := parser.Parse(action) if err != nil { return trace.Wrap(err) } fn, ok := ifn.(predicate.BoolPredicate) if !ok { return trace.BadParameter("unsupported type: %T", ifn) } fn() } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L798-L805
go
train
// HasResource returns true if the rule has the specified resource.
func (r *Rule) HasResource(resource string) bool
// HasResource returns true if the rule has the specified resource. func (r *Rule) HasResource(resource string) bool
{ for _, r := range r.Resources { if r == resource { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L809-L823
go
train
// HasVerb returns true if the rule has verb, // this method also matches wildcard
func (r *Rule) HasVerb(verb string) bool
// HasVerb returns true if the rule has verb, // this method also matches wildcard func (r *Rule) HasVerb(verb string) bool
{ for _, v := range r.Verbs { // readnosecrets can be satisfied by having readnosecrets or read if verb == VerbReadNoSecrets { if v == VerbReadNoSecrets || v == VerbRead { return true } continue } if v == verb { return true } } return false }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L826-L840
go
train
// Equals returns true if the rule equals to another
func (r *Rule) Equals(other Rule) bool
// Equals returns true if the rule equals to another func (r *Rule) Equals(other Rule) bool
{ if !utils.StringSlicesEqual(r.Resources, other.Resources) { return false } if !utils.StringSlicesEqual(r.Verbs, other.Verbs) { return false } if !utils.StringSlicesEqual(r.Actions, other.Actions) { return false } if r.Where != other.Where { return false } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L853-L890
go
train
// MatchRule tests if the resource name and verb are in a given list of rules. // More specific rules will be matched first. See Rule.IsMoreSpecificThan // for exact specs on whether the rule is more or less specific. // // Specifying order solves the problem on having multiple rules, e.g. one wildcard // rule can override more specific rules with 'where' sections that can have // 'actions' lists with side effects that will not be triggered otherwise. //
func (set RuleSet) Match(whereParser predicate.Parser, actionsParser predicate.Parser, resource string, verb string) (bool, error)
// MatchRule tests if the resource name and verb are in a given list of rules. // More specific rules will be matched first. See Rule.IsMoreSpecificThan // for exact specs on whether the rule is more or less specific. // // Specifying order solves the problem on having multiple rules, e.g. one wildcard // rule can override more specific rules with 'where' sections that can have // 'actions' lists with side effects that will not be triggered otherwise. // func (set RuleSet) Match(whereParser predicate.Parser, actionsParser predicate.Parser, resource string, verb string) (bool, error)
{ // empty set matches nothing if len(set) == 0 { return false, nil } // check for matching resource by name // the most specific rule should win rules := set[resource] for _, rule := range rules { match, err := rule.MatchesWhere(whereParser) if err != nil { return false, trace.Wrap(err) } if match && (rule.HasVerb(Wildcard) || rule.HasVerb(verb)) { if err := rule.ProcessActions(actionsParser); err != nil { return true, trace.Wrap(err) } return true, nil } } // check for wildcard resource matcher for _, rule := range set[Wildcard] { match, err := rule.MatchesWhere(whereParser) if err != nil { return false, trace.Wrap(err) } if match && (rule.HasVerb(Wildcard) || rule.HasVerb(verb)) { if err := rule.ProcessActions(actionsParser); err != nil { return true, trace.Wrap(err) } return true, nil } } return false, nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L893-L899
go
train
// Slice returns slice from a set
func (set RuleSet) Slice() []Rule
// Slice returns slice from a set func (set RuleSet) Slice() []Rule
{ var out []Rule for _, rules := range set { out = append(out, rules...) } return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L902-L925
go
train
// MakeRuleSet converts slice of rules to the set of rules
func MakeRuleSet(rules []Rule) RuleSet
// MakeRuleSet converts slice of rules to the set of rules func MakeRuleSet(rules []Rule) RuleSet
{ set := make(RuleSet) for _, rule := range rules { for _, resource := range rule.Resources { rules, ok := set[resource] if !ok { set[resource] = []Rule{rule} } else { rules = append(rules, rule) set[resource] = rules } } } for resource := range set { rules := set[resource] // sort rules by most specific rule, the rule that has actions // is more specific than the one that has no actions sort.Slice(rules, func(i, j int) bool { return rules[i].IsMoreSpecificThan(rules[j]) }) set[resource] = rules } return set }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L928-L932
go
train
// CopyRulesSlice copies input slice of Rules and returns the copy
func CopyRulesSlice(in []Rule) []Rule
// CopyRulesSlice copies input slice of Rules and returns the copy func CopyRulesSlice(in []Rule) []Rule
{ out := make([]Rule, len(in)) copy(out, in) return out }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L935-L945
go
train
// RuleSlicesEqual returns true if two rule slices are equal
func RuleSlicesEqual(a, b []Rule) bool
// RuleSlicesEqual returns true if two rule slices are equal func RuleSlicesEqual(a, b []Rule) bool
{ if len(a) != len(b) { return false } for i := range a { if !a[i].Equals(b[i]) { return false } } return true }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L993-L995
go
train
// Equals test roles for equality. Roles are considered equal if all resources, // logins, namespaces, labels, and options match.
func (r *RoleV2) Equals(other Role) bool
// Equals test roles for equality. Roles are considered equal if all resources, // logins, namespaces, labels, and options match. func (r *RoleV2) Equals(other Role) bool
{ return r.V3().Equals(other) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L998-L1003
go
train
// SetResource sets resource rule
func (r *RoleV2) SetResource(kind string, actions []string)
// SetResource sets resource rule func (r *RoleV2) SetResource(kind string, actions []string)
{ if r.Spec.Resources == nil { r.Spec.Resources = make(map[string][]string) } r.Spec.Resources[kind] = actions }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1006-L1008
go
train
// RemoveResource deletes resource entry
func (r *RoleV2) RemoveResource(kind string)
// RemoveResource deletes resource entry func (r *RoleV2) RemoveResource(kind string)
{ delete(r.Spec.Resources, kind) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1016-L1018
go
train
// SetNodeLabels sets node labels for role
func (r *RoleV2) SetNodeLabels(labels map[string]string)
// SetNodeLabels sets node labels for role func (r *RoleV2) SetNodeLabels(labels map[string]string)
{ r.Spec.NodeLabels = labels }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1021-L1023
go
train
// SetMaxSessionTTL sets a maximum TTL for SSH or Web session
func (r *RoleV2) SetMaxSessionTTL(duration time.Duration)
// SetMaxSessionTTL sets a maximum TTL for SSH or Web session func (r *RoleV2) SetMaxSessionTTL(duration time.Duration)
{ r.Spec.MaxSessionTTL = Duration(duration) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1026-L1028
go
train
// SetExpiry sets expiry time for the object
func (r *RoleV2) SetExpiry(expires time.Time)
// SetExpiry sets expiry time for the object func (r *RoleV2) SetExpiry(expires time.Time)
{ r.Metadata.SetExpiry(expires) }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1097-L1141
go
train
// Check checks validity of all parameters and sets defaults
func (r *RoleV2) CheckAndSetDefaults() error
// Check checks validity of all parameters and sets defaults func (r *RoleV2) CheckAndSetDefaults() error
{ // make sure we have defaults for all fields if r.Metadata.Name == "" { return trace.BadParameter("missing parameter Name") } if r.Metadata.Namespace == "" { r.Metadata.Namespace = defaults.Namespace } if r.Spec.MaxSessionTTL == 0 { r.Spec.MaxSessionTTL = Duration(defaults.MaxCertDuration) } if r.Spec.MaxSessionTTL.Duration() < defaults.MinCertDuration { return trace.BadParameter("maximum session TTL can not be less than %v", defaults.MinCertDuration) } if r.Spec.Namespaces == nil { r.Spec.Namespaces = []string{defaults.Namespace} } if r.Spec.NodeLabels == nil { r.Spec.NodeLabels = map[string]string{Wildcard: Wildcard} } if r.Spec.Resources == nil { r.Spec.Resources = map[string][]string{ KindSSHSession: RO(), KindRole: RO(), KindNode: RO(), KindAuthServer: RO(), KindReverseTunnel: RO(), KindCertAuthority: RO(), } } // restrict wildcards for _, login := range r.Spec.Logins { if login == Wildcard { return trace.BadParameter("wildcard matcher is not allowed in logins") } } for key, val := range r.Spec.NodeLabels { if key == Wildcard && val != Wildcard { return trace.BadParameter("selector *:<val> is not supported") } } return nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1271-L1278
go
train
// FromSpec returns new RoleSet created from spec
func FromSpec(name string, spec RoleSpecV3) (RoleSet, error)
// FromSpec returns new RoleSet created from spec func FromSpec(name string, spec RoleSpecV3) (RoleSet, error)
{ role, err := NewRole(name, spec) if err != nil { return nil, trace.Wrap(err) } return NewRoleSet(role), nil }
gravitational/teleport
d5243dbe8d36bba44bf640c08f1c49185ed2c8a4
lib/services/role.go
https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/role.go#L1297-L1312
go
train
// NewRole constructs new standard role
func NewRole(name string, spec RoleSpecV3) (Role, error)
// NewRole constructs new standard role func NewRole(name string, spec RoleSpecV3) (Role, error)
{ role := RoleV3{ Kind: KindRole, Version: V3, Metadata: Metadata{ Name: name, Namespace: defaults.Namespace, }, Spec: spec, } if err := role.CheckAndSetDefaults(); err != nil { return nil, trace.Wrap(err) } return &role, nil }