|
8 | 8 | "io/ioutil" |
9 | 9 | "net" |
10 | 10 | "os" |
| 11 | + "sync" |
11 | 12 | "time" |
12 | 13 |
|
13 | 14 | rpc "github.com/epithet-ssh/epithet/internal/agent" |
@@ -47,6 +48,7 @@ type Agent struct { |
47 | 48 | privateKey sshcert.RawPrivateKey |
48 | 49 |
|
49 | 50 | hooks map[string]*hook.Hook |
| 51 | + lock sync.Mutex |
50 | 52 | } |
51 | 53 |
|
52 | 54 | // Start creates and starts an SSH Agent |
@@ -194,6 +196,13 @@ func (a *Agent) UseCredential(c Credential) error { |
194 | 196 | return nil |
195 | 197 | } |
196 | 198 |
|
| 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 | + |
197 | 206 | // RequestCertificate tries to convert a `{token, pubkey}` into a certificate |
198 | 207 | func (a *Agent) RequestCertificate(ctx context.Context, token string) error { |
199 | 208 | a.lastToken.Store(token) |
@@ -285,23 +294,26 @@ const CertExpirationFuzzWindow = 20 |
285 | 294 |
|
286 | 295 | func (a *Agent) serveAgent(conn net.Conn) { |
287 | 296 | log.Debug("new connection to agent") |
288 | | - if a.certExpires.Load() < uint64(time.Now().Unix())+CertExpirationFuzzWindow { |
| 297 | + if a.CheckCertificate() { |
| 298 | + a.lock.Lock() |
289 | 299 | err := a.RequestCertificate(a.ctx, a.lastToken.Load()) |
290 | 300 | if err != nil { |
291 | 301 | err = a.hookNeedAuth() |
292 | 302 | if err != nil { |
293 | 303 | conn.Close() |
| 304 | + a.lock.Unlock() |
294 | 305 | return |
295 | 306 | } |
296 | 307 | } |
| 308 | + a.lock.Unlock() |
297 | 309 | } |
298 | 310 |
|
299 | 311 | err := agent.ServeAgent(a.keyring, conn) |
300 | 312 | if err != nil && err != io.EOF { |
301 | 313 | log.Warnf("error from ssh-agent: %v", err) |
302 | | - _ = conn.Close() |
303 | | - // ignoring close erros |
304 | 314 | } |
| 315 | + // close the connection after the credential is served |
| 316 | + conn.Close() |
305 | 317 | } |
306 | 318 |
|
307 | 319 | func (a *Agent) startControlListener() error { |
|
0 commit comments