-
Notifications
You must be signed in to change notification settings - Fork 0
/
agent.go
102 lines (87 loc) · 2.18 KB
/
agent.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package teleagent
import (
"io"
"net"
"time"
"github.com/gravitational/teleport/lib/auth/native"
"github.com/gravitational/teleport/lib/utils"
"github.com/gravitational/teleport/lib/web"
log "github.com/Sirupsen/logrus"
"github.com/gravitational/trace"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// AgentServer is implementation of SSH agent server
type AgentServer struct {
agent.Agent
}
// NewServer returns new instance of agent server
func NewServer() *AgentServer {
return &AgentServer{agent.NewKeyring()}
}
// ListenAndServe is similar http.ListenAndServe
func (a *AgentServer) ListenAndServe(addr utils.NetAddr) error {
l, err := net.Listen(addr.AddrNetwork, addr.Addr)
if err != nil {
return trace.Wrap(err)
}
for {
conn, err := l.Accept()
if err != nil {
log.Errorf(err.Error())
continue
}
go func() {
if err := agent.ServeAgent(a.Agent, conn); err != nil {
if err != io.EOF {
log.Errorf(err.Error())
}
}
}()
}
}
// Client is a client connection to SSH agent
type Client struct {
agent.Agent
}
// NewClient returns a new client connected to remote agent
func NewClient(addr utils.NetAddr) (*Client, error) {
conn, err := net.Dial(addr.AddrNetwork, addr.Addr)
if err != nil {
return nil, trace.Wrap(err)
}
return &Client{agent.NewClient(conn)}, nil
}
// Login logins with remote proxy and adds the certificate to it
func (a *Client) Login(proxyAddr string,
user string, pass string, hotpToken string,
ttl time.Duration, insecure bool) error {
priv, pub, err := native.New().GenerateKeyPair("")
if err != nil {
return trace.Wrap(err)
}
login, err := web.SSHAgentLogin(proxyAddr, user, pass, hotpToken,
pub, ttl, insecure, nil)
if err != nil {
return trace.Wrap(err)
}
pcert, _, _, _, err := ssh.ParseAuthorizedKey(login.Cert)
if err != nil {
return trace.Wrap(err)
}
pk, err := ssh.ParseRawPrivateKey(priv)
if err != nil {
return trace.Wrap(err)
}
addedKey := agent.AddedKey{
PrivateKey: pk,
Certificate: pcert.(*ssh.Certificate),
Comment: "",
LifetimeSecs: 0,
ConfirmBeforeUse: false,
}
if err := a.Agent.Add(addedKey); err != nil {
return trace.Wrap(err)
}
return nil
}