-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
agent.go
65 lines (54 loc) · 1.51 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
// Copyright (c) 2021 Blacknon. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
package sshlib
import (
"net"
"os"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
// AgentInterface Interface for storing agent.Agent or agent.ExtendedAgent.
type AgentInterface interface{}
// ConnectSshAgent
func ConnectSshAgent() (ag AgentInterface) {
// Get env "SSH_AUTH_SOCK" and connect.
sockPath := os.Getenv("SSH_AUTH_SOCK")
sock, err := net.Dial("unix", sockPath)
if err != nil {
ag = agent.NewKeyring()
} else {
// connect SSH_AUTH_SOCK
ag = agent.NewClient(sock)
}
return
}
// AddKeySshAgent is rapper agent.Add().
// key must be a *rsa.PrivateKey, *dsa.PrivateKey or
// *ecdsa.PrivateKey, which will be inserted into the agent.
//
// Should use `ssh.ParseRawPrivateKey()` or `ssh.ParseRawPrivateKeyWithPassphrase()`.
func (c *Connect) AddKeySshAgent(sshAgent interface{}, key interface{}) {
addedKey := agent.AddedKey{
PrivateKey: key,
ConfirmBeforeUse: true,
LifetimeSecs: 3000,
}
switch ag := sshAgent.(type) {
case agent.Agent:
ag.Add(addedKey)
case agent.ExtendedAgent:
ag.Add(addedKey)
}
}
// ForwardAgent forward ssh-agent in session.
func (c *Connect) ForwardSshAgent(session *ssh.Session) {
// forward ssh-agent
switch ag := c.Agent.(type) {
case agent.Agent:
agent.ForwardToAgent(c.Client, ag)
case agent.ExtendedAgent:
agent.ForwardToAgent(c.Client, ag)
}
agent.RequestAgentForwarding(session)
}