/
operator.go
159 lines (128 loc) · 3.71 KB
/
operator.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package operator
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net"
"os"
"strings"
"github.com/mitchellh/go-homedir"
"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/terminal"
)
type CommandRes struct {
StdOut []byte
StdErr []byte
}
type CommandOperator interface {
Execute(command string) error
Output(command string) ([]byte, error)
Upload(src io.Reader, remotePath string, mode string) error
UploadFile(path string, remotePath string, mode string) error
}
type Callback func(CommandOperator) error
func ExecuteLocal(callback Callback) error {
return callback(NewLocalOperator())
}
func ExecuteRemote(host string, user string, privateKey string, password string, callback Callback) error {
var method ssh.AuthMethod
if password != "" {
method = ssh.Password(password)
} else if privateKey == "" {
sshAgentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK"))
if err != nil {
return NewSshAgentError(err)
}
defer sshAgentConn.Close()
client := agent.NewClient(sshAgentConn)
list, err := client.List()
if err != nil || len(list) == 0 {
return NewSshAgentError(err)
}
method = ssh.PublicKeysCallback(client.Signers)
} else {
buffer, err := ioutil.ReadFile(expandPath(privateKey))
if err != nil {
return errors.Wrapf(err, "unable to parse private key: %s", privateKey)
}
key, err := ssh.ParsePrivateKey(buffer)
if err != nil {
if err.Error() != "ssh: this private key is passphrase protected" {
return errors.Wrapf(err, "unable to parse private key: %s", privateKey)
}
sshAgent, closeAgent := privateKeyUsingSSHAgent(privateKey + ".pub")
defer closeAgent()
if sshAgent != nil {
method = sshAgent
} else {
fmt.Printf("Enter passphrase for '%s': ", privateKey)
STDIN := int(os.Stdin.Fd())
bytePassword, _ := terminal.ReadPassword(STDIN)
fmt.Println()
key, err = ssh.ParsePrivateKeyWithPassphrase(buffer, bytePassword)
if err != nil {
return errors.Wrapf(err, "parse private key with passphrase failed: %s", privateKey)
}
method = ssh.PublicKeys(key)
}
} else {
method = ssh.PublicKeys(key)
}
}
return executeRemote(host, user, method, callback)
}
func privateKeyUsingSSHAgent(publicKeyPath string) (ssh.AuthMethod, func() error) {
if sshAgentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
sshAgent := agent.NewClient(sshAgentConn)
signers, err := sshAgent.Signers()
if err != nil || len(signers) == 0 {
return nil, sshAgentConn.Close
}
pubkey, err := ioutil.ReadFile(expandPath(publicKeyPath))
if err != nil {
return nil, sshAgentConn.Close
}
authkey, _, _, _, err := ssh.ParseAuthorizedKey(pubkey)
if err != nil {
return nil, sshAgentConn.Close
}
parsedkey := authkey.Marshal()
for _, signer := range signers {
if bytes.Equal(signer.PublicKey().Marshal(), parsedkey) {
return ssh.PublicKeys(signer), sshAgentConn.Close
}
}
}
return nil, func() error { return nil }
}
func executeRemote(address string, user string, authMethod ssh.AuthMethod, callback Callback) error {
host, port, err := net.SplitHostPort(address)
if err != nil {
if strings.Contains(err.Error(), "missing port") {
host = address
port = "22"
} else {
return fmt.Errorf("error splitting host/port: %w", err)
}
}
config := &ssh.ClientConfig{
User: user,
Auth: []ssh.AuthMethod{
authMethod,
},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
operator, err := NewSSHOperator(net.JoinHostPort(host, port), config)
if err != nil {
return NewTargetConnectError(err)
}
defer operator.Close()
return callback(operator)
}
func expandPath(path string) string {
res, _ := homedir.Expand(path)
return res
}