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

Fix tsh logout with broken key dir #32351

Merged
merged 3 commits into from
Sep 22, 2023
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
27 changes: 27 additions & 0 deletions api/utils/keys/privatekey.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ package keys
import (
"bytes"
"crypto"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
Expand Down Expand Up @@ -212,6 +214,31 @@ func ParsePrivateKey(keyPEM []byte) (*PrivateKey, error) {
}
}

// MarshalPrivateKey will return a PEM encoded crypto.Signer.
// Only supports rsa, ecdsa, and ed25519 keys.
func MarshalPrivateKey(key crypto.Signer) ([]byte, error) {
switch privateKey := key.(type) {
case *rsa.PrivateKey:
privPEM := pem.EncodeToMemory(&pem.Block{
Type: PKCS1PrivateKeyType,
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
})
return privPEM, nil
case *ecdsa.PrivateKey, *ed25519.PrivateKey:
der, err := x509.MarshalPKCS8PrivateKey(privateKey)
if err != nil {
return nil, trace.Wrap(err)
}
privPEM := pem.EncodeToMemory(&pem.Block{
Type: PKCS8PrivateKeyType,
Bytes: der,
})
return privPEM, nil
default:
return nil, trace.BadParameter("unsupported private key type %T", key)
}
}

// LoadKeyPair returns the PrivateKey for the given private and public key files.
func LoadKeyPair(privFile, sshPubFile string) (*PrivateKey, error) {
privPEM, err := os.ReadFile(privFile)
Expand Down
8 changes: 7 additions & 1 deletion lib/client/interfaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ func (k *Key) authorizedHostKeys(hostnames ...string) ([]ssh.PublicKey, error) {
// TeleportClientTLSConfig returns client TLS configuration used
// to authenticate against API servers.
func (k *Key) TeleportClientTLSConfig(cipherSuites []uint16, clusters []string) (*tls.Config, error) {
if len(k.TLSCert) == 0 {
return nil, trace.NotFound("TLS certificate not found")
}
return k.clientTLSConfig(cipherSuites, k.TLSCert, clusters)
}

Expand Down Expand Up @@ -399,6 +402,9 @@ func canAddToSystemAgent(agentKey agent.AddedKey) bool {
// TeleportTLSCertificate returns the parsed x509 certificate for
// authentication against Teleport APIs.
func (k *Key) TeleportTLSCertificate() (*x509.Certificate, error) {
if len(k.TLSCert) == 0 {
return nil, trace.NotFound("TLS certificate not found")
}
return tlsca.ParseCertificatePEM(k.TLSCert)
}

Expand Down Expand Up @@ -491,7 +497,7 @@ func (k *Key) SSHSigner() (ssh.Signer, error) {
// SSHCert returns parsed SSH certificate
func (k *Key) SSHCert() (*ssh.Certificate, error) {
if k.Cert == nil {
return nil, trace.NotFound("SSH cert not available")
return nil, trace.NotFound("SSH cert not found")
}
return sshutils.ParseCertificate(k.Cert)
}
Expand Down
6 changes: 3 additions & 3 deletions tool/tsh/common/tsh.go
Original file line number Diff line number Diff line change
Expand Up @@ -2030,7 +2030,7 @@ func onLogin(cf *CLIConf) error {
func onLogout(cf *CLIConf) error {
// Extract all clusters the user is currently logged into.
active, available, err := cf.FullProfileStatus()
if err != nil {
if err != nil && !trace.IsCompareFailed(err) {
if trace.IsNotFound(err) {
fmt.Printf("All users logged out.\n")
return nil
Expand Down Expand Up @@ -2061,7 +2061,7 @@ func onLogout(cf *CLIConf) error {

// Load profile for the requested proxy/user.
profile, err := tc.ProfileStatus()
if err != nil && !trace.IsNotFound(err) {
if err != nil && !trace.IsNotFound(err) && !trace.IsCompareFailed(err) {
return trace.Wrap(err)
}

Expand Down Expand Up @@ -3389,7 +3389,7 @@ func makeClientForProxy(cf *CLIConf, proxy string) (*client.TeleportClient, erro
profile, profileError := c.GetProfile(c.ClientStore, proxy)
if profileError == nil {
if err := tc.LoadKeyForCluster(ctx, profile.SiteName); err != nil {
if !trace.IsNotFound(err) && !trace.IsConnectionProblem(err) {
if !trace.IsNotFound(err) && !trace.IsConnectionProblem(err) && !trace.IsCompareFailed(err) {
return nil, trace.Wrap(err)
}
log.WithError(err).Infof("Could not load key for %s into the local agent.", cf.SiteName)
Expand Down
83 changes: 83 additions & 0 deletions tool/tsh/common/tsh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ import (
"bytes"
"context"
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
Expand All @@ -44,6 +47,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
otlp "go.opentelemetry.io/proto/otlp/trace/v1"
"golang.org/x/crypto/ssh"
"golang.org/x/exp/slices"
yamlv2 "gopkg.in/yaml.v2"

Expand Down Expand Up @@ -5058,3 +5062,82 @@ func TestBenchmarkMySQL(t *testing.T) {
})
}
}

func TestLogout(t *testing.T) {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
privPEM, err := keys.MarshalPrivateKey(key)
require.NoError(t, err)
privateKey, err := keys.NewPrivateKey(key, privPEM)
require.NoError(t, err)
clientKey := &client.Key{
KeyIndex: client.KeyIndex{
ProxyHost: "proxy",
Username: "user",
ClusterName: "cluster",
},
PrivateKey: privateKey,
}
profile := &profile.Profile{
WebProxyAddr: clientKey.ProxyHost,
Username: clientKey.Username,
SiteName: clientKey.ClusterName,
}

for _, tt := range []struct {
name string
modifyKeyDir func(t *testing.T, homePath string)
}{
{
name: "normal home dir",
modifyKeyDir: func(t *testing.T, homePath string) {},
}, {
name: "public key missing",
modifyKeyDir: func(t *testing.T, homePath string) {
pubKeyPath := keypaths.PublicKeyPath(homePath, clientKey.ProxyHost, clientKey.Username)
require.NoError(t, os.Remove(pubKeyPath))
},
}, {
name: "private key missing",
modifyKeyDir: func(t *testing.T, homePath string) {
privKeyPath := keypaths.UserKeyPath(homePath, clientKey.ProxyHost, clientKey.Username)
require.NoError(t, os.Remove(privKeyPath))
},
}, {
name: "public key mismatch",
modifyKeyDir: func(t *testing.T, homePath string) {
newKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
require.NoError(t, err)
sshPub, err := ssh.NewPublicKey(newKey.Public())
require.NoError(t, err)

pubKeyPath := keypaths.PublicKeyPath(homePath, clientKey.ProxyHost, clientKey.Username)
err = os.WriteFile(pubKeyPath, ssh.MarshalAuthorizedKey(sshPub), 0600)
require.NoError(t, err)
},
},
} {
t.Run(tt.name, func(t *testing.T) {
tmpHomePath := t.TempDir()

store := client.NewFSClientStore(tmpHomePath)
err = store.AddKey(clientKey)
require.NoError(t, err)
store.SaveProfile(profile, true)

tt.modifyKeyDir(t, tmpHomePath)

_, err := os.Lstat(tmpHomePath)
require.NoError(t, err)

err = Run(context.Background(), []string{"logout"}, setHomePath(tmpHomePath))
require.NoError(t, err)

// direcory should be empty.
f, err := os.Open(tmpHomePath)
require.NoError(t, err)
_, err = f.Readdir(1)
require.ErrorIs(t, err, io.EOF)
})
}
}