From c4d1cf63291f3e0da239b05fee11ad9f523a2020 Mon Sep 17 00:00:00 2001 From: Adam Simpson Date: Thu, 10 Jun 2021 22:24:10 -0400 Subject: [PATCH] feat: parse cert expiration and use as lifetime for agent. This keeps the ssh-agent from "filling up" with expired certs over time. An additional option would be to check ssh-agent for expired certs before we add them and remove them then. --- cmd/ssh.go | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/cmd/ssh.go b/cmd/ssh.go index e75e7e2..a11981e 100644 --- a/cmd/ssh.go +++ b/cmd/ssh.go @@ -13,6 +13,7 @@ import ( "net/http" "os" "sb/util" + "time" "github.com/spf13/cobra" "golang.org/x/crypto/ssh" @@ -79,6 +80,11 @@ func parseCert(cert Cert) (sshCert *ssh.Certificate, key *ecdsa.PrivateKey, erro } func addToAgent(cert *ssh.Certificate, key *ecdsa.PrivateKey) { + // validBefore - now === ssh-agent lifetime + diff := time.Unix(int64(cert.ValidBefore), 0).Sub(time.Now()) + // need seconds for lifetime to pass to Agent + lifetime := int(diff.Seconds()) + con, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")) if err != nil { @@ -87,11 +93,14 @@ func addToAgent(cert *ssh.Certificate, key *ecdsa.PrivateKey) { sshAgent := agent.NewClient(con) - if err = sshAgent.Add(agent.AddedKey{ - PrivateKey: key, - Certificate: cert, - }); err != nil { - log.Fatal("ssh-agent failure: ", err) + err = sshAgent.Add(agent.AddedKey{ + PrivateKey: key, + Certificate: cert, + LifetimeSecs: uint32(lifetime), + }) + + if err != nil { + log.Fatal("Failed to add to ssh-agent: ", err) } }