From d7a1e09a3ac7d8ae3929bcf658bc4bda0fcd13be Mon Sep 17 00:00:00 2001 From: Scott Leggett Date: Mon, 13 Dec 2021 22:53:51 +0800 Subject: [PATCH] fix: close all cards on exit This fixes a bug where if piv-agent exited due to an idle or exit timer then connections to the card were left in pcscd, and then when piv-agent started up again it couldn't (re)open the card. --- cmd/piv-agent/serve.go | 1 + internal/keyservice/piv/keyservice.go | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/cmd/piv-agent/serve.go b/cmd/piv-agent/serve.go index df1f9a6..2eb94e2 100644 --- a/cmd/piv-agent/serve.go +++ b/cmd/piv-agent/serve.go @@ -50,6 +50,7 @@ func (cmd *ServeCmd) Run(log *zap.Logger) error { log.Info("startup", zap.String("version", version), zap.String("build date", date)) p := piv.New(log) + defer p.CloseAll() // use FDs passed via socket activation ls, err := sockets.Get(validAgents) if err != nil { diff --git a/internal/keyservice/piv/keyservice.go b/internal/keyservice/piv/keyservice.go index 01130fb..5c68dad 100644 --- a/internal/keyservice/piv/keyservice.go +++ b/internal/keyservice/piv/keyservice.go @@ -138,3 +138,11 @@ func (p *KeyService) GetDecrypter(keygrip []byte) (crypto.Decrypter, error) { } return &ECDHKey{ecdsa: ecdsaPrivKey}, nil } + +// CloseAll closes all security keys without checking for errors. +// This should be called to clean up connections to `pcscd`. +func (p *KeyService) CloseAll() { + for _, k := range p.securityKeys { + _ = k.Close() + } +}