Skip to content

Commit b94c5e0

Browse files
author
Michael Chang
committed
Fix race condition in auth flow
1 parent 6e61e26 commit b94c5e0

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

pkg/agent/agent.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"io/ioutil"
99
"net"
1010
"os"
11+
"sync"
1112
"time"
1213

1314
rpc "github.com/epithet-ssh/epithet/internal/agent"
@@ -47,6 +48,7 @@ type Agent struct {
4748
privateKey sshcert.RawPrivateKey
4849

4950
hooks map[string]*hook.Hook
51+
lock sync.Mutex
5052
}
5153

5254
// Start creates and starts an SSH Agent
@@ -194,6 +196,13 @@ func (a *Agent) UseCredential(c Credential) error {
194196
return nil
195197
}
196198

199+
// CheckCertificate checks if the certificate is expired or invalid
200+
func (a *Agent) CheckCertificate() bool {
201+
a.lock.Lock()
202+
defer a.lock.Unlock()
203+
return a.certExpires.Load() < uint64(time.Now().Unix())+CertExpirationFuzzWindow
204+
}
205+
197206
// RequestCertificate tries to convert a `{token, pubkey}` into a certificate
198207
func (a *Agent) RequestCertificate(ctx context.Context, token string) error {
199208
a.lastToken.Store(token)
@@ -285,15 +294,18 @@ const CertExpirationFuzzWindow = 20
285294

286295
func (a *Agent) serveAgent(conn net.Conn) {
287296
log.Debug("new connection to agent")
288-
if a.certExpires.Load() < uint64(time.Now().Unix())+CertExpirationFuzzWindow {
297+
if a.CheckCertificate() {
298+
a.lock.Lock()
289299
err := a.RequestCertificate(a.ctx, a.lastToken.Load())
290300
if err != nil {
291301
err = a.hookNeedAuth()
292302
if err != nil {
293303
conn.Close()
304+
a.lock.Unlock()
294305
return
295306
}
296307
}
308+
a.lock.Unlock()
297309
}
298310

299311
err := agent.ServeAgent(a.keyring, conn)

0 commit comments

Comments
 (0)