Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

tsh: print kubernetes info in profile status #4348

Merged
merged 1 commit into from
Oct 14, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions lib/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import (
"fmt"
"math/rand"
"net/url"
"sort"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -560,6 +561,13 @@ func (s *AuthServer) generateUserCert(req certRequest) (*certs, error) {
if err := CheckKubeCluster(req.kubernetesCluster, s.Presence); err != nil {
return nil, trace.Wrap(err)
}
} else {
kc, err := defaultKubeCluster(s.Presence, clusterName)
if err != nil {
log.Warningf("Failed setting default kubernetes cluster for user login (user did not provide a cluster): %v; leaving KubernetesCluster extension in the TLS certificate empty", err)
} else {
req.kubernetesCluster = kc
}
}
// generate TLS certificate
tlsAuthority, err := ca.TLSCA()
Expand Down Expand Up @@ -615,6 +623,40 @@ func CheckKubeCluster(kc string, pg services.ProxyGetter) error {
return trace.BadParameter("kubernetes cluster %q is not registered in this teleport cluster; you can list registered kubernetes clusters using 'tsh kube clusters'", kc)
}

// defaultKubeCluster returns the default kubernetes cluster for user logins.
//
// This is the cluster with a name matching the Teleport cluster name (for
// backwards-compatibility with pre-5.0 behavior) or the first name
// alphabetically. If no clusters are registered, a NotFound error is returned.
func defaultKubeCluster(pg services.ProxyGetter, teleportClusterName string) (string, error) {
proxies, err := pg.GetProxies()
if err != nil {
return "", trace.Wrap(err)
}
clusterNames := make(map[string]struct{})
for _, p := range proxies {
pp, ok := p.(*services.ServerV2)
if !ok {
continue
}
for _, pkc := range pp.Spec.KubernetesClusters {
if pkc == teleportClusterName {
return pkc, nil
}
clusterNames[pkc] = struct{}{}
}
}
if len(clusterNames) == 0 {
return "", trace.NotFound("no kubernetes clusters registered in this Teleport cluster")
}
var namesUniq []string
for n := range clusterNames {
namesUniq = append(namesUniq, n)
}
sort.Strings(namesUniq)
return namesUniq[0], nil
}

// WithUserLock executes function authenticateFn that performs user authentication
// if authenticateFn returns non nil error, the login attempt will be logged in as failed.
// The only exception to this rule is ConnectionProblemError, in case if it occurs
Expand Down
45 changes: 36 additions & 9 deletions lib/client/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import (
"github.com/gravitational/teleport/lib/session"
"github.com/gravitational/teleport/lib/shell"
"github.com/gravitational/teleport/lib/sshutils/scp"
"github.com/gravitational/teleport/lib/tlsca"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/utils/agentconn"
"github.com/gravitational/teleport/lib/wrappers"
Expand Down Expand Up @@ -305,6 +306,19 @@ type ProfileStatus struct {
// Logins are the Linux accounts, also known as principals in OpenSSH terminology.
Logins []string

// KubeEnabled is true when this profile is configured to connect to a
// kubernetes cluster.
KubeEnabled bool

// KubeCluster is the name of the kubernetes cluster used by this profile.
KubeCluster string

// KubeUsers are the kubernetes users used by this profile.
KubeUsers []string

// KubeGroups are the kubernetes groups used by this profile.
KubeGroups []string

// ValidUntil is the time at which this SSH certificate will expire.
ValidUntil time.Time

Expand Down Expand Up @@ -385,26 +399,26 @@ func readProfile(profileDir string, profileName string) (*ProfileStatus, error)
if err != nil {
return nil, trace.Wrap(err)
}
keys, err := store.GetKey(profile.Name(), profile.Username)
key, err := store.GetKey(profile.Name(), profile.Username)
if err != nil {
return nil, trace.Wrap(err)
}
publicKey, _, _, _, err := ssh.ParseAuthorizedKey(keys.Cert)
publicKey, _, _, _, err := ssh.ParseAuthorizedKey(key.Cert)
if err != nil {
return nil, trace.Wrap(err)
}
cert, ok := publicKey.(*ssh.Certificate)
sshCert, ok := publicKey.(*ssh.Certificate)
if !ok {
return nil, trace.BadParameter("no certificate found")
}

// Extract from the certificate how much longer it will be valid for.
validUntil := time.Unix(int64(cert.ValidBefore), 0)
validUntil := time.Unix(int64(sshCert.ValidBefore), 0)

// Extract roles from certificate. Note, if the certificate is in old format,
// this will be empty.
var roles []string
rawRoles, ok := cert.Extensions[teleport.CertExtensionTeleportRoles]
rawRoles, ok := sshCert.Extensions[teleport.CertExtensionTeleportRoles]
if ok {
roles, err = services.UnmarshalCertRoles(rawRoles)
if err != nil {
Expand All @@ -416,7 +430,7 @@ func readProfile(profileDir string, profileName string) (*ProfileStatus, error)
// Extract traits from the certificate. Note if the certificate is in the
// old format, this will be empty.
var traits wrappers.Traits
rawTraits, ok := cert.Extensions[teleport.CertExtensionTeleportTraits]
rawTraits, ok := sshCert.Extensions[teleport.CertExtensionTeleportTraits]
if ok {
err = wrappers.UnmarshalTraits([]byte(rawTraits), &traits)
if err != nil {
Expand All @@ -425,7 +439,7 @@ func readProfile(profileDir string, profileName string) (*ProfileStatus, error)
}

var activeRequests services.RequestIDs
rawRequests, ok := cert.Extensions[teleport.CertExtensionTeleportActiveRequests]
rawRequests, ok := sshCert.Extensions[teleport.CertExtensionTeleportActiveRequests]
if ok {
if err := activeRequests.Unmarshal([]byte(rawRequests)); err != nil {
return nil, trace.Wrap(err)
Expand All @@ -435,7 +449,7 @@ func readProfile(profileDir string, profileName string) (*ProfileStatus, error)
// Extract extensions from certificate. This lists the abilities of the
// certificate (like can the user request a PTY, port forwarding, etc.)
var extensions []string
for ext := range cert.Extensions {
for ext := range sshCert.Extensions {
if ext == teleport.CertExtensionTeleportRoles ||
ext == teleport.CertExtensionTeleportTraits ||
ext == teleport.CertExtensionTeleportRouteToCluster ||
Expand All @@ -457,19 +471,32 @@ func readProfile(profileDir string, profileName string) (*ProfileStatus, error)
clusterName = profile.Name()
}

tlsCert, err := key.TLSCertificate()
if err != nil {
return nil, trace.Wrap(err)
}
tlsID, err := tlsca.FromSubject(tlsCert.Subject, time.Time{})
if err != nil {
return nil, trace.Wrap(err)
}

return &ProfileStatus{
ProxyURL: url.URL{
Scheme: "https",
Host: profile.WebProxyAddr,
},
Username: profile.Username,
Logins: cert.ValidPrincipals,
Logins: sshCert.ValidPrincipals,
ValidUntil: validUntil,
Extensions: extensions,
Roles: roles,
Cluster: clusterName,
Traits: traits,
ActiveRequests: activeRequests,
KubeEnabled: tlsID.KubernetesCluster != "" && (len(tlsID.KubernetesUsers) > 0 || len(tlsID.KubernetesGroups) > 0),
KubeCluster: tlsID.KubernetesCluster,
KubeUsers: tlsID.KubernetesUsers,
KubeGroups: tlsID.KubernetesGroups,
}, nil
}

Expand Down
30 changes: 21 additions & 9 deletions tool/tsh/tsh.go
Original file line number Diff line number Diff line change
Expand Up @@ -1314,25 +1314,37 @@ func printStatus(debug bool, p *client.ProfileStatus, isActive bool) {
humanDuration = fmt.Sprintf("valid for %v", duration.Round(time.Minute))
}

fmt.Printf("%vProfile URL: %v\n", prefix, p.ProxyURL.String())
fmt.Printf(" Logged in as: %v\n", p.Username)
fmt.Printf("%vProfile URL: %v\n", prefix, p.ProxyURL.String())
fmt.Printf(" Logged in as: %v\n", p.Username)
if p.Cluster != "" {
fmt.Printf(" Cluster: %v\n", p.Cluster)
fmt.Printf(" Cluster: %v\n", p.Cluster)
}
fmt.Printf(" Roles: %v*\n", strings.Join(p.Roles, ", "))
fmt.Printf(" Roles: %v*\n", strings.Join(p.Roles, ", "))
if debug {
for k, v := range p.Traits {
if count == 0 {
fmt.Printf(" Traits: %v: %v\n", k, v)
fmt.Printf(" Traits: %v: %v\n", k, v)
} else {
fmt.Printf(" %v: %v\n", k, v)
fmt.Printf(" %v: %v\n", k, v)
}
count = count + 1
}
}
fmt.Printf(" Logins: %v\n", strings.Join(p.Logins, ", "))
fmt.Printf(" Valid until: %v [%v]\n", p.ValidUntil, humanDuration)
fmt.Printf(" Extensions: %v\n", strings.Join(p.Extensions, ", "))
fmt.Printf(" Logins: %v\n", strings.Join(p.Logins, ", "))
if p.KubeEnabled {
fmt.Printf(" Kubernetes: enabled\n")
fmt.Printf(" Kubernetes cluster: %q\n", p.KubeCluster)
if len(p.KubeUsers) > 0 {
fmt.Printf(" Kubernetes users: %v\n", strings.Join(p.KubeUsers, ", "))
}
if len(p.KubeGroups) > 0 {
fmt.Printf(" Kubernetes groups: %v\n", strings.Join(p.KubeGroups, ", "))
}
} else {
fmt.Printf(" Kubernetes: disabled\n")
}
fmt.Printf(" Valid until: %v [%v]\n", p.ValidUntil, humanDuration)
fmt.Printf(" Extensions: %v\n", strings.Join(p.Extensions, ", "))

fmt.Printf("\n")
}
Expand Down