-
Notifications
You must be signed in to change notification settings - Fork 2
/
TableSaltCli.go
executable file
·399 lines (316 loc) · 10.8 KB
/
TableSaltCli.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
package main
import (
"fmt"
"os"
"log"
"net"
"strings"
"bytes"
"runtime"
"bufio"
"io"
"io/ioutil"
"regexp"
"path/filepath"
"encoding/json"
"encoding/base64"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
var saltCommand string
var configuration = Configuration{}
var bsshClientConnection *ssh.Client = nil
var hostKeyCallBackConfig ssh.HostKeyCallback = nil
var sshConfig *ssh.ClientConfig = nil
type Configuration struct {
Auth string
UseJump bool
UseSudo bool
SudoType string
HostKeyCheck bool
JumpUsername string
JumpPassword string
JumpPrivateKey string
JumpServer string
RemoteEndpoint string
RemoteUsername string
RemotePassword string
RemotePrivateKey string
}
func SSHAgent() ssh.AuthMethod {
if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
return ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers)
}
return nil
}
func HostKeyCheck(remoteHost string) (ssh.HostKeyCallback) {
host := remoteHost
file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
if err != nil {
log.Fatal(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
var hostKey ssh.PublicKey
for scanner.Scan() {
fields := strings.Split(scanner.Text(), " ")
if len(fields) != 3 {
continue
}
if strings.Contains(fields[0], host) {
var err error
hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
if err != nil {
log.Fatalf("Error parsing %q: %v", fields[2], err)
}
break
}
}
if hostKey == nil {
log.Fatalf("No hostkey for %s. You can disable checks in the config by setting HostKeyCheck to false.", host)
}
return ssh.FixedHostKey(hostKey)
}
func setupJump() {
err := error(nil)
// Set SSH configuration
bsshConfig := generateSshConfig("jump")
bsshClientConnection, err = ssh.Dial("tcp", configuration.JumpServer, bsshConfig)
if err != nil {
log.Fatal(err)
}
}
func generateSshConfig(configType string) (*ssh.ClientConfig) {
var sshConfigUsername string
var sshConfigPassword string
var sshConfigPrivateKey string
var sshConfigEndpoint string
sshAuthMethod := []ssh.AuthMethod{SSHAgent()}
if configType == "jump" {
sshConfigUsername = configuration.JumpUsername
sshConfigPassword = configuration.JumpPassword
sshConfigPrivateKey = configuration.JumpPrivateKey
sshConfigEndpoint = configuration.JumpServer
} else {
sshConfigUsername = configuration.RemoteUsername
sshConfigPassword = configuration.RemotePassword
sshConfigPrivateKey = configuration.RemotePrivateKey
sshConfigEndpoint = configuration.RemoteEndpoint
}
if configuration.Auth == "key" && len(sshConfigPrivateKey) > 0 {
privateBytes, err := ioutil.ReadFile(sshConfigPrivateKey)
if err != nil {
log.Fatal("Failed to load private key: ", err)
}
remoteKey, err := ssh.ParsePrivateKey(privateBytes)
if err != nil {
log.Fatal("Could not parse private key file. Check the path and ensure it is not encrypted.")
}
sshAuthMethod[0] = ssh.PublicKeys(remoteKey)
} else if configuration.Auth == "agent" && runtime.GOOS != "windows" {
sshAuthMethod[0] = SSHAgent()
} else if configuration.Auth == "password" && len(sshConfigPassword) > 0 {
sshAuthMethod[0] = ssh.Password(sshConfigPassword)
} else {
log.Fatal("No supported authentication modes available/supported. Double check your configuration.")
}
if configuration.HostKeyCheck {
hostSplit := strings.Split(sshConfigEndpoint, ":")
hostKeyCallBackConfig = HostKeyCheck(hostSplit[0])
} else {
hostKeyCallBackConfig = ssh.InsecureIgnoreHostKey()
}
sshConfig := &ssh.ClientConfig{
User: sshConfigUsername,
Auth: sshAuthMethod,
HostKeyCallback: hostKeyCallBackConfig,
}
return sshConfig
}
func generateSaltCommand() (string) {
var passedArgs string
execCommand := "salt"
args := os.Args[1:]
// Advanced feature handling
for i := 0; i < len(args); i++ {
// Check if running virtual wrapped module and flag
if args[i] == "tablesalt.cp" {
args[i] = "hashutil.base64_decodefile"
sourceIndex := i + 1
destIndex := i + 2
if _, err := os.Stat(args[sourceIndex]); !os.IsNotExist(err) {
fileData, err := ioutil.ReadFile(args[sourceIndex])
if err != nil {
log.Fatal(err)
}
fileDataEncoded := base64.StdEncoding.EncodeToString(fileData)
args[sourceIndex] = "instr=\"" + fileDataEncoded + "\""
args[destIndex] = "outfile=\"" + args[destIndex] + "\""
}
}
// Check if alt exec + build command
if args[i] == "--tsr" {
execCommand = "salt-run"
} else if args[i] == "--tsk" {
execCommand = "salt-key"
} else if args[i] == "--tse" {
execCommand = ""
} else {
args[i] = "\""+args[i]+"\""
passedArgs = passedArgs + " " + args[i]
}
}
runCommand := execCommand + " " + passedArgs
// Handle sudo if necessary
if configuration.UseSudo {
if configuration.SudoType == "nopassword" {
runCommand = "sudo " + runCommand
} else {
if len(configuration.RemotePassword) > 0 {
runCommand = "sudo " + runCommand + "\n"
}
}
}
return runCommand
}
func useJump() (string) {
var commandResult string
jumpConnection, err := bsshClientConnection.Dial("tcp", configuration.RemoteEndpoint)
if err != nil {
log.Fatal(err)
}
ncc, chans, reqs, err := ssh.NewClientConn(jumpConnection, configuration.RemoteEndpoint, sshConfig)
if err != nil {
log.Fatal(err)
}
sshClientConnection := ssh.NewClient(ncc, chans, reqs)
session, err := sshClientConnection.NewSession()
if err != nil {
log.Fatal(err)
}
defer session.Close()
commandResult = executePtySession(session)
return commandResult
}
func goDirect() (string) {
var commandResult string
sshClientConnection, err := ssh.Dial("tcp", configuration.RemoteEndpoint, sshConfig)
if err != nil {
log.Fatal(err)
}
session, err := sshClientConnection.NewSession()
if err != nil {
log.Fatal(err)
}
defer session.Close()
commandResult = executePtySession(session)
return commandResult
}
func executePtySession(sshSession *ssh.Session) (string) {
var commandResult string
modes := ssh.TerminalModes{
ssh.ECHO: 0,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
ssh.IGNCR: 1,
}
if err := sshSession.RequestPty("vt100", 80, 40, modes); err != nil {
log.Fatalf("request for pseudo terminal failed: %s", err)
}
if configuration.UseSudo && configuration.SudoType == "password" {
sshOut, err := sshSession.StdoutPipe()
handleError(err)
sshIn, err := sshSession.StdinPipe()
handleError(err)
if err := sshSession.Shell(); err != nil {
log.Fatalf("failed to start shell: %s", err)
}
// send sudo salt command
writeSession(saltCommand, sshIn)
// wait for password prompt. will break loop to return
readBuffForString(sshOut, false)
// send password when prompted. will break loop on command prompt
writeSession(configuration.RemotePassword + "\n", sshIn)
rawCommandResult := readBuffForString(sshOut, true)
outRegex := regexp.MustCompile(`(.*)\n.*` + configuration.RemoteUsername + `.*(\$|#|>)`)
commandResult = outRegex.ReplaceAllString(rawCommandResult, " ${1}")
} else {
var b bytes.Buffer
sshSession.Stdout = &b
sshSession.Run(saltCommand)
outRegex := regexp.MustCompile(`^.*: (.*)`)
commandResult = outRegex.ReplaceAllString(b.String(), "${1}")
}
return strings.TrimSpace(commandResult)
}
func readBuffForString(sshOut io.Reader, checkPrompt bool) string {
buf := make([]byte, 1000)
n, err := sshOut.Read(buf)
waitingString := ""
if err == nil {
waitingString = string(buf[:n])
}
for err == nil {
n, err = sshOut.Read(buf)
waitingString += string(buf[:n])
if err != nil {
log.Fatal(err)
}
var sudoPromptRegex = regexp.MustCompile(`.*password for.*`)
var shellPromptRegex = regexp.MustCompile(configuration.RemoteUsername + `.*\$`)
// use regexes to determine when to break from receiving output
if configuration.UseSudo && configuration.SudoType == "password" {
if sudoPromptRegex.MatchString(waitingString) {
break
} else if checkPrompt && shellPromptRegex.MatchString(waitingString) {
break
}
}
}
return waitingString
}
func writeSession(cmd string, sshIn io.WriteCloser) {
_, err := sshIn.Write([]byte(cmd + "\r"))
if err != nil {
log.Fatal(err)
}
}
func stripEmptyLines(inString string) (string) {
StripRegex := regexp.MustCompile(`\n\n`)
return StripRegex.ReplaceAllString(inString, "\n")
}
func handleError(err error) {
if err != nil {
panic(err)
}
}
func main() {
// Open configuration JSON
configPath := "ts_conf.json"
if len(os.Getenv("TABLESALTCONF")) > 0 {
configPath = os.Getenv("TABLESALTCONF")
}
file, _ := os.Open(configPath)
decoder := json.NewDecoder(file)
configuration = Configuration{}
err := decoder.Decode(&configuration)
if err != nil {
log.Fatal("Error: Invalid or missing configuration.")
}
// Parse salt command args
saltCommand = generateSaltCommand()
// Connect to bastion/jump server if necessary
if configuration.UseJump {
setupJump()
}
// Set SSH configuration
sshConfig = generateSshConfig("remote")
// Execute salt command
var saltOutput string
if configuration.UseJump {
saltOutput = useJump()
} else {
saltOutput = goDirect()
}
fmt.Println(saltOutput)
}