Skip to content

Commit

Permalink
yubikey-agent: release the connection on macOS for YK 5
Browse files Browse the repository at this point in the history
Updates #4
  • Loading branch information
FiloSottile committed Dec 31, 2022
1 parent a812d01 commit 2e5376c
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,19 @@ func (a *Agent) ensureYK() error {
return nil
}

func (a *Agent) maybeReleaseYK() {
// On macOS, YubiKey 5s persist the PIN cache even across sessions (and even
// processes), so we can release the lock on the key, to let other
// applications like age-plugin-yubikey use it.
if runtime.GOOS != "darwin" || a.yk.Version().Major < 5 {
return
}
if err := a.yk.Close(); err != nil {
log.Println("Failed to automatically release YubiKey lock:", err)
}
a.yk = nil
}

func (a *Agent) connectToYK() (*piv.YubiKey, error) {
yk, err := openYK()
if err != nil {
Expand Down Expand Up @@ -216,6 +229,7 @@ func (a *Agent) List() ([]*agent.Key, error) {
if err := a.ensureYK(); err != nil {
return nil, fmt.Errorf("could not reach YubiKey: %w", err)
}
defer a.maybeReleaseYK()

pk, err := getPublicKey(a.yk, piv.SlotAuthentication)
if err != nil {
Expand Down Expand Up @@ -252,6 +266,7 @@ func (a *Agent) Signers() ([]ssh.Signer, error) {
if err := a.ensureYK(); err != nil {
return nil, fmt.Errorf("could not reach YubiKey: %w", err)
}
defer a.maybeReleaseYK()

return a.signers()
}
Expand Down Expand Up @@ -286,6 +301,7 @@ func (a *Agent) SignWithFlags(key ssh.PublicKey, data []byte, flags agent.Signat
if err := a.ensureYK(); err != nil {
return nil, fmt.Errorf("could not reach YubiKey: %w", err)
}
defer a.maybeReleaseYK()

signers, err := a.signers()
if err != nil {
Expand Down

0 comments on commit 2e5376c

Please sign in to comment.