Skip to content
Closed
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
23 changes: 23 additions & 0 deletions agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,28 @@ func (a *Agent) Close() error {
return nil
}

// reap deletes the keys whose lifetime constraint has run out, as the
// reaper of ssh-agent(1) does. The caller holds a.mu.
func (a *Agent) reap() {
now := time.Now()
a.keys = slices.DeleteFunc(a.keys, func(k key.SSHTPMKeys) bool {
exp := k.GetExpiry()
if exp.IsZero() || now.Before(exp) {
return false
}
slog.Debug("deleting key past its lifetime",
slog.String("fingerprint", k.Fingerprint()),
slog.String("type", k.AgentKey().Type()),
)
return true
})
}

func (a *Agent) signers() ([]ssh.Signer, error) {
var signers []ssh.Signer

a.reap()

for _, agent := range a.agents {
l, err := agent.Signers()
if err != nil {
Expand Down Expand Up @@ -146,6 +165,8 @@ func (a *Agent) List() ([]*agent.Key, error) {
a.mu.Lock()
defer a.mu.Unlock()

a.reap()

// Our keys first, then proxied agents
for _, k := range a.keys {
agentKeys = append(agentKeys, k.AgentKey())
Expand Down Expand Up @@ -387,6 +408,8 @@ func (a *Agent) Remove(sshkey ssh.PublicKey) error {
a.mu.Lock()
defer a.mu.Unlock()

a.reap()

var found bool
a.keys = slices.DeleteFunc(a.keys, func(k key.SSHTPMKeys) bool {
if bytes.Equal(sshkey.Marshal(), k.AgentKey().Marshal()) {
Expand Down
105 changes: 105 additions & 0 deletions agent/agent_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package agent_test

import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
Expand All @@ -9,6 +10,7 @@ import (
"net"
"path"
"testing"
"time"

"github.com/foxboron/ssh-tpm-agent/agent"
"github.com/foxboron/ssh-tpm-agent/internal/keyring"
Expand Down Expand Up @@ -229,3 +231,106 @@ func TestRemoveCertFromProxy(t *testing.T) {
})
}
}

func TestLifetime(t *testing.T) {
tpm, err := simulator.OpenSimulator()
if err != nil {
t.Fatal(err)
}
defer tpm.Close()

t.Run("a key added with a lifetime is deleted when it runs out", func(t *testing.T) {
socket := path.Join(t.TempDir(), "socket")
unixList, err := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: socket})
if err != nil {
t.Fatal(err)
}
defer unixList.Close()
ag := agent.NewAgent(unixList,
[]sshagent.ExtendedAgent{},
func() *keyring.ThreadKeyring { return &keyring.ThreadKeyring{} },
func() transport.TPMCloser { return tpm },
func() ([]byte, error) { return []byte(""), nil },
func(_ key.SSHTPMKeys) ([]byte, *keyring.Key, error) { return []byte(""), nil, nil },
)
defer ag.Stop()
conn, err := net.Dial("unix", socket)
if err != nil {
t.Fatal(err)
}
defer conn.Close()
client := sshagent.NewClient(conn)

k, err := key.NewSSHTPMKey(tpm, tpm2.TPMAlgECC, 256, []byte(""))
if err != nil {
t.Fatal(err)
}
if _, err := client.Extension(agent.SSH_TPM_AGENT_ADD, agent.MarshalTPMKeyMsg(&sshagent.AddedKey{
PrivateKey: k,
LifetimeSecs: 1,
})); err != nil {
t.Fatal(err)
}
if l, err := client.List(); err != nil || len(l) != 1 {
t.Fatalf("want the key, got %d keys: %v", len(l), err)
}
time.Sleep(1100 * time.Millisecond)
if l, err := client.List(); err != nil || len(l) != 0 {
t.Fatalf("want no keys past the lifetime, got %d: %v", len(l), err)
}
})

k, err := keytest.MkKey(t, tpm, tpm2.TPMAlgECC, 256, []byte(""), "")
if err != nil {
t.Fatal(err)
}
ca := keytest.MkECDSA(t, elliptic.P256())
certified, err := keytest.MkCertificate(t, &ca)(t, tpm, tpm2.TPMAlgECC, 256, []byte(""), "")
if err != nil {
t.Fatal(err)
}
// with returns a copy of k that the agent deletes at expiry.
with := func(k *key.SSHTPMKey, expiry time.Time) *key.SSHTPMKey {
c := *k
c.Expiry = expiry
return &c
}

t.Run("only the keys past their lifetime go", func(t *testing.T) {
ag := keytest.NewTestAgent(t, tpm)
defer ag.Stop()

gone := with(certified, time.Now().Add(-time.Second))
stays := with(k, time.Now().Add(time.Hour))
for _, k := range []*key.SSHTPMKey{gone, stays, certified} {
if err := ag.AddKey(k); err != nil {
t.Fatal(err)
}
}
l, err := ag.List()
if err != nil {
t.Fatal(err)
}
// certified without a lifetime stays too
if len(l) != 2 || !bytes.Equal(l[0].Blob, (*k.PublicKey).Marshal()) ||
!bytes.Equal(l[1].Blob, certified.Certificate.Marshal()) {
t.Fatalf("want the key with time left and the one without a lifetime, got %d keys", len(l))
}
})

t.Run("a key past its lifetime neither signs nor is removed", func(t *testing.T) {
ag := keytest.NewTestAgent(t, tpm)
defer ag.Stop()

gone := with(certified, time.Now().Add(-time.Second))
if err := ag.AddKey(gone); err != nil {
t.Fatal(err)
}
if _, err := ag.Sign(gone.Certificate, []byte("test")); !errors.Is(err, agent.ErrNoMatchPrivateKeys) {
t.Fatalf("want ErrNoMatchPrivateKeys, got %v", err)
}
if err := ag.Remove(gone.Certificate); err == nil {
t.Fatal("removed a key past its lifetime")
}
})
}
7 changes: 5 additions & 2 deletions agent/gocrypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package agent
import (
"encoding/binary"
"fmt"
"time"

"github.com/foxboron/ssh-tpm-agent/key"
)
Expand Down Expand Up @@ -54,12 +55,14 @@ func parseConstraints(constraints []byte) (lifetimeSecs uint32, confirmBeforeUse
}

func setConstraints(k *key.SSHTPMKey, constraintBytes []byte) error {
_, confirmBeforeUse, err := parseConstraints(constraintBytes)
lifetimeSecs, confirmBeforeUse, err := parseConstraints(constraintBytes)
if err != nil {
return err
}

// LifetimeSecs is not yet supported by ssh-tpm-agent
if lifetimeSecs != 0 {
k.Expiry = time.Now().Add(time.Duration(lifetimeSecs) * time.Second)
}
k.ConfirmBeforeUse = confirmBeforeUse
return nil
}
33 changes: 33 additions & 0 deletions agent/gocrypto_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package agent

import (
"testing"
"time"

"github.com/foxboron/ssh-tpm-agent/key"
"github.com/google/go-tpm/tpm2"
Expand Down Expand Up @@ -50,3 +51,35 @@ func TestTPMKeyMsgConfirmRoundTrip(t *testing.T) {
})
}
}

// The lifetime constraint survives the Marshal/Parse round-trip as the
// expiry of the key, and without one the key never expires.
func TestTPMKeyMsgLifetimeRoundTrip(t *testing.T) {
tpm, err := simulator.OpenSimulator()
if err != nil {
t.Fatal(err)
}
defer tpm.Close()

k, err := key.NewSSHTPMKey(tpm, tpm2.TPMAlgECC, 256, []byte(""))
if err != nil {
t.Fatal(err)
}

before := time.Now()
parsed, err := ParseTPMKeyMsg(MarshalTPMKeyMsg(&sshagent.AddedKey{PrivateKey: k, LifetimeSecs: 60}))
if err != nil {
t.Fatal(err)
}
if exp := parsed.GetExpiry(); exp.Before(before.Add(60*time.Second)) || exp.After(time.Now().Add(60*time.Second)) {
t.Fatalf("expiry %v, want 60s from %v", exp, before)
}

parsed, err = ParseTPMKeyMsg(MarshalTPMKeyMsg(&sshagent.AddedKey{PrivateKey: k}))
if err != nil {
t.Fatal(err)
}
if !parsed.GetExpiry().IsZero() {
t.Fatalf("expiry %v without a lifetime", parsed.GetExpiry())
}
}
9 changes: 9 additions & 0 deletions key/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"strings"
"time"

keyfile "github.com/foxboron/go-tpm-keyfiles"
"github.com/foxboron/ssh-tpm-agent/internal/keyring"
Expand All @@ -26,6 +27,7 @@ type SSHTPMKeys interface {
AgentKey() *agent.Key
GetTPMKey() *keyfile.TPMKey
GetConfirmBeforeUse() bool
GetExpiry() time.Time
}

// SSHTPMKey is a wrapper for TPMKey implementing the ssh.PublicKey specific parts
Expand All @@ -34,6 +36,9 @@ type SSHTPMKey struct {
PublicKey *ssh.PublicKey
Certificate *ssh.Certificate
ConfirmBeforeUse bool
// Expiry is when the agent deletes the key, from the lifetime
// constraint it was added with; zero is never.
Expiry time.Time
}

func WrapTPMKey(k *keyfile.TPMKey) (*SSHTPMKey, error) {
Expand Down Expand Up @@ -124,6 +129,10 @@ func (k *SSHTPMKey) GetConfirmBeforeUse() bool {
return k.ConfirmBeforeUse
}

func (k *SSHTPMKey) GetExpiry() time.Time {
return k.Expiry
}

func (k *SSHTPMKey) Signer(keyring *keyring.ThreadKeyring, ownerAuth func() ([]byte, error), tpm func() transport.TPMCloser, auth func(*keyfile.TPMKey) ([]byte, *keyring.Key, error)) *SSHKeySigner {
return NewSSHKeySigner(k, keyring, ownerAuth, tpm, auth)
}
Expand Down
Loading