Skip to content

Commit 112cc29

Browse files
authored
Merge pull request #7 from epithet-ssh/mc/race_condition
Fix race condition in auth flow
2 parents 6e61e26 + 6950def commit 112cc29

File tree

1 file changed

+15
-3
lines changed

1 file changed

+15
-3
lines changed

pkg/agent/agent.go

Lines changed: 15 additions & 3 deletions
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,23 +294,26 @@ 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)
300312
if err != nil && err != io.EOF {
301313
log.Warnf("error from ssh-agent: %v", err)
302-
_ = conn.Close()
303-
// ignoring close erros
304314
}
315+
// close the connection after the credential is served
316+
conn.Close()
305317
}
306318

307319
func (a *Agent) startControlListener() error {

0 commit comments

Comments
 (0)