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/methods.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/methods.go#L274-L320 | go | train | // AuthenticateSSHUser authenticates web user, creates and returns web session
// in case if authentication is successful | func (s *AuthServer) AuthenticateSSHUser(req AuthenticateSSHRequest) (*SSHLoginResponse, error) | // AuthenticateSSHUser authenticates web user, creates and returns web session
// in case if authentication is successful
func (s *AuthServer) AuthenticateSSHUser(req AuthenticateSSHRequest) (*SSHLoginResponse, error) | {
clusterName, err := s.GetClusterName()
if err != nil {
return nil, trace.Wrap(err)
}
if err := s.AuthenticateUser(req.AuthenticateUserRequest); err != nil {
return nil, trace.Wrap(err)
}
user, err := s.GetUser(req.Username)
if err != nil {
return nil, trace.Wrap(err)
}
roles, err := services.FetchRoles(user.GetRoles(), s, user.GetTraits())
if err != nil {
return nil, trace.Wrap(err)
}
// Return the host CA for this cluster only.
authority, err := s.GetCertAuthority(services.CertAuthID{
Type: services.HostCA,
DomainName: clusterName.GetClusterName(),
}, false)
if err != nil {
return nil, trace.Wrap(err)
}
hostCertAuthorities := []services.CertAuthority{
authority,
}
certs, err := s.generateUserCert(certRequest{
user: user,
roles: roles,
ttl: req.TTL,
publicKey: req.PublicKey,
compatibility: req.CompatibilityMode,
})
if err != nil {
return nil, trace.Wrap(err)
}
return &SSHLoginResponse{
Username: req.Username,
Cert: certs.ssh,
TLSCert: certs.tls,
HostSigners: AuthoritiesToTrustedCerts(hostCertAuthorities),
}, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/pam/pam.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/pam.go#L75-L88 | go | train | //export writeCallback | func writeCallback(index C.int, stream C.int, s *C.char) | //export writeCallback
func writeCallback(index C.int, stream C.int, s *C.char) | {
handle, err := lookupHandler(int(index))
if err != nil {
log.Errorf("Unable to write to output stream: %v", err)
return
}
// To prevent poorly written PAM modules from sending more data than they
// should, cap strings to the maximum message size that PAM allows.
str := C.GoStringN(s, C.int(C.strnlen(s, C.PAM_MAX_MSG_SIZE)))
// Write to the stream (typically stdout or stderr or equivalent).
handle.writeStream(int(stream), str)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/pam/pam.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/pam.go#L91-L121 | go | train | //export readCallback | func readCallback(index C.int, e C.int) *C.char | //export readCallback
func readCallback(index C.int, e C.int) *C.char | {
handle, err := lookupHandler(int(index))
if err != nil {
log.Errorf("Unable to read from input stream: %v", err)
return nil
}
var echo bool
if e == 1 {
echo = true
}
// Read from the stream (typically stdin or equivalent).
s, err := handle.readStream(echo)
if err != nil {
log.Errorf("Unable to read from input stream: %v", err)
return nil
}
// Return one less than PAM_MAX_RESP_SIZE to prevent a Teleport user from
// sending more than a PAM module can handle and to allow space for \0.
//
// Note: The function C.CString allocates memory using malloc. The memory is
// not released in Go code because the caller of the callback function (PAM
// module) will release it. C.CString will null terminate s.
n := int(C.PAM_MAX_RESP_SIZE)
if len(s) > n-1 {
return C.CString(s[:n-1])
}
return C.CString(s)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/pam/pam.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/pam.go#L125-L136 | go | train | // registerHandler will register a instance of *PAM with the package level
// handlers to support callbacks from C. | func registerHandler(p *PAM) int | // registerHandler will register a instance of *PAM with the package level
// handlers to support callbacks from C.
func registerHandler(p *PAM) int | {
handlerMu.Lock()
defer handlerMu.Unlock()
// The make_pam_conv function allocates struct pam_conv on the heap. It will
// be released by Close function.
handlerCount = handlerCount + 1
p.conv = C.make_pam_conv(C.int(handlerCount))
handlers[handlerCount] = p
return handlerCount
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/pam/pam.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/pam.go#L140-L145 | go | train | // unregisterHandler will remove the PAM handle from the package level map
// once no more C callbacks can come back. | func unregisterHandler(handlerIndex int) | // unregisterHandler will remove the PAM handle from the package level map
// once no more C callbacks can come back.
func unregisterHandler(handlerIndex int) | {
handlerMu.Lock()
defer handlerMu.Unlock()
delete(handlers, handlerIndex)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/pam/pam.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/pam.go#L148-L158 | go | train | // lookupHandler returns a particular handler from the package level map. | func lookupHandler(handlerIndex int) (handler, error) | // lookupHandler returns a particular handler from the package level map.
func lookupHandler(handlerIndex int) (handler, error) | {
handlerMu.Lock()
defer handlerMu.Unlock()
handle, ok := handlers[handlerIndex]
if !ok {
return nil, trace.BadParameter("handler with index %v not registered", handlerIndex)
}
return handle, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/pam/pam.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/pam.go#L215-L271 | go | train | // Open creates a PAM context and initiates a PAM transaction to check the
// account and then opens a session. | func Open(config *Config) (*PAM, error) | // Open creates a PAM context and initiates a PAM transaction to check the
// account and then opens a session.
func Open(config *Config) (*PAM, error) | {
if config == nil {
return nil, trace.BadParameter("PAM configuration is required.")
}
err := config.CheckDefaults()
if err != nil {
return nil, trace.Wrap(err)
}
p := &PAM{
pamh: nil,
stdin: config.Stdin,
stdout: config.Stdout,
stderr: config.Stderr,
}
// Both config.ServiceName and config.Username convert between Go strings to
// C strings. Since the C strings are allocated on the heap in Go code, this
// memory must be released (and will be on the call to the Close method).
p.service_name = C.CString(config.ServiceName)
p.user = C.CString(config.Username)
// C code does not know that this PAM context exists. To ensure the
// conversation function can get messages to the right context, a handle
// registry at the package level is created (handlers). Each instance of the
// PAM context has it's own handle which is used to communicate between C
// and a instance of a PAM context.
p.handlerIndex = registerHandler(p)
// Create and initialize a PAM context. The pam_start function will
// allocate pamh if needed and the pam_end function will release any
// allocated memory.
p.retval = C._pam_start(pamHandle, p.service_name, p.user, p.conv, &p.pamh)
if p.retval != C.PAM_SUCCESS {
return nil, p.codeToError(p.retval)
}
// Check that the *nix account is valid. Checking an account varies based off
// the PAM modules used in the account stack. Typically this consists of
// checking if the account is expired or has access restrictions.
//
// Note: This function does not perform any authentication!
retval := C._pam_acct_mgmt(pamHandle, p.pamh, 0)
if retval != C.PAM_SUCCESS {
return nil, p.codeToError(retval)
}
// Open a user session. Opening a session varies based off the PAM modules
// used in the "session" stack. Opening a session typically consists of
// printing the MOTD, mounting a home directory, updating auth.log.
p.retval = C._pam_open_session(pamHandle, p.pamh, 0)
if p.retval != C.PAM_SUCCESS {
return nil, p.codeToError(p.retval)
}
return p, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/pam/pam.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/pam.go#L275-L300 | go | train | // Close will close the session, the PAM context, and release any allocated
// memory. | func (p *PAM) Close() error | // Close will close the session, the PAM context, and release any allocated
// memory.
func (p *PAM) Close() error | {
// Close the PAM session. Closing a session can entail anything from
// unmounting a home directory and updating auth.log.
p.retval = C._pam_close_session(pamHandle, p.pamh, 0)
if p.retval != C.PAM_SUCCESS {
return p.codeToError(p.retval)
}
// Terminate the PAM transaction.
retval := C._pam_end(pamHandle, p.pamh, p.retval)
if retval != C.PAM_SUCCESS {
return p.codeToError(retval)
}
// Unregister handler index at the package level.
unregisterHandler(p.handlerIndex)
// Release the memory allocated for the conversation function.
C.free(unsafe.Pointer(p.conv))
// Release strings that were allocated when opening the PAM context.
C.free(unsafe.Pointer(p.service_name))
C.free(unsafe.Pointer(p.user))
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/pam/pam.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/pam.go#L304-L318 | go | train | // writeStream will write to the output stream (stdout or stderr or
// equivalent). | func (p *PAM) writeStream(stream int, s string) (int, error) | // writeStream will write to the output stream (stdout or stderr or
// equivalent).
func (p *PAM) writeStream(stream int, s string) (int, error) | {
writer := p.stdout
if stream == syscall.Stderr {
writer = p.stderr
}
// Replace \n with \r\n so the message correctly aligned.
r := strings.NewReplacer("\r\n", "\r\n", "\n", "\r\n")
n, err := writer.Write([]byte(r.Replace(s)))
if err != nil {
return n, err
}
return n, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/pam/pam.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/pam.go#L323-L331 | go | train | // readStream will read from the input stream (stdin or equivalent).
// TODO(russjones): At some point in the future if this becomes an issue, we
// should consider supporting echo = false. | func (p *PAM) readStream(echo bool) (string, error) | // readStream will read from the input stream (stdin or equivalent).
// TODO(russjones): At some point in the future if this becomes an issue, we
// should consider supporting echo = false.
func (p *PAM) readStream(echo bool) (string, error) | {
reader := bufio.NewReader(p.stdin)
text, err := reader.ReadString('\n')
if err != nil {
return "", trace.Wrap(err)
}
return text, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/pam/pam.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/pam/pam.go#L334-L343 | go | train | // codeToError returns a human readable string from the PAM error. | func (p *PAM) codeToError(returnValue C.int) error | // codeToError returns a human readable string from the PAM error.
func (p *PAM) codeToError(returnValue C.int) error | {
// Error strings are not allocated on the heap, so memory does not need
// released.
err := C._pam_strerror(pamHandle, p.pamh, returnValue)
if err != nil {
return trace.BadParameter(C.GoString(err))
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/fakeconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/fakeconn.go#L89-L96 | go | train | // DualPipeAddrConn creates a net.Pipe to connect a client and a server. The
// two net.Conn instances are wrapped in an addrConn which holds the source and
// destination addresses. | func DualPipeNetConn(srcAddr net.Addr, dstAddr net.Addr) (*PipeNetConn, *PipeNetConn) | // DualPipeAddrConn creates a net.Pipe to connect a client and a server. The
// two net.Conn instances are wrapped in an addrConn which holds the source and
// destination addresses.
func DualPipeNetConn(srcAddr net.Addr, dstAddr net.Addr) (*PipeNetConn, *PipeNetConn) | {
server, client := net.Pipe()
serverConn := NewPipeNetConn(server, server, server, dstAddr, srcAddr)
clientConn := NewPipeNetConn(client, client, client, srcAddr, dstAddr)
return serverConn, clientConn
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/clustername.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clustername.go#L46-L61 | go | train | // NewClusterName is a convenience wrapper to create a ClusterName resource. | func NewClusterName(spec ClusterNameSpecV2) (ClusterName, error) | // NewClusterName is a convenience wrapper to create a ClusterName resource.
func NewClusterName(spec ClusterNameSpecV2) (ClusterName, error) | {
cn := ClusterNameV2{
Kind: KindClusterName,
Version: V2,
Metadata: Metadata{
Name: MetaNameClusterName,
Namespace: defaults.Namespace,
},
Spec: spec,
}
if err := cn.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
return &cn, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/clustername.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clustername.go#L109-L111 | go | train | // SetExpiry sets expiry time for the object | func (c *ClusterNameV2) SetExpiry(expires time.Time) | // SetExpiry sets expiry time for the object
func (c *ClusterNameV2) SetExpiry(expires time.Time) | {
c.Metadata.SetExpiry(expires)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/clustername.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clustername.go#L134-L146 | go | train | // CheckAndSetDefaults checks validity of all parameters and sets defaults. | func (c *ClusterNameV2) CheckAndSetDefaults() error | // CheckAndSetDefaults checks validity of all parameters and sets defaults.
func (c *ClusterNameV2) CheckAndSetDefaults() error | {
// make sure we have defaults for all metadata fields
err := c.Metadata.CheckAndSetDefaults()
if err != nil {
return trace.Wrap(err)
}
if c.Spec.ClusterName == "" {
return trace.BadParameter("cluster name is required")
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/clustername.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clustername.go#L166-L174 | go | train | // GetClusterNameSchema returns the schema with optionally injected
// schema for extensions. | func GetClusterNameSchema(extensionSchema string) string | // GetClusterNameSchema returns the schema with optionally injected
// schema for extensions.
func GetClusterNameSchema(extensionSchema string) string | {
var clusterNameSchema string
if clusterNameSchema == "" {
clusterNameSchema = fmt.Sprintf(ClusterNameSpecSchemaTemplate, "")
} else {
clusterNameSchema = fmt.Sprintf(ClusterNameSpecSchemaTemplate, ","+extensionSchema)
}
return fmt.Sprintf(V2SchemaTemplate, MetadataSchema, clusterNameSchema, DefaultDefinitions)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/clustername.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clustername.go#L203-L239 | go | train | // Unmarshal unmarshals ClusterName from JSON. | func (t *TeleportClusterNameMarshaler) Unmarshal(bytes []byte, opts ...MarshalOption) (ClusterName, error) | // Unmarshal unmarshals ClusterName from JSON.
func (t *TeleportClusterNameMarshaler) Unmarshal(bytes []byte, opts ...MarshalOption) (ClusterName, error) | {
var clusterName ClusterNameV2
if len(bytes) == 0 {
return nil, trace.BadParameter("missing resource data")
}
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
if cfg.SkipValidation {
if err := utils.FastUnmarshal(bytes, &clusterName); err != nil {
return nil, trace.BadParameter(err.Error())
}
} else {
err = utils.UnmarshalWithSchema(GetClusterNameSchema(""), &clusterName, bytes)
if err != nil {
return nil, trace.BadParameter(err.Error())
}
}
err = clusterName.CheckAndSetDefaults()
if err != nil {
return nil, trace.Wrap(err)
}
if cfg.ID != 0 {
clusterName.SetResourceID(cfg.ID)
}
if !cfg.Expires.IsZero() {
clusterName.SetExpiry(cfg.Expires)
}
return &clusterName, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/clustername.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/clustername.go#L242-L260 | go | train | // Marshal marshals ClusterName to JSON. | func (t *TeleportClusterNameMarshaler) Marshal(c ClusterName, opts ...MarshalOption) ([]byte, error) | // Marshal marshals ClusterName to JSON.
func (t *TeleportClusterNameMarshaler) Marshal(c ClusterName, opts ...MarshalOption) ([]byte, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
switch resource := c.(type) {
case *ClusterNameV2:
if !cfg.PreserveResourceID {
// avoid modifying the original object
// to prevent unexpected data races
copy := *resource
copy.SetResourceID(0)
resource = ©
}
return utils.FastMarshal(resource)
default:
return nil, trace.BadParameter("unrecognized resource version %T", c)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/trust.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/trust.go#L81-L86 | go | train | // Check checks if certificate authority type value is correct | func (c CertAuthType) Check() error | // Check checks if certificate authority type value is correct
func (c CertAuthType) Check() error | {
if c != HostCA && c != UserCA {
return trace.BadParameter("'%v' authority type is not supported", c)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/trust.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/trust.go#L99-L107 | go | train | // Check returns error if any of the id parameters are bad, nil otherwise | func (c *CertAuthID) Check() error | // Check returns error if any of the id parameters are bad, nil otherwise
func (c *CertAuthID) Check() error | {
if err := c.Type.Check(); err != nil {
return trace.Wrap(err)
}
if strings.TrimSpace(c.DomainName) == "" {
return trace.BadParameter("identity validation error: empty domain name")
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnel.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L55-L68 | go | train | // NewReverseTunnel returns new version of reverse tunnel | func NewReverseTunnel(clusterName string, dialAddrs []string) ReverseTunnel | // NewReverseTunnel returns new version of reverse tunnel
func NewReverseTunnel(clusterName string, dialAddrs []string) ReverseTunnel | {
return &ReverseTunnelV2{
Kind: KindReverseTunnel,
Version: V2,
Metadata: Metadata{
Name: clusterName,
Namespace: defaults.Namespace,
},
Spec: ReverseTunnelSpecV2{
ClusterName: clusterName,
DialAddrs: dialAddrs,
},
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnel.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L106-L108 | go | train | // SetExpiry sets expiry time for the object | func (r *ReverseTunnelV2) SetExpiry(expires time.Time) | // SetExpiry sets expiry time for the object
func (r *ReverseTunnelV2) SetExpiry(expires time.Time) | {
r.Metadata.SetExpiry(expires)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnel.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L136-L141 | go | train | // V1 returns V1 version of the resource | func (r *ReverseTunnelV2) V1() *ReverseTunnelV1 | // V1 returns V1 version of the resource
func (r *ReverseTunnelV2) V1() *ReverseTunnelV1 | {
return &ReverseTunnelV1{
DomainName: r.Spec.ClusterName,
DialAddrs: r.Spec.DialAddrs,
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnel.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L168-L173 | go | train | // GetType gets the type of ReverseTunnel. | func (r *ReverseTunnelV2) GetType() TunnelType | // GetType gets the type of ReverseTunnel.
func (r *ReverseTunnelV2) GetType() TunnelType | {
if string(r.Spec.Type) == "" {
return ProxyTunnel
}
return r.Spec.Type
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnel.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L186-L206 | go | train | // Check returns nil if all parameters are good, error otherwise | func (r *ReverseTunnelV2) Check() error | // Check returns nil if all parameters are good, error otherwise
func (r *ReverseTunnelV2) Check() error | {
if r.Version == "" {
return trace.BadParameter("missing reverse tunnel version")
}
if strings.TrimSpace(r.Spec.ClusterName) == "" {
return trace.BadParameter("Reverse tunnel validation error: empty cluster name")
}
if len(r.Spec.DialAddrs) == 0 {
return trace.BadParameter("Invalid dial address for reverse tunnel '%v'", r.Spec.ClusterName)
}
for _, addr := range r.Spec.DialAddrs {
_, err := utils.ParseAddr(addr)
if err != nil {
return trace.Wrap(err)
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnel.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L240-L254 | go | train | // V2 returns V2 version of reverse tunnel | func (r *ReverseTunnelV1) V2() *ReverseTunnelV2 | // V2 returns V2 version of reverse tunnel
func (r *ReverseTunnelV1) V2() *ReverseTunnelV2 | {
return &ReverseTunnelV2{
Kind: KindReverseTunnel,
Version: V2,
Metadata: Metadata{
Name: r.DomainName,
Namespace: defaults.Namespace,
},
Spec: ReverseTunnelSpecV2{
ClusterName: r.DomainName,
Type: ProxyTunnel,
DialAddrs: r.DialAddrs,
},
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnel.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L264-L313 | go | train | // UnmarshalReverseTunnel unmarshals reverse tunnel from JSON or YAML,
// sets defaults and checks the schema | func UnmarshalReverseTunnel(data []byte, opts ...MarshalOption) (ReverseTunnel, error) | // UnmarshalReverseTunnel unmarshals reverse tunnel from JSON or YAML,
// sets defaults and checks the schema
func UnmarshalReverseTunnel(data []byte, opts ...MarshalOption) (ReverseTunnel, error) | {
if len(data) == 0 {
return nil, trace.BadParameter("missing tunnel data")
}
var h ResourceHeader
err := json.Unmarshal(data, &h)
if err != nil {
return nil, trace.Wrap(err)
}
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
switch h.Version {
case "":
var r ReverseTunnelV1
err := json.Unmarshal(data, &r)
if err != nil {
return nil, trace.Wrap(err)
}
v2 := r.V2()
if cfg.ID != 0 {
v2.SetResourceID(cfg.ID)
}
return r.V2(), nil
case V2:
var r ReverseTunnelV2
if cfg.SkipValidation {
if err := utils.FastUnmarshal(data, &r); err != nil {
return nil, trace.BadParameter(err.Error())
}
} else {
if err := utils.UnmarshalWithSchema(GetReverseTunnelSchema(), &r, data); err != nil {
return nil, trace.BadParameter(err.Error())
}
}
if err := r.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
if cfg.ID != 0 {
r.SetResourceID(cfg.ID)
}
if !cfg.Expires.IsZero() {
r.SetExpiry(cfg.Expires)
}
return &r, nil
}
return nil, trace.BadParameter("reverse tunnel version %v is not supported", h.Version)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnel.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L340-L342 | go | train | // UnmarshalReverseTunnel unmarshals reverse tunnel from JSON or YAML | func (*TeleportTunnelMarshaler) UnmarshalReverseTunnel(bytes []byte, opts ...MarshalOption) (ReverseTunnel, error) | // UnmarshalReverseTunnel unmarshals reverse tunnel from JSON or YAML
func (*TeleportTunnelMarshaler) UnmarshalReverseTunnel(bytes []byte, opts ...MarshalOption) (ReverseTunnel, error) | {
return UnmarshalReverseTunnel(bytes, opts...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnel.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnel.go#L345-L381 | go | train | // MarshalRole marshalls role into JSON | func (*TeleportTunnelMarshaler) MarshalReverseTunnel(rt ReverseTunnel, opts ...MarshalOption) ([]byte, error) | // MarshalRole marshalls role into JSON
func (*TeleportTunnelMarshaler) MarshalReverseTunnel(rt ReverseTunnel, opts ...MarshalOption) ([]byte, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
type tunv1 interface {
V1() *ReverseTunnelV1
}
type tunv2 interface {
V2() *ReverseTunnelV2
}
version := cfg.GetVersion()
switch version {
case V1:
v, ok := rt.(tunv1)
if !ok {
return nil, trace.BadParameter("don't know how to marshal %v", V1)
}
return json.Marshal(v.V1())
case V2:
v, ok := rt.(tunv2)
if !ok {
return nil, trace.BadParameter("don't know how to marshal %v", V2)
}
v2 := v.V2()
if !cfg.PreserveResourceID {
// avoid modifying the original object
// to prevent unexpected data races
copy := *v2
copy.SetResourceID(0)
v2 = ©
}
return utils.FastMarshal(v2)
default:
return nil, trace.BadParameter("version %v is not supported", version)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/syslog.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/syslog.go#L33-L45 | go | train | // SwitchLoggingtoSyslog tells the logger to send the output to syslog. This
// code is behind a build flag because Windows does not support syslog. | func SwitchLoggingtoSyslog() error | // SwitchLoggingtoSyslog tells the logger to send the output to syslog. This
// code is behind a build flag because Windows does not support syslog.
func SwitchLoggingtoSyslog() error | {
log.StandardLogger().SetHooks(make(log.LevelHooks))
hook, err := logrusSyslog.NewSyslogHook("", "", syslog.LOG_WARNING, "")
if err != nil {
// syslog is not available
log.SetOutput(os.Stderr)
return trace.Wrap(err)
}
log.AddHook(hook)
// ... and disable stderr:
log.SetOutput(ioutil.Discard)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L61-L71 | go | train | // Types returns cert authority types requested to be rotated. | func (r *RotateRequest) Types() []services.CertAuthType | // Types returns cert authority types requested to be rotated.
func (r *RotateRequest) Types() []services.CertAuthType | {
switch r.Type {
case "":
return []services.CertAuthType{services.HostCA, services.UserCA}
case services.HostCA:
return []services.CertAuthType{services.HostCA}
case services.UserCA:
return []services.CertAuthType{services.UserCA}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L74-L105 | go | train | // CheckAndSetDefaults checks and sets default values. | func (r *RotateRequest) CheckAndSetDefaults(clock clockwork.Clock) error | // CheckAndSetDefaults checks and sets default values.
func (r *RotateRequest) CheckAndSetDefaults(clock clockwork.Clock) error | {
if r.TargetPhase == "" {
// if phase if not set, imply that the first meaningful phase
// is set as a target phase
r.TargetPhase = services.RotationPhaseInit
}
// if mode is not set, default to manual (as it's safer)
if r.Mode == "" {
r.Mode = services.RotationModeManual
}
switch r.Type {
case "", services.HostCA, services.UserCA:
default:
return trace.BadParameter("unsupported certificate authority type: %q", r.Type)
}
if r.GracePeriod == nil {
period := defaults.RotationGracePeriod
r.GracePeriod = &period
}
if r.Schedule == nil {
var err error
r.Schedule, err = services.GenerateSchedule(clock, *r.GracePeriod)
if err != nil {
return trace.Wrap(err)
}
} else {
if err := r.Schedule.CheckAndSetDefaults(clock); err != nil {
return trace.Wrap(err)
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L198-L240 | go | train | // RotateCertAuthority starts or restarts certificate authority rotation process.
//
// Rotation procedure is based on the state machine approach.
//
// Here are the supported rotation states:
//
// * Standby - the cluster is in standby mode and ready to take action.
// * In-progress - cluster CA rotation is in progress.
//
// In-progress state is split into multiple phases and the cluster
// can traverse between phases using supported transitions.
//
// Here are the supported phases:
//
// * Standby - no action is taken.
//
// * Init - New CAs are issued, but all internal system clients
// and servers are still using the old certificates. New CAs are trusted,
// but are not used. New components that are joining the cluster
// are issued certificates signed by "old" CAs.
//
// This phase is necessary for remote clusters to fetch new certificate authorities,
// otherwise remote clusters will be locked out, because they won't have a chance
// to discover the new certificate authorities to be issued.
//
// * Update Clients - All internal system clients
// have to reconnect and receive the new credentials, but all servers
// TLS, SSH and Proxies will still use old credentials.
// Certs from old CA and new CA are trusted within the system.
// This phase is necessary because old clients should receive new credentials
// from the auth servers. If this phase did not exist, old clients could not
// trust servers serving new credentials, because old clients did not receive
// new information yet. It is possible to transition from this phase to phase
// "Update servers" or "Rollback".
//
// * Update Servers - triggers all internal system components to reload and use
// new credentials both in the internal clients and servers, however
// old CA issued credentials are still trusted. This is done to make it possible
// for old components to be trusted within the system, to make rollback possible.
// It is possible to transition from this phase to "Rollback" or "Standby".
// When transitioning to "Standby" phase, the rotation is considered completed,
// old CA is removed from the system and components reload again,
// but this time they don't trust old CA any more.
//
// * Rollback phase is used to revert any changes. When going to rollback phase
// the newly issued CA is no longer used, but set up as trusted,
// so components can reload and receive credentials issued by "old" CA back.
// This phase is useful when administrator makes a mistake, or there are some
// offline components that will loose the connection in case if rotation
// completes. It is only possible to transition from this phase to "Standby".
// When transitioning to "Standby" phase from "Rollback" phase, all components
// reload again, but the "new" CA is discarded and is no longer trusted,
// cluster goes back to the original state.
//
// Rotation modes
//
// There are two rotation modes supported - manual or automatic.
//
// * Manual mode allows administrators to transition between
// phases explicitly setting a phase on every request.
//
// * Automatic mode performs automatic transition between phases
// on a given schedule. Schedule is a time table
// that specifies exact date when the next phase should take place. If automatic
// transition between any phase fails, the rotation switches back to the manual
// mode and stops execution phases on the schedule. If schedule is not specified,
// it will be auto generated based on the "grace period" duration parameter,
// and time between all phases will be evenly split over the grace period duration.
//
// It is possible to switch from automatic to manual by setting the phase
// to the rollback phase.
// | func (a *AuthServer) RotateCertAuthority(req RotateRequest) error | // RotateCertAuthority starts or restarts certificate authority rotation process.
//
// Rotation procedure is based on the state machine approach.
//
// Here are the supported rotation states:
//
// * Standby - the cluster is in standby mode and ready to take action.
// * In-progress - cluster CA rotation is in progress.
//
// In-progress state is split into multiple phases and the cluster
// can traverse between phases using supported transitions.
//
// Here are the supported phases:
//
// * Standby - no action is taken.
//
// * Init - New CAs are issued, but all internal system clients
// and servers are still using the old certificates. New CAs are trusted,
// but are not used. New components that are joining the cluster
// are issued certificates signed by "old" CAs.
//
// This phase is necessary for remote clusters to fetch new certificate authorities,
// otherwise remote clusters will be locked out, because they won't have a chance
// to discover the new certificate authorities to be issued.
//
// * Update Clients - All internal system clients
// have to reconnect and receive the new credentials, but all servers
// TLS, SSH and Proxies will still use old credentials.
// Certs from old CA and new CA are trusted within the system.
// This phase is necessary because old clients should receive new credentials
// from the auth servers. If this phase did not exist, old clients could not
// trust servers serving new credentials, because old clients did not receive
// new information yet. It is possible to transition from this phase to phase
// "Update servers" or "Rollback".
//
// * Update Servers - triggers all internal system components to reload and use
// new credentials both in the internal clients and servers, however
// old CA issued credentials are still trusted. This is done to make it possible
// for old components to be trusted within the system, to make rollback possible.
// It is possible to transition from this phase to "Rollback" or "Standby".
// When transitioning to "Standby" phase, the rotation is considered completed,
// old CA is removed from the system and components reload again,
// but this time they don't trust old CA any more.
//
// * Rollback phase is used to revert any changes. When going to rollback phase
// the newly issued CA is no longer used, but set up as trusted,
// so components can reload and receive credentials issued by "old" CA back.
// This phase is useful when administrator makes a mistake, or there are some
// offline components that will loose the connection in case if rotation
// completes. It is only possible to transition from this phase to "Standby".
// When transitioning to "Standby" phase from "Rollback" phase, all components
// reload again, but the "new" CA is discarded and is no longer trusted,
// cluster goes back to the original state.
//
// Rotation modes
//
// There are two rotation modes supported - manual or automatic.
//
// * Manual mode allows administrators to transition between
// phases explicitly setting a phase on every request.
//
// * Automatic mode performs automatic transition between phases
// on a given schedule. Schedule is a time table
// that specifies exact date when the next phase should take place. If automatic
// transition between any phase fails, the rotation switches back to the manual
// mode and stops execution phases on the schedule. If schedule is not specified,
// it will be auto generated based on the "grace period" duration parameter,
// and time between all phases will be evenly split over the grace period duration.
//
// It is possible to switch from automatic to manual by setting the phase
// to the rollback phase.
//
func (a *AuthServer) RotateCertAuthority(req RotateRequest) error | {
if err := req.CheckAndSetDefaults(a.clock); err != nil {
return trace.Wrap(err)
}
clusterName, err := a.GetClusterName()
if err != nil {
return trace.Wrap(err)
}
caTypes := req.Types()
for _, caType := range caTypes {
existing, err := a.Trust.GetCertAuthority(services.CertAuthID{
Type: caType,
DomainName: clusterName.GetClusterName(),
}, true)
if err != nil {
return trace.Wrap(err)
}
rotated, err := processRotationRequest(rotationReq{
ca: existing,
clock: a.clock,
targetPhase: req.TargetPhase,
schedule: *req.Schedule,
gracePeriod: *req.GracePeriod,
mode: req.Mode,
privateKey: a.privateKey,
})
if err != nil {
return trace.Wrap(err)
}
if err := a.CompareAndSwapCertAuthority(rotated, existing); err != nil {
return trace.Wrap(err)
}
rotation := rotated.GetRotation()
switch rotation.State {
case services.RotationStateInProgress:
log.WithFields(logrus.Fields{"type": caType}).Infof("Updated rotation state, set current phase to: %q.", rotation.Phase)
case services.RotationStateStandby:
log.WithFields(logrus.Fields{"type": caType}).Infof("Updated and completed rotation.")
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L245-L280 | go | train | // RotateExternalCertAuthority rotates external certificate authority,
// this method is called by remote trusted cluster and is used to update
// only public keys and certificates of the certificate authority. | func (a *AuthServer) RotateExternalCertAuthority(ca services.CertAuthority) error | // RotateExternalCertAuthority rotates external certificate authority,
// this method is called by remote trusted cluster and is used to update
// only public keys and certificates of the certificate authority.
func (a *AuthServer) RotateExternalCertAuthority(ca services.CertAuthority) error | {
if ca == nil {
return trace.BadParameter("missing certificate authority")
}
clusterName, err := a.GetClusterName()
if err != nil {
return trace.Wrap(err)
}
// this is just an extra precaution against local admins,
// because this is additionally enforced by RBAC as well
if ca.GetClusterName() == clusterName.GetClusterName() {
return trace.BadParameter("can not rotate local certificate authority")
}
existing, err := a.Trust.GetCertAuthority(services.CertAuthID{
Type: ca.GetType(),
DomainName: ca.GetClusterName(),
}, false)
if err != nil {
return trace.Wrap(err)
}
updated := existing.Clone()
updated.SetCheckingKeys(ca.GetCheckingKeys())
updated.SetTLSKeyPairs(ca.GetTLSKeyPairs())
updated.SetRotation(ca.GetRotation())
// use compare and swap to protect from concurrent updates
// by trusted cluster API
if err := a.CompareAndSwapCertAuthority(updated, existing); err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L285-L303 | go | train | // autoRotateCertAuthorities automatically rotates cert authorities,
// does nothing if no rotation parameters were set up
// or it is too early to rotate per schedule | func (a *AuthServer) autoRotateCertAuthorities() error | // autoRotateCertAuthorities automatically rotates cert authorities,
// does nothing if no rotation parameters were set up
// or it is too early to rotate per schedule
func (a *AuthServer) autoRotateCertAuthorities() error | {
clusterName, err := a.GetClusterName()
if err != nil {
return trace.Wrap(err)
}
for _, caType := range []services.CertAuthType{services.HostCA, services.UserCA} {
ca, err := a.Trust.GetCertAuthority(services.CertAuthID{
Type: caType,
DomainName: clusterName.GetClusterName(),
}, true)
if err != nil {
return trace.Wrap(err)
}
if err := a.autoRotate(ca); err != nil {
return trace.Wrap(err)
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L371-L450 | go | train | // processRotationRequest processes rotation request based on the target and
// current phase and state. | func processRotationRequest(req rotationReq) (services.CertAuthority, error) | // processRotationRequest processes rotation request based on the target and
// current phase and state.
func processRotationRequest(req rotationReq) (services.CertAuthority, error) | {
rotation := req.ca.GetRotation()
ca := req.ca.Clone()
switch req.targetPhase {
case services.RotationPhaseInit:
// This is the first stage of the rotation - new certificate authorities
// are being generated, but no components are using them yet
switch rotation.State {
case services.RotationStateStandby, "":
default:
return nil, trace.BadParameter("can not initate rotation while another is in progress")
}
if err := startNewRotation(req, ca); err != nil {
return nil, trace.Wrap(err)
}
return ca, nil
case services.RotationPhaseUpdateClients:
// Update client phase clients will start using new credentials
// and servers will use the existing credentials, but will trust clients
// with both old and new credentials.
if rotation.Phase != services.RotationPhaseInit {
return nil, trace.BadParameter(
"can only switch to phase %v from %v, current phase is %v",
services.RotationPhaseUpdateClients,
services.RotationPhaseInit,
rotation.Phase)
}
if err := updateClients(ca, req.mode); err != nil {
return nil, trace.Wrap(err)
}
return ca, nil
case services.RotationPhaseUpdateServers:
// Update server phase uses the new credentials both for servers
// and clients, but still trusts clients with old credentials.
if rotation.Phase != services.RotationPhaseUpdateClients {
return nil, trace.BadParameter(
"can only switch to phase %v from %v, current phase is %v",
services.RotationPhaseUpdateServers,
services.RotationPhaseUpdateClients,
rotation.Phase)
}
// Signal nodes to restart and start serving new signatures
// by updating the phase.
rotation.Phase = req.targetPhase
rotation.Mode = req.mode
ca.SetRotation(rotation)
return ca, nil
case services.RotationPhaseRollback:
// Rollback moves back both clients and servers to use the old credentials
// but will trust new credentials.
switch rotation.Phase {
case services.RotationPhaseInit, services.RotationPhaseUpdateClients, services.RotationPhaseUpdateServers:
if err := startRollingBackRotation(ca); err != nil {
return nil, trace.Wrap(err)
}
return ca, nil
default:
return nil, trace.BadParameter("can not transition to phase %q from %q phase.", req.targetPhase, rotation.Phase)
}
case services.RotationPhaseStandby:
// Transition to the standby phase moves rotation process
// to standby, servers will only trust one certificate authority.
switch rotation.Phase {
case services.RotationPhaseUpdateServers, services.RotationPhaseRollback:
if err := completeRotation(req.clock, ca); err != nil {
return nil, trace.Wrap(err)
}
return ca, nil
default:
return nil, trace.BadParameter(
"can only switch to phase %v from %v, current phase is %v",
services.RotationPhaseUpdateServers,
services.RotationPhaseUpdateClients,
rotation.Phase)
}
default:
return nil, trace.BadParameter("unsupported phase: %q", req.targetPhase)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L454-L544 | go | train | // startNewRotation starts new rotation and updates the certificate
// authority with new CA keys. | func startNewRotation(req rotationReq, ca services.CertAuthority) error | // startNewRotation starts new rotation and updates the certificate
// authority with new CA keys.
func startNewRotation(req rotationReq, ca services.CertAuthority) error | {
clock := req.clock
gracePeriod := req.gracePeriod
rotation := ca.GetRotation()
id := uuid.New()
rotation.Mode = req.mode
rotation.Schedule = req.schedule
var sshPrivPEM, sshPubPEM []byte
var keyPEM, certPEM []byte
// generate keys and certificates:
if len(req.privateKey) != 0 {
log.Infof("Generating CA, using pregenerated test private key.")
rsaKey, err := ssh.ParseRawPrivateKey(req.privateKey)
if err != nil {
return trace.Wrap(err)
}
signer, err := ssh.NewSignerFromKey(rsaKey)
if err != nil {
return trace.Wrap(err)
}
sshPubPEM = ssh.MarshalAuthorizedKey(signer.PublicKey())
sshPrivPEM = req.privateKey
keyPEM, certPEM, err = tlsca.GenerateSelfSignedCAWithPrivateKey(rsaKey.(*rsa.PrivateKey), pkix.Name{
CommonName: ca.GetClusterName(),
Organization: []string{ca.GetClusterName()},
}, nil, defaults.CATTL)
if err != nil {
return trace.Wrap(err)
}
} else {
var err error
sshPrivPEM, sshPubPEM, err = native.GenerateKeyPair("")
if err != nil {
return trace.Wrap(err)
}
keyPEM, certPEM, err = tlsca.GenerateSelfSignedCA(pkix.Name{
CommonName: ca.GetClusterName(),
Organization: []string{ca.GetClusterName()},
}, nil, defaults.CATTL)
if err != nil {
return trace.Wrap(err)
}
}
tlsKeyPair := &services.TLSKeyPair{
Cert: certPEM,
Key: keyPEM,
}
// rotate the certificate authority:
rotation.Started = clock.Now().UTC()
rotation.GracePeriod = services.NewDuration(gracePeriod)
rotation.CurrentID = id
signingKeys := ca.GetSigningKeys()
checkingKeys := ca.GetCheckingKeys()
keyPairs := ca.GetTLSKeyPairs()
// Drop old certificate authority without keeping it as trusted.
if gracePeriod == 0 {
signingKeys = [][]byte{sshPrivPEM}
checkingKeys = [][]byte{sshPubPEM}
keyPairs = []services.TLSKeyPair{*tlsKeyPair}
// In case of forced rotation, rotation has been started and completed
// in the same step moving it to standby state.
rotation.State = services.RotationStateStandby
rotation.Phase = services.RotationPhaseStandby
} else {
// Initial phase of rotation keeps old CAs as primary signing key
// pairs, and generates new CAs that are trusted, but not used in the cluster.
signingKeys = [][]byte{signingKeys[0], sshPrivPEM}
checkingKeys = [][]byte{checkingKeys[0], sshPubPEM}
keyPairs = []services.TLSKeyPair{keyPairs[0], *tlsKeyPair}
rotation.State = services.RotationStateInProgress
rotation.Phase = services.RotationPhaseInit
}
ca.SetSigningKeys(signingKeys)
ca.SetCheckingKeys(checkingKeys)
ca.SetTLSKeyPairs(keyPairs)
ca.SetRotation(rotation)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L552-L572 | go | train | // updateClients swaps old and new cert authorities:
//
// * old CAs exist and are trusted, but are not used for signing
// * the new CAs are now used for signing
// * remote components will reload with new certificates used for client connections
// | func updateClients(ca services.CertAuthority, mode string) error | // updateClients swaps old and new cert authorities:
//
// * old CAs exist and are trusted, but are not used for signing
// * the new CAs are now used for signing
// * remote components will reload with new certificates used for client connections
//
func updateClients(ca services.CertAuthority, mode string) error | {
rotation := ca.GetRotation()
signingKeys := ca.GetSigningKeys()
checkingKeys := ca.GetCheckingKeys()
keyPairs := ca.GetTLSKeyPairs()
signingKeys = [][]byte{signingKeys[1], signingKeys[0]}
checkingKeys = [][]byte{checkingKeys[1], checkingKeys[0]}
keyPairs = []services.TLSKeyPair{keyPairs[1], keyPairs[0]}
rotation.State = services.RotationStateInProgress
rotation.Phase = services.RotationPhaseUpdateClients
rotation.Mode = mode
ca.SetSigningKeys(signingKeys)
ca.SetCheckingKeys(checkingKeys)
ca.SetTLSKeyPairs(keyPairs)
ca.SetRotation(rotation)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L575-L601 | go | train | // startRollingBackRotation starts roll back to the original state. | func startRollingBackRotation(ca services.CertAuthority) error | // startRollingBackRotation starts roll back to the original state.
func startRollingBackRotation(ca services.CertAuthority) error | {
rotation := ca.GetRotation()
// Rollback always sets rotation to manual mode.
rotation.Mode = services.RotationModeManual
signingKeys := ca.GetSigningKeys()
checkingKeys := ca.GetCheckingKeys()
keyPairs := ca.GetTLSKeyPairs()
// Rotation sets the first key to be the new key
// and keep only public keys/certs for the new CA.
signingKeys = [][]byte{signingKeys[1]}
checkingKeys = [][]byte{checkingKeys[1]}
// Keep the new certificate as trusted
// as during the rollback phase, both types of clients may be present in the cluster.
keyPairs = []services.TLSKeyPair{keyPairs[1], services.TLSKeyPair{Cert: keyPairs[0].Cert}}
rotation.State = services.RotationStateInProgress
rotation.Phase = services.RotationPhaseRollback
ca.SetSigningKeys(signingKeys)
ca.SetCheckingKeys(checkingKeys)
ca.SetTLSKeyPairs(keyPairs)
ca.SetRotation(rotation)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L604-L622 | go | train | // completeRollingBackRotation completes rollback of the rotation and sets it to the standby state | func completeRollingBackRotation(clock clockwork.Clock, ca services.CertAuthority) error | // completeRollingBackRotation completes rollback of the rotation and sets it to the standby state
func completeRollingBackRotation(clock clockwork.Clock, ca services.CertAuthority) error | {
rotation := ca.GetRotation()
// clean up the state
rotation.Started = time.Time{}
rotation.State = services.RotationStateStandby
rotation.Phase = services.RotationPhaseStandby
rotation.Mode = ""
rotation.Schedule = services.RotationSchedule{}
keyPairs := ca.GetTLSKeyPairs()
// only keep the original certificate authority as trusted
// and remove everything else.
keyPairs = []services.TLSKeyPair{keyPairs[0]}
ca.SetTLSKeyPairs(keyPairs)
ca.SetRotation(rotation)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/rotate.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/rotate.go#L625-L647 | go | train | // completeRotation completes the certificate authority rotation. | func completeRotation(clock clockwork.Clock, ca services.CertAuthority) error | // completeRotation completes the certificate authority rotation.
func completeRotation(clock clockwork.Clock, ca services.CertAuthority) error | {
rotation := ca.GetRotation()
signingKeys := ca.GetSigningKeys()
checkingKeys := ca.GetCheckingKeys()
keyPairs := ca.GetTLSKeyPairs()
signingKeys = signingKeys[:1]
checkingKeys = checkingKeys[:1]
keyPairs = keyPairs[:1]
rotation.Started = time.Time{}
rotation.State = services.RotationStateStandby
rotation.Phase = services.RotationPhaseStandby
rotation.LastRotated = clock.Now()
rotation.Mode = ""
rotation.Schedule = services.RotationSchedule{}
ca.SetSigningKeys(signingKeys)
ca.SetCheckingKeys(checkingKeys)
ca.SetTLSKeyPairs(keyPairs)
ca.SetRotation(rotation)
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/unpack.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/unpack.go#L33-L49 | go | train | // Extract extracts the contents of the specified tarball under dir.
// The resulting files and directories are created using the current user context. | func Extract(r io.Reader, dir string) error | // Extract extracts the contents of the specified tarball under dir.
// The resulting files and directories are created using the current user context.
func Extract(r io.Reader, dir string) error | {
tarball := tar.NewReader(r)
for {
header, err := tarball.Next()
if err == io.EOF {
break
} else if err != nil {
return trace.Wrap(err)
}
if err := extractFile(tarball, header, dir); err != nil {
return trace.Wrap(err)
}
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/unpack.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/unpack.go#L54-L68 | go | train | // extractFile extracts a single file or directory from tarball into dir.
// Uses header to determine the type of item to create
// Based on https://github.com/mholt/archiver | func extractFile(tarball *tar.Reader, header *tar.Header, dir string) error | // extractFile extracts a single file or directory from tarball into dir.
// Uses header to determine the type of item to create
// Based on https://github.com/mholt/archiver
func extractFile(tarball *tar.Reader, header *tar.Header, dir string) error | {
switch header.Typeflag {
case tar.TypeDir:
return withDir(filepath.Join(dir, header.Name), nil)
case tar.TypeBlock, tar.TypeChar, tar.TypeReg, tar.TypeRegA, tar.TypeFifo:
return writeFile(filepath.Join(dir, header.Name), tarball, header.FileInfo().Mode())
case tar.TypeLink:
return writeHardLink(filepath.Join(dir, header.Name), filepath.Join(dir, header.Linkname))
case tar.TypeSymlink:
return writeSymbolicLink(filepath.Join(dir, header.Name), header.Linkname)
default:
log.Warnf("Unsupported type flag %v for %v.", header.Typeflag, header.Name)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/rand.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/rand.go#L30-L36 | go | train | // CryptoRandomHex returns hex encoded random string generated with crypto-strong
// pseudo random generator of the given bytes | func CryptoRandomHex(len int) (string, error) | // CryptoRandomHex returns hex encoded random string generated with crypto-strong
// pseudo random generator of the given bytes
func CryptoRandomHex(len int) (string, error) | {
randomBytes := make([]byte, len)
if _, err := rand.Reader.Read(randomBytes); err != nil {
return "", trace.Wrap(err)
}
return hex.EncodeToString(randomBytes), nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/utils/rand.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/utils/rand.go#L39-L45 | go | train | // RandomDuration returns a duration in a range [0, max) | func RandomDuration(max time.Duration) time.Duration | // RandomDuration returns a duration in a range [0, max)
func RandomDuration(max time.Duration) time.Duration | {
randomVal, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
if err != nil {
return max / 2
}
return time.Duration(randomVal.Int64())
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/suite/suite.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L302-L315 | go | train | // NewServer creates a new server resource | func NewServer(kind, name, addr, namespace string) *services.ServerV2 | // NewServer creates a new server resource
func NewServer(kind, name, addr, namespace string) *services.ServerV2 | {
return &services.ServerV2{
Kind: kind,
Version: services.V2,
Metadata: services.Metadata{
Name: name,
Namespace: namespace,
},
Spec: services.ServerSpecV2{
Addr: addr,
PublicAddr: addr,
},
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/suite/suite.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L890-L905 | go | train | // AuthPreference tests authentication preference service | func (s *ServicesTestSuite) AuthPreference(c *check.C) | // AuthPreference tests authentication preference service
func (s *ServicesTestSuite) AuthPreference(c *check.C) | {
ap, err := services.NewAuthPreference(services.AuthPreferenceSpecV2{
Type: "local",
SecondFactor: "otp",
})
c.Assert(err, check.IsNil)
err = s.ConfigS.SetAuthPreference(ap)
c.Assert(err, check.IsNil)
gotAP, err := s.ConfigS.GetAuthPreference()
c.Assert(err, check.IsNil)
c.Assert(gotAP.GetType(), check.Equals, "local")
c.Assert(gotAP.GetSecondFactor(), check.Equals, "otp")
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/suite/suite.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L953-L959 | go | train | // CollectOptions collects suite options | func CollectOptions(opts ...SuiteOption) SuiteOptions | // CollectOptions collects suite options
func CollectOptions(opts ...SuiteOption) SuiteOptions | {
var suiteOpts SuiteOptions
for _, o := range opts {
o(&suiteOpts)
}
return suiteOpts
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/suite/suite.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L962-L1023 | go | train | // ClusterConfig tests cluster configuration | func (s *ServicesTestSuite) ClusterConfig(c *check.C, opts ...SuiteOption) | // ClusterConfig tests cluster configuration
func (s *ServicesTestSuite) ClusterConfig(c *check.C, opts ...SuiteOption) | {
config, err := services.NewClusterConfig(services.ClusterConfigSpecV3{
ClientIdleTimeout: services.NewDuration(17 * time.Second),
DisconnectExpiredCert: services.NewBool(true),
ClusterID: "27",
SessionRecording: services.RecordAtProxy,
Audit: services.AuditConfig{
Region: "us-west-1",
Type: "dynamodb",
AuditSessionsURI: "file:///home/log",
AuditTableName: "audit_table_name",
AuditEventsURI: []string{"dynamodb://audit_table_name", "file:///home/log"},
},
})
c.Assert(err, check.IsNil)
err = s.ConfigS.SetClusterConfig(config)
c.Assert(err, check.IsNil)
gotConfig, err := s.ConfigS.GetClusterConfig()
c.Assert(err, check.IsNil)
config.SetResourceID(gotConfig.GetResourceID())
fixtures.DeepCompare(c, config, gotConfig)
// Some parts (e.g. auth server) will not function
// without cluster name or cluster config
if CollectOptions(opts...).SkipDelete {
return
}
err = s.ConfigS.DeleteClusterConfig()
c.Assert(err, check.IsNil)
_, err = s.ConfigS.GetClusterConfig()
fixtures.ExpectNotFound(c, err)
clusterName, err := services.NewClusterName(services.ClusterNameSpecV2{
ClusterName: "example.com",
})
c.Assert(err, check.IsNil)
err = s.ConfigS.SetClusterName(clusterName)
c.Assert(err, check.IsNil)
gotName, err := s.ConfigS.GetClusterName()
c.Assert(err, check.IsNil)
clusterName.SetResourceID(gotName.GetResourceID())
fixtures.DeepCompare(c, clusterName, gotName)
err = s.ConfigS.DeleteClusterName()
c.Assert(err, check.IsNil)
_, err = s.ConfigS.GetClusterName()
fixtures.ExpectNotFound(c, err)
err = s.ConfigS.UpsertClusterName(clusterName)
c.Assert(err, check.IsNil)
gotName, err = s.ConfigS.GetClusterName()
c.Assert(err, check.IsNil)
clusterName.SetResourceID(gotName.GetResourceID())
fixtures.DeepCompare(c, clusterName, gotName)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/suite/suite.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L1026-L1307 | go | train | // Events tests various events variations | func (s *ServicesTestSuite) Events(c *check.C) | // Events tests various events variations
func (s *ServicesTestSuite) Events(c *check.C) | {
testCases := []eventTest{
{
name: "Cert authority with secrets",
kind: services.WatchKind{
Kind: services.KindCertAuthority,
LoadSecrets: true,
},
crud: func() services.Resource {
ca := NewTestCA(services.UserCA, "example.com")
c.Assert(s.CAS.UpsertCertAuthority(ca), check.IsNil)
out, err := s.CAS.GetCertAuthority(*ca.ID(), true)
c.Assert(err, check.IsNil)
c.Assert(s.CAS.DeleteCertAuthority(*ca.ID()), check.IsNil)
return out
},
},
}
s.runEventsTests(c, testCases)
testCases = []eventTest{
{
name: "Cert authority without secrets",
kind: services.WatchKind{
Kind: services.KindCertAuthority,
LoadSecrets: false,
},
crud: func() services.Resource {
ca := NewTestCA(services.UserCA, "example.com")
c.Assert(s.CAS.UpsertCertAuthority(ca), check.IsNil)
out, err := s.CAS.GetCertAuthority(*ca.ID(), false)
c.Assert(err, check.IsNil)
c.Assert(s.CAS.DeleteCertAuthority(*ca.ID()), check.IsNil)
return out
},
},
}
s.runEventsTests(c, testCases)
testCases = []eventTest{
{
name: "Token",
kind: services.WatchKind{
Kind: services.KindToken,
},
crud: func() services.Resource {
expires := time.Now().UTC().Add(time.Hour)
t, err := services.NewProvisionToken("token",
teleport.Roles{teleport.RoleAuth, teleport.RoleNode}, expires)
c.Assert(err, check.IsNil)
c.Assert(s.ProvisioningS.UpsertToken(t), check.IsNil)
token, err := s.ProvisioningS.GetToken("token")
c.Assert(err, check.IsNil)
c.Assert(s.ProvisioningS.DeleteToken("token"), check.IsNil)
return token
},
},
{
name: "Namespace",
kind: services.WatchKind{
Kind: services.KindNamespace,
},
crud: func() services.Resource {
ns := services.Namespace{
Kind: services.KindNamespace,
Version: services.V2,
Metadata: services.Metadata{
Name: "testnamespace",
Namespace: defaults.Namespace,
},
}
err := s.PresenceS.UpsertNamespace(ns)
c.Assert(err, check.IsNil)
out, err := s.PresenceS.GetNamespace(ns.Metadata.Name)
c.Assert(err, check.IsNil)
err = s.PresenceS.DeleteNamespace(ns.Metadata.Name)
c.Assert(err, check.IsNil)
return out
},
},
{
name: "Static tokens",
kind: services.WatchKind{
Kind: services.KindStaticTokens,
},
crud: func() services.Resource {
staticTokens, err := services.NewStaticTokens(services.StaticTokensSpecV2{
StaticTokens: []services.ProvisionTokenV1{
{
Token: "tok1",
Roles: teleport.Roles{teleport.RoleNode},
Expires: time.Now().UTC().Add(time.Hour),
},
},
})
c.Assert(err, check.IsNil)
err = s.ConfigS.SetStaticTokens(staticTokens)
c.Assert(err, check.IsNil)
out, err := s.ConfigS.GetStaticTokens()
c.Assert(err, check.IsNil)
err = s.ConfigS.DeleteStaticTokens()
c.Assert(err, check.IsNil)
return out
},
},
{
name: "Role",
kind: services.WatchKind{
Kind: services.KindRole,
},
crud: func() services.Resource {
role, err := services.NewRole("role1", services.RoleSpecV3{
Options: services.RoleOptions{
MaxSessionTTL: services.Duration(time.Hour),
},
Allow: services.RoleConditions{
Logins: []string{"root", "bob"},
NodeLabels: services.Labels{services.Wildcard: []string{services.Wildcard}},
},
Deny: services.RoleConditions{},
})
err = s.Access.UpsertRole(role)
c.Assert(err, check.IsNil)
out, err := s.Access.GetRole(role.GetName())
c.Assert(err, check.IsNil)
err = s.Access.DeleteRole(role.GetName())
c.Assert(err, check.IsNil)
return out
},
},
{
name: "User",
kind: services.WatchKind{
Kind: services.KindUser,
},
crud: func() services.Resource {
user := newUser("user1", []string{"admin"})
err := s.Users().UpsertUser(user)
out, err := s.Users().GetUser(user.GetName())
c.Assert(err, check.IsNil)
c.Assert(s.Users().DeleteUser(user.GetName()), check.IsNil)
return out
},
},
{
name: "Node",
kind: services.WatchKind{
Kind: services.KindNode,
},
crud: func() services.Resource {
srv := NewServer(services.KindNode, "srv1", "127.0.0.1:2022", defaults.Namespace)
_, err := s.PresenceS.UpsertNode(srv)
c.Assert(err, check.IsNil)
out, err := s.PresenceS.GetNodes(srv.Metadata.Namespace)
c.Assert(err, check.IsNil)
err = s.PresenceS.DeleteAllNodes(srv.Metadata.Namespace)
c.Assert(err, check.IsNil)
return out[0]
},
},
{
name: "Proxy",
kind: services.WatchKind{
Kind: services.KindProxy,
},
crud: func() services.Resource {
srv := NewServer(services.KindProxy, "srv1", "127.0.0.1:2022", defaults.Namespace)
err := s.PresenceS.UpsertProxy(srv)
c.Assert(err, check.IsNil)
out, err := s.PresenceS.GetProxies()
c.Assert(err, check.IsNil)
err = s.PresenceS.DeleteAllProxies()
c.Assert(err, check.IsNil)
return out[0]
},
},
{
name: "Tunnel connection",
kind: services.WatchKind{
Kind: services.KindTunnelConnection,
},
crud: func() services.Resource {
conn, err := services.NewTunnelConnection("conn1", services.TunnelConnectionSpecV2{
ClusterName: "example.com",
ProxyName: "p1",
LastHeartbeat: time.Now().UTC(),
})
c.Assert(err, check.IsNil)
err = s.PresenceS.UpsertTunnelConnection(conn)
c.Assert(err, check.IsNil)
out, err := s.PresenceS.GetTunnelConnections("example.com")
c.Assert(err, check.IsNil)
err = s.PresenceS.DeleteAllTunnelConnections()
c.Assert(err, check.IsNil)
return out[0]
},
},
{
name: "Reverse tunnel",
kind: services.WatchKind{
Kind: services.KindReverseTunnel,
},
crud: func() services.Resource {
tunnel := newReverseTunnel("example.com", []string{"example.com:2023"})
c.Assert(s.PresenceS.UpsertReverseTunnel(tunnel), check.IsNil)
out, err := s.PresenceS.GetReverseTunnels()
c.Assert(err, check.IsNil)
err = s.PresenceS.DeleteReverseTunnel(tunnel.Spec.ClusterName)
c.Assert(err, check.IsNil)
return out[0]
},
},
}
s.runEventsTests(c, testCases)
// Namespace with a name
testCases = []eventTest{
{
name: "Namespace with a name",
kind: services.WatchKind{
Kind: services.KindNamespace,
Name: "shmest",
},
crud: func() services.Resource {
ns := services.Namespace{
Kind: services.KindNamespace,
Version: services.V2,
Metadata: services.Metadata{
Name: "shmest",
Namespace: defaults.Namespace,
},
}
err := s.PresenceS.UpsertNamespace(ns)
c.Assert(err, check.IsNil)
out, err := s.PresenceS.GetNamespace(ns.Metadata.Name)
c.Assert(err, check.IsNil)
err = s.PresenceS.DeleteNamespace(ns.Metadata.Name)
c.Assert(err, check.IsNil)
return out
},
},
}
s.runEventsTests(c, testCases)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/suite/suite.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/suite/suite.go#L1310-L1357 | go | train | // EventsClusterConfig tests cluster config resource events | func (s *ServicesTestSuite) EventsClusterConfig(c *check.C) | // EventsClusterConfig tests cluster config resource events
func (s *ServicesTestSuite) EventsClusterConfig(c *check.C) | {
testCases := []eventTest{
{
name: "Cluster config",
kind: services.WatchKind{
Kind: services.KindClusterConfig,
},
crud: func() services.Resource {
config, err := services.NewClusterConfig(services.ClusterConfigSpecV3{})
c.Assert(err, check.IsNil)
err = s.ConfigS.SetClusterConfig(config)
c.Assert(err, check.IsNil)
out, err := s.ConfigS.GetClusterConfig()
c.Assert(err, check.IsNil)
err = s.ConfigS.DeleteClusterConfig()
c.Assert(err, check.IsNil)
return out
},
},
{
name: "Cluster name",
kind: services.WatchKind{
Kind: services.KindClusterName,
},
crud: func() services.Resource {
clusterName, err := services.NewClusterName(services.ClusterNameSpecV2{
ClusterName: "example.com",
})
c.Assert(err, check.IsNil)
err = s.ConfigS.SetClusterName(clusterName)
c.Assert(err, check.IsNil)
out, err := s.ConfigS.GetClusterName()
c.Assert(err, check.IsNil)
err = s.ConfigS.DeleteClusterName()
c.Assert(err, check.IsNil)
return out
},
},
}
s.runEventsTests(c, testCases)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L78-L84 | go | train | // IsTunnelConnectionStatus returns tunnel connection status based on the last
// heartbeat time recorded for a connection | func TunnelConnectionStatus(clock clockwork.Clock, conn TunnelConnection) string | // IsTunnelConnectionStatus returns tunnel connection status based on the last
// heartbeat time recorded for a connection
func TunnelConnectionStatus(clock clockwork.Clock, conn TunnelConnection) string | {
diff := clock.Now().Sub(conn.GetLastHeartbeat())
if diff < defaults.ReverseTunnelOfflineThreshold {
return teleport.RemoteClusterStatusOnline
}
return teleport.RemoteClusterStatusOffline
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L88-L94 | go | train | // MustCreateTunnelConnection returns new connection from V2 spec or panics if
// parameters are incorrect | func MustCreateTunnelConnection(name string, spec TunnelConnectionSpecV2) TunnelConnection | // MustCreateTunnelConnection returns new connection from V2 spec or panics if
// parameters are incorrect
func MustCreateTunnelConnection(name string, spec TunnelConnectionSpecV2) TunnelConnection | {
conn, err := NewTunnelConnection(name, spec)
if err != nil {
panic(err)
}
return conn
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L97-L112 | go | train | // NewTunnelConnection returns new connection from V2 spec | func NewTunnelConnection(name string, spec TunnelConnectionSpecV2) (TunnelConnection, error) | // NewTunnelConnection returns new connection from V2 spec
func NewTunnelConnection(name string, spec TunnelConnectionSpecV2) (TunnelConnection, error) | {
conn := &TunnelConnectionV2{
Kind: KindTunnelConnection,
SubKind: spec.ClusterName,
Version: V2,
Metadata: Metadata{
Name: name,
Namespace: defaults.Namespace,
},
Spec: spec,
}
if err := conn.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
return conn, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L151-L154 | go | train | // String returns user-friendly description of this connection | func (r *TunnelConnectionV2) String() string | // String returns user-friendly description of this connection
func (r *TunnelConnectionV2) String() string | {
return fmt.Sprintf("TunnelConnection(name=%v, type=%v, cluster=%v, proxy=%v)",
r.Metadata.Name, r.Spec.Type, r.Spec.ClusterName, r.Spec.ProxyName)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L162-L164 | go | train | // SetExpiry sets expiry time for the object | func (r *TunnelConnectionV2) SetExpiry(expires time.Time) | // SetExpiry sets expiry time for the object
func (r *TunnelConnectionV2) SetExpiry(expires time.Time) | {
r.Metadata.SetExpiry(expires)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L172-L174 | go | train | // SetTTL sets Expires header using realtime clock | func (r *TunnelConnectionV2) SetTTL(clock clockwork.Clock, ttl time.Duration) | // SetTTL sets Expires header using realtime clock
func (r *TunnelConnectionV2) SetTTL(clock clockwork.Clock, ttl time.Duration) | {
r.Metadata.SetTTL(clock, ttl)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L221-L223 | go | train | // SetLastHeartbeat sets last heartbeat time | func (r *TunnelConnectionV2) SetLastHeartbeat(tm time.Time) | // SetLastHeartbeat sets last heartbeat time
func (r *TunnelConnectionV2) SetLastHeartbeat(tm time.Time) | {
r.Spec.LastHeartbeat = tm
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L226-L231 | go | train | // GetType gets the type of ReverseTunnel. | func (r *TunnelConnectionV2) GetType() TunnelType | // GetType gets the type of ReverseTunnel.
func (r *TunnelConnectionV2) GetType() TunnelType | {
if string(r.Spec.Type) == "" {
return ProxyTunnel
}
return r.Spec.Type
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L239-L252 | go | train | // Check returns nil if all parameters are good, error otherwise | func (r *TunnelConnectionV2) Check() error | // Check returns nil if all parameters are good, error otherwise
func (r *TunnelConnectionV2) Check() error | {
if r.Version == "" {
return trace.BadParameter("missing version")
}
if strings.TrimSpace(r.Spec.ClusterName) == "" {
return trace.BadParameter("empty cluster name")
}
if len(r.Spec.ProxyName) == 0 {
return trace.BadParameter("missing parameter proxy name")
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L275-L314 | go | train | // UnmarshalTunnelConnection unmarshals reverse tunnel from JSON or YAML,
// sets defaults and checks the schema | func UnmarshalTunnelConnection(data []byte, opts ...MarshalOption) (TunnelConnection, error) | // UnmarshalTunnelConnection unmarshals reverse tunnel from JSON or YAML,
// sets defaults and checks the schema
func UnmarshalTunnelConnection(data []byte, opts ...MarshalOption) (TunnelConnection, error) | {
if len(data) == 0 {
return nil, trace.BadParameter("missing tunnel connection data")
}
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
var h ResourceHeader
err = utils.FastUnmarshal(data, &h)
if err != nil {
return nil, trace.Wrap(err)
}
switch h.Version {
case V2:
var r TunnelConnectionV2
if cfg.SkipValidation {
if err := utils.FastUnmarshal(data, &r); err != nil {
return nil, trace.BadParameter(err.Error())
}
} else {
if err := utils.UnmarshalWithSchema(GetTunnelConnectionSchema(), &r, data); err != nil {
return nil, trace.BadParameter(err.Error())
}
}
if err := r.CheckAndSetDefaults(); err != nil {
return nil, trace.Wrap(err)
}
if cfg.ID != 0 {
r.SetResourceID(cfg.ID)
}
if !cfg.Expires.IsZero() {
r.SetExpiry(cfg.Expires)
}
return &r, nil
}
return nil, trace.BadParameter("reverse tunnel version %v is not supported", h.Version)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/tunnelconn.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/tunnelconn.go#L317-L335 | go | train | // MarshalTunnelConnection marshals tunnel connection | func MarshalTunnelConnection(rt TunnelConnection, opts ...MarshalOption) ([]byte, error) | // MarshalTunnelConnection marshals tunnel connection
func MarshalTunnelConnection(rt TunnelConnection, opts ...MarshalOption) ([]byte, error) | {
cfg, err := collectOptions(opts)
if err != nil {
return nil, trace.Wrap(err)
}
switch resource := rt.(type) {
case *TunnelConnectionV2:
if !cfg.PreserveResourceID {
// avoid modifying the original object
// to prevent unexpected data races
copy := *resource
copy.SetResourceID(0)
resource = ©
}
return utils.FastMarshal(resource)
default:
return nil, trace.BadParameter("unrecognized resource version %T", rt)
}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/status_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/status_command.go#L41-L44 | go | train | // Initialize allows StatusCommand to plug itself into the CLI parser. | func (c *StatusCommand) Initialize(app *kingpin.Application, config *service.Config) | // Initialize allows StatusCommand to plug itself into the CLI parser.
func (c *StatusCommand) Initialize(app *kingpin.Application, config *service.Config) | {
c.config = config
c.status = app.Command("status", "Report cluster status")
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/status_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/status_command.go#L47-L55 | go | train | // TryRun takes the CLI command as an argument (like "nodes ls") and executes it. | func (c *StatusCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error) | // TryRun takes the CLI command as an argument (like "nodes ls") and executes it.
func (c *StatusCommand) TryRun(cmd string, client auth.ClientI) (match bool, err error) | {
switch cmd {
case c.status.FullCommand():
err = c.Status(client)
default:
return false, nil
}
return true, trace.Wrap(err)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | tool/tctl/common/status_command.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/tool/tctl/common/status_command.go#L58-L126 | go | train | // Status is called to execute "status" CLI command. | func (c *StatusCommand) Status(client auth.ClientI) error | // Status is called to execute "status" CLI command.
func (c *StatusCommand) Status(client auth.ClientI) error | {
clusterNameResource, err := client.GetClusterName()
if err != nil {
return trace.Wrap(err)
}
clusterName := clusterNameResource.GetClusterName()
hostCAs, err := client.GetCertAuthorities(services.HostCA, false)
if err != nil {
return trace.Wrap(err)
}
userCAs, err := client.GetCertAuthorities(services.UserCA, false)
if err != nil {
return trace.Wrap(err)
}
// Calculate the CA pin for this cluster. The CA pin is used by the client
// to verify the identity of the Auth Server.
caPin, err := calculateCAPin(client)
if err != nil {
return trace.Wrap(err)
}
authorities := append(userCAs, hostCAs...)
view := func() string {
table := asciitable.MakeHeadlessTable(2)
table.AddRow([]string{"Cluster", clusterName})
for _, ca := range authorities {
if ca.GetClusterName() != clusterName {
continue
}
info := fmt.Sprintf("%v CA ", strings.Title(string(ca.GetType())))
rotation := ca.GetRotation()
if c.config.Debug {
table.AddRow([]string{info,
fmt.Sprintf("%v, update_servers: %v, complete: %v",
rotation.String(),
rotation.Schedule.UpdateServers.Format(teleport.HumanDateFormatSeconds),
rotation.Schedule.Standby.Format(teleport.HumanDateFormatSeconds),
)})
} else {
table.AddRow([]string{info, rotation.String()})
}
}
table.AddRow([]string{"CA pin", caPin})
return table.AsBuffer().String()
}
fmt.Printf(view())
// in debug mode, output mode of remote certificate authorities
if c.config.Debug {
view := func() string {
table := asciitable.MakeHeadlessTable(2)
for _, ca := range authorities {
if ca.GetClusterName() == clusterName {
continue
}
info := fmt.Sprintf("Remote %v CA %q", strings.Title(string(ca.GetType())), ca.GetClusterName())
rotation := ca.GetRotation()
table.AddRow([]string{info, rotation.String()})
}
return "Remote clusters\n\n" + table.AsBuffer().String()
}
fmt.Printf(view())
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/trustedcluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L38-L147 | go | train | // UpsertTrustedCluster creates or toggles a Trusted Cluster relationship. | func (a *AuthServer) UpsertTrustedCluster(trustedCluster services.TrustedCluster) (services.TrustedCluster, error) | // UpsertTrustedCluster creates or toggles a Trusted Cluster relationship.
func (a *AuthServer) UpsertTrustedCluster(trustedCluster services.TrustedCluster) (services.TrustedCluster, error) | {
var exists bool
// it is recommended to omit trusted cluster name, because
// it will be always set to the cluster name as set by the cluster
var existingCluster services.TrustedCluster
var err error
if trustedCluster.GetName() != "" {
existingCluster, err = a.Presence.GetTrustedCluster(trustedCluster.GetName())
if err == nil {
exists = true
}
}
enable := trustedCluster.GetEnabled()
// if the trusted cluster already exists in the backend, make sure it's a
// valid state change client is trying to make
if exists == true {
err := existingCluster.CanChangeStateTo(trustedCluster)
if err != nil {
return nil, trace.Wrap(err)
}
}
// change state
switch {
case exists == true && enable == true:
log.Debugf("Enabling existing Trusted Cluster relationship.")
err := a.activateCertAuthority(trustedCluster)
if err != nil {
if trace.IsNotFound(err) {
return nil, trace.BadParameter("enable only supported for Trusted Clusters created with Teleport 2.3 and above")
}
return nil, trace.Wrap(err)
}
err = a.createReverseTunnel(trustedCluster)
if err != nil {
return nil, trace.Wrap(err)
}
case exists == true && enable == false:
log.Debugf("Disabling existing Trusted Cluster relationship.")
err := a.deactivateCertAuthority(trustedCluster)
if err != nil {
if trace.IsNotFound(err) {
return nil, trace.BadParameter("enable only supported for Trusted Clusters created with Teleport 2.3 and above")
}
return nil, trace.Wrap(err)
}
err = a.DeleteReverseTunnel(trustedCluster.GetName())
if err != nil {
return nil, trace.Wrap(err)
}
case exists == false && enable == true:
log.Debugf("Creating enabled Trusted Cluster relationship.")
if err := a.checkLocalRoles(trustedCluster.GetRoleMap()); err != nil {
return nil, trace.Wrap(err)
}
remoteCAs, err := a.establishTrust(trustedCluster)
if err != nil {
return nil, trace.Wrap(err)
}
// force name of the trusted cluster resource
// to be equal to the name of the remote cluster it is connecting to
trustedCluster.SetName(remoteCAs[0].GetClusterName())
err = a.addCertAuthorities(trustedCluster, remoteCAs)
if err != nil {
return nil, trace.Wrap(err)
}
err = a.createReverseTunnel(trustedCluster)
if err != nil {
return nil, trace.Wrap(err)
}
case exists == false && enable == false:
log.Debugf("Creating disabled Trusted Cluster relationship.")
if err := a.checkLocalRoles(trustedCluster.GetRoleMap()); err != nil {
return nil, trace.Wrap(err)
}
remoteCAs, err := a.establishTrust(trustedCluster)
if err != nil {
return nil, trace.Wrap(err)
}
// force name to the name of the trusted cluster
trustedCluster.SetName(remoteCAs[0].GetClusterName())
err = a.addCertAuthorities(trustedCluster, remoteCAs)
if err != nil {
return nil, trace.Wrap(err)
}
err = a.deactivateCertAuthority(trustedCluster)
if err != nil {
return nil, trace.Wrap(err)
}
}
return a.Presence.UpsertTrustedCluster(trustedCluster)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/trustedcluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L171-L199 | go | train | // DeleteTrustedCluster removes services.CertAuthority, services.ReverseTunnel,
// and services.TrustedCluster resources. | func (a *AuthServer) DeleteTrustedCluster(name string) error | // DeleteTrustedCluster removes services.CertAuthority, services.ReverseTunnel,
// and services.TrustedCluster resources.
func (a *AuthServer) DeleteTrustedCluster(name string) error | {
err := a.DeleteCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: name})
if err != nil {
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
}
err = a.DeleteCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: name})
if err != nil {
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
}
err = a.DeleteReverseTunnel(name)
if err != nil {
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
}
err = a.Presence.DeleteTrustedCluster(name)
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/trustedcluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L293-L325 | go | train | // DeleteRemoteCluster deletes remote cluster resource, all certificate authorities
// associated with it | func (a *AuthServer) DeleteRemoteCluster(clusterName string) error | // DeleteRemoteCluster deletes remote cluster resource, all certificate authorities
// associated with it
func (a *AuthServer) DeleteRemoteCluster(clusterName string) error | {
// To make sure remote cluster exists - to protect against random
// clusterName requests (e.g. when clusterName is set to local cluster name)
_, err := a.Presence.GetRemoteCluster(clusterName)
if err != nil {
return trace.Wrap(err)
}
// delete cert authorities associated with the cluster
err = a.DeleteCertAuthority(services.CertAuthID{
Type: services.HostCA,
DomainName: clusterName,
})
if err != nil {
// this method could have succeeded on the first call,
// but then if the remote cluster resource could not be deleted
// it would be impossible to delete the cluster after then
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
}
// there should be no User CA in trusted clusters on the main cluster side
// per standard automation but clean up just in case
err = a.DeleteCertAuthority(services.CertAuthID{
Type: services.UserCA,
DomainName: clusterName,
})
if err != nil {
if !trace.IsNotFound(err) {
return trace.Wrap(err)
}
}
return a.Presence.DeleteRemoteCluster(clusterName)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/trustedcluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L328-L339 | go | train | // GetRemoteCluster returns remote cluster by name | func (a *AuthServer) GetRemoteCluster(clusterName string) (services.RemoteCluster, error) | // GetRemoteCluster returns remote cluster by name
func (a *AuthServer) GetRemoteCluster(clusterName string) (services.RemoteCluster, error) | {
// To make sure remote cluster exists - to protect against random
// clusterName requests (e.g. when clusterName is set to local cluster name)
remoteCluster, err := a.Presence.GetRemoteCluster(clusterName)
if err != nil {
return nil, trace.Wrap(err)
}
if err := a.updateRemoteClusterStatus(remoteCluster); err != nil {
return nil, trace.Wrap(err)
}
return remoteCluster, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/trustedcluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L357-L370 | go | train | // GetRemoteClusters returns remote clusters with updated statuses | func (a *AuthServer) GetRemoteClusters(opts ...services.MarshalOption) ([]services.RemoteCluster, error) | // GetRemoteClusters returns remote clusters with updated statuses
func (a *AuthServer) GetRemoteClusters(opts ...services.MarshalOption) ([]services.RemoteCluster, error) | {
// To make sure remote cluster exists - to protect against random
// clusterName requests (e.g. when clusterName is set to local cluster name)
remoteClusters, err := a.Presence.GetRemoteClusters(opts...)
if err != nil {
return nil, trace.Wrap(err)
}
for i := range remoteClusters {
if err := a.updateRemoteClusterStatus(remoteClusters[i]); err != nil {
return nil, trace.Wrap(err)
}
}
return remoteClusters, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/trustedcluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L599-L606 | go | train | // activateCertAuthority will activate both the user and host certificate
// authority given in the services.TrustedCluster resource. | func (a *AuthServer) activateCertAuthority(t services.TrustedCluster) error | // activateCertAuthority will activate both the user and host certificate
// authority given in the services.TrustedCluster resource.
func (a *AuthServer) activateCertAuthority(t services.TrustedCluster) error | {
err := a.ActivateCertAuthority(services.CertAuthID{Type: services.UserCA, DomainName: t.GetName()})
if err != nil {
return trace.Wrap(err)
}
return trace.Wrap(a.ActivateCertAuthority(services.CertAuthID{Type: services.HostCA, DomainName: t.GetName()}))
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/auth/trustedcluster.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/auth/trustedcluster.go#L621-L627 | go | train | // createReverseTunnel will create a services.ReverseTunnel givenin the
// services.TrustedCluster resource. | func (a *AuthServer) createReverseTunnel(t services.TrustedCluster) error | // createReverseTunnel will create a services.ReverseTunnel givenin the
// services.TrustedCluster resource.
func (a *AuthServer) createReverseTunnel(t services.TrustedCluster) error | {
reverseTunnel := services.NewReverseTunnel(
t.GetName(),
[]string{t.GetReverseTunnelAddress()},
)
return trace.Wrap(a.UpsertReverseTunnel(reverseTunnel))
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L41-L51 | go | train | // GetClusterName gets the name of the cluster from the backend. | func (s *ClusterConfigurationService) GetClusterName(opts ...services.MarshalOption) (services.ClusterName, error) | // GetClusterName gets the name of the cluster from the backend.
func (s *ClusterConfigurationService) GetClusterName(opts ...services.MarshalOption) (services.ClusterName, error) | {
item, err := s.Get(context.TODO(), backend.Key(clusterConfigPrefix, namePrefix))
if err != nil {
if trace.IsNotFound(err) {
return nil, trace.NotFound("cluster name not found")
}
return nil, trace.Wrap(err)
}
return services.GetClusterNameMarshaler().Unmarshal(item.Value,
services.AddOptions(opts, services.WithResourceID(item.ID))...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L54-L63 | go | train | // DeleteClusterName deletes services.ClusterName from the backend. | func (s *ClusterConfigurationService) DeleteClusterName() error | // DeleteClusterName deletes services.ClusterName from the backend.
func (s *ClusterConfigurationService) DeleteClusterName() error | {
err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, namePrefix))
if err != nil {
if trace.IsNotFound(err) {
return trace.NotFound("cluster configuration not found")
}
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L67-L83 | go | train | // SetClusterName sets the name of the cluster in the backend. SetClusterName
// can only be called once on a cluster after which it will return trace.AlreadyExists. | func (s *ClusterConfigurationService) SetClusterName(c services.ClusterName) error | // SetClusterName sets the name of the cluster in the backend. SetClusterName
// can only be called once on a cluster after which it will return trace.AlreadyExists.
func (s *ClusterConfigurationService) SetClusterName(c services.ClusterName) error | {
value, err := services.GetClusterNameMarshaler().Marshal(c)
if err != nil {
return trace.Wrap(err)
}
_, err = s.Create(context.TODO(), backend.Item{
Key: backend.Key(clusterConfigPrefix, namePrefix),
Value: value,
Expires: c.Expiry(),
})
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L106-L116 | go | train | // GetStaticTokens gets the list of static tokens used to provision nodes. | func (s *ClusterConfigurationService) GetStaticTokens() (services.StaticTokens, error) | // GetStaticTokens gets the list of static tokens used to provision nodes.
func (s *ClusterConfigurationService) GetStaticTokens() (services.StaticTokens, error) | {
item, err := s.Get(context.TODO(), backend.Key(clusterConfigPrefix, staticTokensPrefix))
if err != nil {
if trace.IsNotFound(err) {
return nil, trace.NotFound("static tokens not found")
}
return nil, trace.Wrap(err)
}
return services.GetStaticTokensMarshaler().Unmarshal(item.Value,
services.WithResourceID(item.ID), services.WithExpires(item.Expires))
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L119-L135 | go | train | // SetStaticTokens sets the list of static tokens used to provision nodes. | func (s *ClusterConfigurationService) SetStaticTokens(c services.StaticTokens) error | // SetStaticTokens sets the list of static tokens used to provision nodes.
func (s *ClusterConfigurationService) SetStaticTokens(c services.StaticTokens) error | {
value, err := services.GetStaticTokensMarshaler().Marshal(c)
if err != nil {
return trace.Wrap(err)
}
_, err = s.Put(context.TODO(), backend.Item{
Key: backend.Key(clusterConfigPrefix, staticTokensPrefix),
Value: value,
Expires: c.Expiry(),
ID: c.GetResourceID(),
})
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L138-L147 | go | train | // DeleteStaticTokens deletes static tokens | func (s *ClusterConfigurationService) DeleteStaticTokens() error | // DeleteStaticTokens deletes static tokens
func (s *ClusterConfigurationService) DeleteStaticTokens() error | {
err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, staticTokensPrefix))
if err != nil {
if trace.IsNotFound(err) {
return trace.NotFound("static tokens are not found")
}
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L151-L161 | go | train | // GetAuthPreference fetches the cluster authentication preferences
// from the backend and return them. | func (s *ClusterConfigurationService) GetAuthPreference() (services.AuthPreference, error) | // GetAuthPreference fetches the cluster authentication preferences
// from the backend and return them.
func (s *ClusterConfigurationService) GetAuthPreference() (services.AuthPreference, error) | {
item, err := s.Get(context.TODO(), backend.Key(authPrefix, preferencePrefix, generalPrefix))
if err != nil {
if trace.IsNotFound(err) {
return nil, trace.NotFound("authentication preference not found")
}
return nil, trace.Wrap(err)
}
return services.GetAuthPreferenceMarshaler().Unmarshal(item.Value,
services.WithResourceID(item.ID), services.WithExpires(item.Expires))
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L165-L183 | go | train | // SetAuthPreference sets the cluster authentication preferences
// on the backend. | func (s *ClusterConfigurationService) SetAuthPreference(preferences services.AuthPreference) error | // SetAuthPreference sets the cluster authentication preferences
// on the backend.
func (s *ClusterConfigurationService) SetAuthPreference(preferences services.AuthPreference) error | {
value, err := services.GetAuthPreferenceMarshaler().Marshal(preferences)
if err != nil {
return trace.Wrap(err)
}
item := backend.Item{
Key: backend.Key(authPrefix, preferencePrefix, generalPrefix),
Value: value,
ID: preferences.GetResourceID(),
}
_, err = s.Put(context.TODO(), item)
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L186-L197 | go | train | // GetClusterConfig gets services.ClusterConfig from the backend. | func (s *ClusterConfigurationService) GetClusterConfig(opts ...services.MarshalOption) (services.ClusterConfig, error) | // GetClusterConfig gets services.ClusterConfig from the backend.
func (s *ClusterConfigurationService) GetClusterConfig(opts ...services.MarshalOption) (services.ClusterConfig, error) | {
item, err := s.Get(context.TODO(), backend.Key(clusterConfigPrefix, generalPrefix))
if err != nil {
if trace.IsNotFound(err) {
return nil, trace.NotFound("cluster configuration not found")
}
return nil, trace.Wrap(err)
}
return services.GetClusterConfigMarshaler().Unmarshal(item.Value,
services.AddOptions(opts, services.WithResourceID(item.ID),
services.WithExpires(item.Expires))...)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L200-L209 | go | train | // DeleteClusterConfig deletes services.ClusterConfig from the backend. | func (s *ClusterConfigurationService) DeleteClusterConfig() error | // DeleteClusterConfig deletes services.ClusterConfig from the backend.
func (s *ClusterConfigurationService) DeleteClusterConfig() error | {
err := s.Delete(context.TODO(), backend.Key(clusterConfigPrefix, generalPrefix))
if err != nil {
if trace.IsNotFound(err) {
return trace.NotFound("cluster configuration not found")
}
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/services/local/configuration.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/services/local/configuration.go#L212-L230 | go | train | // SetClusterConfig sets services.ClusterConfig on the backend. | func (s *ClusterConfigurationService) SetClusterConfig(c services.ClusterConfig) error | // SetClusterConfig sets services.ClusterConfig on the backend.
func (s *ClusterConfigurationService) SetClusterConfig(c services.ClusterConfig) error | {
value, err := services.GetClusterConfigMarshaler().Marshal(c)
if err != nil {
return trace.Wrap(err)
}
item := backend.Item{
Key: backend.Key(clusterConfigPrefix, generalPrefix),
Value: value,
ID: c.GetResourceID(),
}
_, err = s.Put(context.TODO(), item)
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/httplib/httpheaders.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httpheaders.go#L27-L31 | go | train | // SetNoCacheHeaders tells proxies and browsers do not cache the content | func SetNoCacheHeaders(h http.Header) | // SetNoCacheHeaders tells proxies and browsers do not cache the content
func SetNoCacheHeaders(h http.Header) | {
h.Set("Cache-Control", "no-cache, no-store, must-revalidate")
h.Set("Pragma", "no-cache")
h.Set("Expires", "0")
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/httplib/httpheaders.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/httplib/httpheaders.go#L40-L70 | go | train | // SetIndexHTMLHeaders sets security header flags for main index.html page | func SetIndexHTMLHeaders(h http.Header) | // SetIndexHTMLHeaders sets security header flags for main index.html page
func SetIndexHTMLHeaders(h http.Header) | {
SetNoCacheHeaders(h)
SetSameOriginIFrame(h)
SetNoSniff(h)
// X-Frame-Options indicates that the page can only be displayed in iframe on the same origin as the page itself
h.Set("X-Frame-Options", "SAMEORIGIN")
// X-XSS-Protection is a feature of Internet Explorer, Chrome and Safari that stops pages
// from loading when they detect reflected cross-site scripting (XSS) attacks.
h.Set("X-XSS-Protection", "1; mode=block")
// Once a supported browser receives this header that browser will prevent any communications from
// being sent over HTTP to the specified domain and will instead send all communications over HTTPS.
// It also prevents HTTPS click through prompts on browsers
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
// Prevent web browsers from using content sniffing to discover a file’s MIME type
h.Set("X-Content-Type-Options", "nosniff")
// Set content policy flags
var cspValue = strings.Join([]string{
"script-src 'self'",
// 'unsafe-inline' needed for reactjs inline styles
"style-src 'self' 'unsafe-inline'",
"object-src 'none'",
"img-src 'self' data: blob:",
}, ";")
h.Set("Content-Security-Policy", cspValue)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/roundtrip.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/roundtrip.go#L99-L101 | go | train | // NewSpdyRoundTripperWithDialer creates a new SpdyRoundTripper that will use
// the specified tlsConfig. This function is mostly meant for unit tests. | func NewSpdyRoundTripperWithDialer(cfg roundTripperConfig) *SpdyRoundTripper | // NewSpdyRoundTripperWithDialer creates a new SpdyRoundTripper that will use
// the specified tlsConfig. This function is mostly meant for unit tests.
func NewSpdyRoundTripperWithDialer(cfg roundTripperConfig) *SpdyRoundTripper | {
return &SpdyRoundTripper{tlsConfig: cfg.tlsConfig, followRedirects: cfg.followRedirects, dialWithContext: cfg.dial, ctx: cfg.ctx, authCtx: cfg.authCtx, bearerToken: cfg.bearerToken}
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/roundtrip.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/roundtrip.go#L125-L127 | go | train | // dial dials the host specified by req | func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) | // dial dials the host specified by req
func (s *SpdyRoundTripper) dial(req *http.Request) (net.Conn, error) | {
return s.dialWithoutProxy(req.URL)
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/roundtrip.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/roundtrip.go#L130-L172 | go | train | // dialWithoutProxy dials the host specified by url, using TLS if appropriate. | func (s *SpdyRoundTripper) dialWithoutProxy(url *url.URL) (net.Conn, error) | // dialWithoutProxy dials the host specified by url, using TLS if appropriate.
func (s *SpdyRoundTripper) dialWithoutProxy(url *url.URL) (net.Conn, error) | {
dialAddr := netutil.CanonicalAddr(url)
if url.Scheme == "http" {
switch {
case s.dialWithContext != nil:
return s.dialWithContext(s.ctx, "tcp", dialAddr)
default:
return net.Dial("tcp", dialAddr)
}
}
// TODO validate the TLSClientConfig is set up?
var conn *tls.Conn
var err error
if s.dialWithContext == nil {
conn, err = tls.Dial("tcp", dialAddr, s.tlsConfig)
} else {
conn, err = utils.TLSDial(s.ctx, s.dialWithContext, "tcp", dialAddr, s.tlsConfig)
}
if err != nil {
return nil, err
}
// Return if we were configured to skip validation
if s.tlsConfig != nil && s.tlsConfig.InsecureSkipVerify {
return conn, nil
}
host, _, err := net.SplitHostPort(dialAddr)
if err != nil {
return nil, err
}
if s.tlsConfig != nil && len(s.tlsConfig.ServerName) > 0 {
host = s.tlsConfig.ServerName
}
err = conn.VerifyHostname(host)
if err != nil {
return nil, err
}
return conn, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/kube/proxy/roundtrip.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/kube/proxy/roundtrip.go#L187-L241 | go | train | // RoundTrip executes the Request and upgrades it. After a successful upgrade,
// clients may call SpdyRoundTripper.Connection() to retrieve the upgraded
// connection. | func (s *SpdyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) | // RoundTrip executes the Request and upgrades it. After a successful upgrade,
// clients may call SpdyRoundTripper.Connection() to retrieve the upgraded
// connection.
func (s *SpdyRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) | {
header := utilnet.CloneHeader(req.Header)
header.Add(httpstream.HeaderConnection, httpstream.HeaderUpgrade)
header.Add(httpstream.HeaderUpgrade, streamspdy.HeaderSpdy31)
// impersonation for remote clusters is handled by remote proxies
if !s.authCtx.cluster.isRemote {
header.Add("Impersonate-User", s.authCtx.User.GetName())
log.Debugf("Impersonate User: %v", s.authCtx.User)
for _, group := range s.authCtx.kubeGroups {
header.Add("Impersonate-Group", group)
log.Debugf("Impersonate Group: %v", group)
}
if s.bearerToken != "" {
log.Debugf("Using Bearer Token Auth")
header.Set("Authorization", fmt.Sprintf("Bearer %v", s.bearerToken))
}
}
var (
conn net.Conn
rawResponse []byte
err error
)
if s.followRedirects {
conn, rawResponse, err = utilnet.ConnectWithRedirects(req.Method, req.URL, header, req.Body, s)
} else {
clone := utilnet.CloneRequest(req)
clone.Header = header
conn, err = s.Dial(clone)
}
if err != nil {
return nil, err
}
responseReader := bufio.NewReader(
io.MultiReader(
bytes.NewBuffer(rawResponse),
conn,
),
)
resp, err := http.ReadResponse(responseReader, nil)
if err != nil {
if conn != nil {
conn.Close()
}
return nil, err
}
s.conn = conn
return resp, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L59-L92 | go | train | // BuildIdentityContext returns an IdentityContext populated with information
// about the logged in user on the connection. | func (h *AuthHandlers) CreateIdentityContext(sconn *ssh.ServerConn) (IdentityContext, error) | // BuildIdentityContext returns an IdentityContext populated with information
// about the logged in user on the connection.
func (h *AuthHandlers) CreateIdentityContext(sconn *ssh.ServerConn) (IdentityContext, error) | {
identity := IdentityContext{
TeleportUser: sconn.Permissions.Extensions[utils.CertTeleportUser],
Certificate: []byte(sconn.Permissions.Extensions[utils.CertTeleportUserCertificate]),
Login: sconn.User(),
}
clusterName, err := h.AccessPoint.GetClusterName()
if err != nil {
return IdentityContext{}, trace.Wrap(err)
}
certificate, err := identity.GetCertificate()
if err != nil {
return IdentityContext{}, trace.Wrap(err)
}
if certificate.ValidBefore != 0 {
identity.CertValidBefore = time.Unix(int64(certificate.ValidBefore), 0)
}
certAuthority, err := h.authorityForCert(services.UserCA, certificate.SignatureKey)
if err != nil {
return IdentityContext{}, trace.Wrap(err)
}
identity.CertAuthority = certAuthority
roleSet, err := h.fetchRoleSet(certificate, certAuthority, identity.TeleportUser, clusterName.GetClusterName())
if err != nil {
return IdentityContext{}, trace.Wrap(err)
}
identity.RoleSet = roleSet
return identity, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L95-L101 | go | train | // CheckAgentForward checks if agent forwarding is allowed for the users RoleSet. | func (h *AuthHandlers) CheckAgentForward(ctx *ServerContext) error | // CheckAgentForward checks if agent forwarding is allowed for the users RoleSet.
func (h *AuthHandlers) CheckAgentForward(ctx *ServerContext) error | {
if err := ctx.Identity.RoleSet.CheckAgentForward(ctx.Identity.Login); err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L104-L125 | go | train | // CheckPortForward checks if port forwarding is allowed for the users RoleSet. | func (h *AuthHandlers) CheckPortForward(addr string, ctx *ServerContext) error | // CheckPortForward checks if port forwarding is allowed for the users RoleSet.
func (h *AuthHandlers) CheckPortForward(addr string, ctx *ServerContext) error | {
if ok := ctx.Identity.RoleSet.CanPortForward(); !ok {
systemErrorMessage := fmt.Sprintf("port forwarding not allowed by role set: %v", ctx.Identity.RoleSet)
userErrorMessage := "port forwarding not allowed"
// emit port forward failure event
h.AuditLog.EmitAuditEvent(events.PortForwardFailure, events.EventFields{
events.PortForwardAddr: addr,
events.PortForwardSuccess: false,
events.PortForwardErr: systemErrorMessage,
events.EventLogin: ctx.Identity.Login,
events.EventUser: ctx.Identity.TeleportUser,
events.LocalAddr: ctx.Conn.LocalAddr().String(),
events.RemoteAddr: ctx.Conn.RemoteAddr().String(),
})
h.Warnf("Port forwarding request denied: %v.", systemErrorMessage)
return trace.AccessDenied(userErrorMessage)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L129-L229 | go | train | // UserKeyAuth implements SSH client authentication using public keys and is
// called by the server every time the client connects. | func (h *AuthHandlers) UserKeyAuth(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) | // UserKeyAuth implements SSH client authentication using public keys and is
// called by the server every time the client connects.
func (h *AuthHandlers) UserKeyAuth(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) | {
fingerprint := fmt.Sprintf("%v %v", key.Type(), sshutils.Fingerprint(key))
// as soon as key auth starts, we know something about the connection, so
// update *log.Entry.
h.Entry = log.WithFields(log.Fields{
trace.Component: h.Component,
trace.ComponentFields: log.Fields{
"local": conn.LocalAddr(),
"remote": conn.RemoteAddr(),
"user": conn.User(),
"fingerprint": fingerprint,
},
})
cid := fmt.Sprintf("conn(%v->%v, user=%v)", conn.RemoteAddr(), conn.LocalAddr(), conn.User())
h.Debugf("%v auth attempt", cid)
cert, ok := key.(*ssh.Certificate)
h.Debugf("%v auth attempt with key %v, %#v", cid, fingerprint, cert)
if !ok {
h.Debugf("auth attempt, unsupported key type")
return nil, trace.BadParameter("unsupported key type: %v", fingerprint)
}
if len(cert.ValidPrincipals) == 0 {
h.Debugf("need a valid principal for key")
return nil, trace.BadParameter("need a valid principal for key %v", fingerprint)
}
if len(cert.KeyId) == 0 {
h.Debugf("need a valid key ID for key")
return nil, trace.BadParameter("need a valid key for key %v", fingerprint)
}
teleportUser := cert.KeyId
// only failed attempts are logged right now
recordFailedLogin := func(err error) {
fields := events.EventFields{
events.EventUser: teleportUser,
events.AuthAttemptSuccess: false,
events.AuthAttemptErr: err.Error(),
}
h.Warnf("failed login attempt %#v", fields)
h.AuditLog.EmitAuditEvent(events.AuthAttemptFailure, fields)
}
// Check that the user certificate uses supported public key algorithms, was
// issued by Teleport, and check the certificate metadata (principals,
// timestamp, etc). Fallback to keys is not supported.
certChecker := utils.CertChecker{
CertChecker: ssh.CertChecker{
IsUserAuthority: h.IsUserAuthority,
},
}
permissions, err := certChecker.Authenticate(conn, key)
if err != nil {
recordFailedLogin(err)
return nil, trace.Wrap(err)
}
h.Debugf("Successfully authenticated")
// see if the host user is valid, we only do this when logging into a teleport node
if h.isTeleportNode() {
_, err = user.Lookup(conn.User())
if err != nil {
host, _ := os.Hostname()
h.Warnf("host '%s' does not have OS user '%s'", host, conn.User())
h.Errorf("no such user")
return nil, trace.AccessDenied("no such user: '%s'", conn.User())
}
}
clusterName, err := h.AccessPoint.GetClusterName()
if err != nil {
return nil, trace.Wrap(err)
}
// this is the only way we know of to pass valid additional data about the
// connection to the handlers
permissions.Extensions[utils.CertTeleportUser] = teleportUser
permissions.Extensions[utils.CertTeleportClusterName] = clusterName.GetClusterName()
permissions.Extensions[utils.CertTeleportUserCertificate] = string(ssh.MarshalAuthorizedKey(cert))
if h.isProxy() {
return permissions, nil
}
// check if the user has permission to log into the node.
switch {
case h.Component == teleport.ComponentForwardingNode:
err = h.canLoginWithoutRBAC(cert, clusterName.GetClusterName(), teleportUser, conn.User())
default:
err = h.canLoginWithRBAC(cert, clusterName.GetClusterName(), teleportUser, conn.User())
}
if err != nil {
h.Errorf("Permission denied: %v", err)
recordFailedLogin(err)
return nil, trace.Wrap(err)
}
return permissions, nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L237-L263 | go | train | // HostKeyAuth implements host key verification and is called by the client
// to validate the certificate presented by the target server. If the target
// server presents a SSH certificate, we validate that it was Teleport that
// generated the certificate. If the target server presents a public key, if
// we are strictly checking keys, we reject the target server. If we are not
// we take whatever. | func (h *AuthHandlers) HostKeyAuth(addr string, remote net.Addr, key ssh.PublicKey) error | // HostKeyAuth implements host key verification and is called by the client
// to validate the certificate presented by the target server. If the target
// server presents a SSH certificate, we validate that it was Teleport that
// generated the certificate. If the target server presents a public key, if
// we are strictly checking keys, we reject the target server. If we are not
// we take whatever.
func (h *AuthHandlers) HostKeyAuth(addr string, remote net.Addr, key ssh.PublicKey) error | {
fingerprint := fmt.Sprintf("%v %v", key.Type(), sshutils.Fingerprint(key))
// update entry to include a fingerprint of the key so admins can track down
// the key causing problems
h.Entry = log.WithFields(log.Fields{
trace.Component: h.Component,
trace.ComponentFields: log.Fields{
"remote": remote.String(),
"fingerprint": fingerprint,
},
})
// Check if the given host key was signed by a Teleport certificate
// authority (CA) or fallback to host key checking if it's allowed.
certChecker := utils.CertChecker{
CertChecker: ssh.CertChecker{
IsHostAuthority: h.IsHostAuthority,
HostKeyFallback: h.hostKeyCallback,
},
}
err := certChecker.CheckHostKey(addr, remote, key)
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L267-L281 | go | train | // hostKeyCallback allows connections to hosts that present keys only if
// strict host key checking is disabled. | func (h *AuthHandlers) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error | // hostKeyCallback allows connections to hosts that present keys only if
// strict host key checking is disabled.
func (h *AuthHandlers) hostKeyCallback(hostname string, remote net.Addr, key ssh.PublicKey) error | {
// If strict host key checking is enabled, reject host key fallback.
clusterConfig, err := h.AccessPoint.GetClusterConfig()
if err != nil {
return trace.Wrap(err)
}
if clusterConfig.GetProxyChecksHostKeys() == services.HostKeyCheckYes {
return trace.AccessDenied("remote host presented a public key, expected a host certificate")
}
// If strict host key checking is not enabled, log that Teleport trusted an
// insecure key, but allow the request to go through.
h.Warn("Insecure configuration! Strict host key checking disabled, allowing login without checking host key of type %v.", key.Type())
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L285-L291 | go | train | // IsUserAuthority is called during checking the client key, to see if the
// key used to sign the certificate was a Teleport CA. | func (h *AuthHandlers) IsUserAuthority(cert ssh.PublicKey) bool | // IsUserAuthority is called during checking the client key, to see if the
// key used to sign the certificate was a Teleport CA.
func (h *AuthHandlers) IsUserAuthority(cert ssh.PublicKey) bool | {
if _, err := h.authorityForCert(services.UserCA, cert); err != nil {
return false
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L296-L302 | go | train | // IsHostAuthority is called when checking the host certificate a server
// presents. It make sure that the key used to sign the host certificate was a
// Teleport CA. | func (h *AuthHandlers) IsHostAuthority(cert ssh.PublicKey, address string) bool | // IsHostAuthority is called when checking the host certificate a server
// presents. It make sure that the key used to sign the host certificate was a
// Teleport CA.
func (h *AuthHandlers) IsHostAuthority(cert ssh.PublicKey, address string) bool | {
if _, err := h.authorityForCert(services.HostCA, cert); err != nil {
h.Entry.Debugf("Unable to find SSH host CA: %v.", err)
return false
}
return true
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L307-L317 | go | train | // canLoginWithoutRBAC checks the given certificate (supplied by a connected
// client) to see if this certificate can be allowed to login as user:login
// pair to requested server. | func (h *AuthHandlers) canLoginWithoutRBAC(cert *ssh.Certificate, clusterName string, teleportUser, osUser string) error | // canLoginWithoutRBAC checks the given certificate (supplied by a connected
// client) to see if this certificate can be allowed to login as user:login
// pair to requested server.
func (h *AuthHandlers) canLoginWithoutRBAC(cert *ssh.Certificate, clusterName string, teleportUser, osUser string) error | {
h.Debugf("Checking permissions for (%v,%v) to login to node without RBAC checks.", teleportUser, osUser)
// check if the ca that signed the certificate is known to the cluster
_, err := h.authorityForCert(services.UserCA, cert.SignatureKey)
if err != nil {
return trace.Wrap(err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L322-L344 | go | train | // canLoginWithRBAC checks the given certificate (supplied by a connected
// client) to see if this certificate can be allowed to login as user:login
// pair to requested server and if RBAC rules allow login. | func (h *AuthHandlers) canLoginWithRBAC(cert *ssh.Certificate, clusterName string, teleportUser, osUser string) error | // canLoginWithRBAC checks the given certificate (supplied by a connected
// client) to see if this certificate can be allowed to login as user:login
// pair to requested server and if RBAC rules allow login.
func (h *AuthHandlers) canLoginWithRBAC(cert *ssh.Certificate, clusterName string, teleportUser, osUser string) error | {
h.Debugf("Checking permissions for (%v,%v) to login to node with RBAC checks.", teleportUser, osUser)
// get the ca that signd the users certificate
ca, err := h.authorityForCert(services.UserCA, cert.SignatureKey)
if err != nil {
return trace.Wrap(err)
}
// get roles assigned to this user
roles, err := h.fetchRoleSet(cert, ca, teleportUser, clusterName)
if err != nil {
return trace.Wrap(err)
}
// check if roles allow access to server
if err := roles.CheckAccessToServer(osUser, h.Server.GetInfo()); err != nil {
return trace.AccessDenied("user %s@%s is not authorized to login as %v@%s: %v",
teleportUser, ca.GetClusterName(), osUser, clusterName, err)
}
return nil
} |
gravitational/teleport | d5243dbe8d36bba44bf640c08f1c49185ed2c8a4 | lib/srv/authhandlers.go | https://github.com/gravitational/teleport/blob/d5243dbe8d36bba44bf640c08f1c49185ed2c8a4/lib/srv/authhandlers.go#L347-L381 | go | train | // fetchRoleSet fetches the services.RoleSet assigned to a Teleport user. | func (h *AuthHandlers) fetchRoleSet(cert *ssh.Certificate, ca services.CertAuthority, teleportUser string, clusterName string) (services.RoleSet, error) | // fetchRoleSet fetches the services.RoleSet assigned to a Teleport user.
func (h *AuthHandlers) fetchRoleSet(cert *ssh.Certificate, ca services.CertAuthority, teleportUser string, clusterName string) (services.RoleSet, error) | {
// for local users, go and check their individual permissions
var roles services.RoleSet
if clusterName == ca.GetClusterName() {
u, err := h.AccessPoint.GetUser(teleportUser)
if err != nil {
return nil, trace.Wrap(err)
}
// Pass along the traits so we get the substituted roles for this user.
roles, err = services.FetchRoles(u.GetRoles(), h.AccessPoint, u.GetTraits())
if err != nil {
return nil, trace.Wrap(err)
}
} else {
certRoles, err := extractRolesFromCert(cert)
if err != nil {
return nil, trace.AccessDenied("failed to parse certificate roles")
}
roleNames, err := ca.CombinedMapping().Map(certRoles)
if err != nil {
return nil, trace.AccessDenied("failed to map roles")
}
// pass the principals on the certificate along as the login traits
// to the remote cluster.
traits := map[string][]string{
teleport.TraitLogins: cert.ValidPrincipals,
}
roles, err = services.FetchRoles(roleNames, h.AccessPoint, traits)
if err != nil {
return nil, trace.Wrap(err)
}
}
return roles, nil
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.