2023-09-19 21:31:41 +02:00
|
|
|
package lib
|
|
|
|
|
|
|
|
import (
|
2023-09-23 17:12:35 +02:00
|
|
|
"io"
|
|
|
|
"net"
|
|
|
|
|
2023-09-19 21:31:41 +02:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
"golang.org/x/crypto/ssh"
|
|
|
|
"golang.org/x/crypto/ssh/agent"
|
|
|
|
)
|
|
|
|
|
2023-09-23 17:12:35 +02:00
|
|
|
type SshAgentKey struct {
|
2023-09-19 21:31:41 +02:00
|
|
|
Key []byte
|
|
|
|
Passphrase []byte
|
2023-09-23 17:12:35 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type SshAgent struct {
|
|
|
|
Keys []SshAgentKey
|
2023-09-19 21:31:41 +02:00
|
|
|
Logger Logger
|
|
|
|
listener net.Listener
|
2023-09-23 17:12:35 +02:00
|
|
|
SocketFile string
|
2023-09-19 21:31:41 +02:00
|
|
|
done chan struct{}
|
|
|
|
}
|
|
|
|
|
2023-09-23 17:12:35 +02:00
|
|
|
func (a *SshAgent) Listen() error {
|
|
|
|
|
|
|
|
var err error
|
|
|
|
|
2023-09-19 21:31:41 +02:00
|
|
|
keyring := agent.NewKeyring()
|
2023-09-23 17:12:35 +02:00
|
|
|
|
|
|
|
for _, k := range a.Keys {
|
|
|
|
var key interface{}
|
|
|
|
|
|
|
|
if len(k.Passphrase) == 0 {
|
|
|
|
key, err = ssh.ParseRawPrivateKey(k.Key)
|
|
|
|
} else {
|
|
|
|
key, err = ssh.ParseRawPrivateKeyWithPassphrase(k.Key, k.Passphrase)
|
|
|
|
}
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "parsing private key")
|
|
|
|
}
|
|
|
|
err = keyring.Add(agent.AddedKey{PrivateKey: key})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-09-19 21:31:41 +02:00
|
|
|
}
|
2023-09-23 17:12:35 +02:00
|
|
|
|
|
|
|
l, err := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: a.SocketFile})
|
2023-09-19 21:31:41 +02:00
|
|
|
if err != nil {
|
2023-09-23 17:12:35 +02:00
|
|
|
return errors.Wrapf(err, "listening on socket %q", a.SocketFile)
|
2023-09-19 21:31:41 +02:00
|
|
|
}
|
|
|
|
l.SetUnlinkOnClose(true)
|
|
|
|
a.listener = l
|
|
|
|
a.done = make(chan struct{})
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
conn, err := a.listener.Accept()
|
|
|
|
if err != nil {
|
|
|
|
select {
|
|
|
|
case <-a.done:
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
a.Logger.Log("error accepting socket connection")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
go func(conn net.Conn) {
|
|
|
|
defer conn.Close()
|
|
|
|
|
|
|
|
if err := agent.ServeAgent(keyring, conn); err != nil && err != io.EOF {
|
|
|
|
a.Logger.Log("error serving SSH agent")
|
|
|
|
}
|
|
|
|
}(conn)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (a *SshAgent) Close() error {
|
|
|
|
close(a.done)
|
|
|
|
return a.listener.Close()
|
|
|
|
}
|