forked from blacknon/lssh
/
run.go
405 lines (328 loc) · 9.44 KB
/
run.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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
// Copyright (c) 2019 Blacknon. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
package ssh
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
"github.com/bingoohuang/bssh/common"
"github.com/bingoohuang/gou/pbe"
sshlib "github.com/blacknon/go-sshlib"
"github.com/bingoohuang/bssh/conf"
"github.com/bingoohuang/bssh/misc"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/terminal"
)
// TDXX(blacknon): 自動再接続機能の追加(v0.6.1)
// autosshのように、接続が切れた際に自動的に再接続を試みる動作をさせたい
// パラメータでの有効・無効指定が必要になる。
// TDXX(blacknon): リバースでのsshfsの追加(v0.6.1以降?)
// lsshfs実装後になるか?ssh接続時に、指定したフォルダにローカルの内容をマウントさせて読み取らせる。
// うまくやれれば、ローカルのスクリプトなどをそのままマウントさせて実行させたりできるかもしれない。
// Socketかなにかでトンネルさせて、あとは指定したディレクトリ配下をそのままFUSEでファイルシステムとして利用できるように書けばいける…?
//
// 【参考】
// - https://github.com/rom1v/rsshfs
// - https://github.com/hanwen/go-fuse
// - https://gitlab.com/dns2utf8/revfs/
// Run running info.
type Run struct {
ServerList []string
Conf conf.Config
// Mode value in
// - shell
// - cmd
// - pshell
Mode string
// tty use (-t option)
IsTerm bool
// parallel connect (-p option)
IsParallel bool
// not run (-N option)
IsNone bool
// x11 forwarding (-X option)
X11 bool
// use or not-use local bashrc.
// IsNotBashrc takes precedence.
IsBashrc bool
IsNotBashrc bool
// enable/disable print header in command mode
EnableHeader bool
DisableHeader bool
// StdinData from pipe flag
isStdinPipe bool
// local/remote Port Forwarding
PortForwardMode string // L or R
PortForwardLocal string
PortForwardRemote string
// Dynamic Port Forwarding
// set localhost port num (ex. 11080).
DynamicPortForward string
// Exec command
ExecCmd []string
// Agent is ssh-agent.
// In agent.Agent or agent.ExtendedAgent.
agent interface{}
// AuthMethodMap is
// map of AuthMethod summarized in Run overall
authMethodMap map[AuthKey][]ssh.AuthMethod
// ServerAuthMethodMap is
// Map of AuthMethod used by target server
serverAuthMethodMap map[string][]ssh.AuthMethod
decodedPasswordMap map[string]bool
confFile string
}
// NewRun news a Run struct.
func NewRun(confFile string) *Run {
r := &Run{
decodedPasswordMap: make(map[string]bool),
confFile: confFile,
}
return r
}
// AuthKey define auth key.
type AuthKey struct {
// auth type:
// - password
// - agent
// - key
// - cert
// - pkcs11
Type string
// auth type value:
// - key(path)
// ex.) ~/.ssh/id_rsa
// - cert(path)
// ex.) ~/.ssh/id_rsa.crt
// - pkcs11(libpath)
// ex.) /usr/local/lib/opensc-pkcs11.so
Value string
}
// PathSet ...
type PathSet struct {
Base string
PathSlice []string
}
const (
// AuthKeyPassword auth by Password
AuthKeyPassword = "password"
// AuthKeyKey auth by key
AuthKeyKey = "key"
// AuthKeyCert auth by cert
AuthKeyCert = "cert"
// AuthKeyPkcs11 auth by pkcs11
AuthKeyPkcs11 = "pkcs11"
)
// Start ssh connect.
func (r *Run) Start() {
var err error
// Get stdin data(pipe)
// TDXX(blacknon): os.StdinをReadAllで全部読み込んでから処理する方式だと、ストリームで処理出来ない
// (全部読み込み終わるまで待ってしまう)ので、Reader/Writerによるストリーム処理に切り替える(v0.6.0)
// => flagとして検知させて、あとはpushPipeWriterにos.Stdinを渡すことで対処する
if runtime.GOOS != "windows" {
stdin := 0
if !terminal.IsTerminal(stdin) {
r.isStdinPipe = true
}
}
r.CreateAuthMethodMap()
switch {
case len(r.ExecCmd) > 0 && r.Mode == "cmd":
r.cmd()
case r.Mode == "shell":
err = r.shell()
case r.Mode == "pshell":
err = r.pshell()
default:
return
}
if err != nil {
fmt.Println(err)
}
}
// PrintSelectServer is printout select server.
// use ssh login header.
func (r *Run) PrintSelectServer() {
serverListStr := strings.Join(r.ServerList, ",")
fmt.Fprintf(os.Stderr, "Select Server :%s\n", serverListStr)
}
// printRunCommand is printout run command.
// use ssh command run header.
func (r *Run) printRunCommand() {
runCmdStr := strings.Join(r.ExecCmd, " ")
fmt.Fprintf(os.Stderr, "Run Command :%s\n", runCmdStr)
}
// printPortForward is printout port forwarding.
// use ssh command run header. only use shell().
func (r *Run) printPortForward(m, forwardLocal, forwardRemote string) {
if forwardLocal != "" && forwardRemote != "" {
var mode, arrow string
switch m {
case "L", "":
mode = "LOCAL "
arrow = " =>"
case "R":
mode = "REMOTE"
arrow = "<= "
}
fmt.Fprintf(os.Stderr, "Port Forward :%s\n", mode)
fmt.Fprintf(os.Stderr, " local[%s] %s remote[%s]\n", forwardLocal, arrow, forwardRemote)
}
}
// printPortForward is printout port forwarding.
// use ssh command run header. only use shell().
func (r *Run) printDynamicPortForward(port string) {
if port != "" {
fmt.Fprintf(os.Stderr, "DynamicForward:%s\n", port)
fmt.Fprintf(os.Stderr, " %s\n", "connect Socks5.")
}
}
// printProxy is printout proxy route.
// use ssh command run header. only use shell().
func (r *Run) printProxy(server string) {
array := []string{}
proxyRoute, err := getProxyRoute(server, r.Conf)
if err != nil || len(proxyRoute) == 0 {
return
}
// set localhost
localhost := "localhost"
// set target host
targethost := server
// add localhost
array = append(array, localhost)
for _, pxy := range proxyRoute {
// separator
var sep string
if pxy.Type == misc.Command {
sep = ":"
} else {
sep = "://"
}
// setup string
str := "[" + pxy.Type + sep + pxy.Name
if pxy.Port != "" {
str += ":" + pxy.Port
}
str += "]"
array = append(array, str)
}
// add target
array = append(array, targethost)
// print header
header := strings.Join(array, " => ")
fmt.Fprintf(os.Stderr, "Proxy :%s\n", header)
}
func (r *Run) registerAutoEncryptPwd(oldPwd string) {
if oldPwd == "na" || r.Conf.IsDisableAutoEncryptPwd() || strings.HasPrefix(oldPwd, `{PBE}`) {
return
}
if _, ok := r.decodedPasswordMap[oldPwd]; ok {
return
}
r.decodedPasswordMap[oldPwd] = true
}
func readConfContent(confPath string) (string, error) {
confPath = common.ExpandHomeDir(confPath)
bytes, err := ioutil.ReadFile(confPath)
return string(bytes), err
}
func writeConfContent(confPath, content string) error {
confPath = common.ExpandHomeDir(confPath)
stat, err := os.Stat(confPath)
if err != nil {
return err
}
return ioutil.WriteFile(confPath, []byte(content), stat.Mode())
}
func (r *Run) autoEncryptPwd() {
if r.Conf.IsDisableAutoEncryptPwd() || len(r.decodedPasswordMap) == 0 {
return
}
content, err := readConfContent(r.confFile)
if err != nil {
fmt.Fprintf(os.Stderr, "read conf file %s, error %v\n", r.confFile, err)
return
}
newContent := content
for pwd := range r.decodedPasswordMap {
newPwd, err := pbe.Pbe(pwd)
if err != nil {
fmt.Fprintf(os.Stderr, "read conf file %s, error %v\n", r.confFile, err)
return
}
reg := regexp.MustCompile(`\b` + regexp.QuoteMeta(pwd) + `\b`)
newContent = reg.ReplaceAllString(newContent, newPwd)
}
if newContent != content {
if err := writeConfContent(r.confFile, newContent); err != nil {
fmt.Fprintf(os.Stderr, "write conf file %s, error %v\n", r.confFile, err)
return
}
}
for pwd := range r.decodedPasswordMap {
r.decodedPasswordMap[pwd] = false
}
}
func (r *Run) createAuthMethodMapForServer(server string) {
// get server config
config := r.Conf.Server[server]
// Password
r.registerAuthMapPassword(server, config.Pass)
// Multiple Password
for _, pass := range config.Passes {
r.registerAuthMapPassword(server, pass)
}
// PublicKey
if err := r.registerAuthMapPublicKey(server, config.Key, config.KeyPass); err != nil {
fmt.Fprintln(os.Stderr, err)
}
// Multiple PublicKeys
for _, key := range config.Keys {
pair := strings.SplitN(key, "::", 2)
keyName := pair[0]
keyPass := ""
if len(pair) > 1 {
keyPass = pair[1]
}
if err := r.registerAuthMapPublicKey(server, keyName, keyPass); err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
}
// Public Key Command
// TDXX(blacknon): keyCommandの追加
if err := r.registerAuthMapPublicKeyCommand(server, config.KeyCommand, config.KeyCommandPass); err != nil {
fmt.Fprintln(os.Stderr, err)
}
// Certificate
if config.Cert != "" {
keySigner, err := sshlib.CreateSignerPublicKeyPrompt(config.CertKey, config.CertKeyPass)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
if err := r.registerAuthMapCertificate(server, config.Cert, keySigner); err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
}
// PKCS11
if config.PKCS11Use {
if err := r.registerAuthMapPKCS11(server, config.PKCS11Provider, config.PKCS11PIN); err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
}
// runCmdLocal exec command local machine.
// Mainly used in r.shell().
func execLocalCommand(cmd string) {
out, _ := exec.Command("sh", "-c", cmd).CombinedOutput()
fmt.Print(string(out))
}