-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
526 lines (415 loc) · 13.2 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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
package main
import (
"context"
"errors"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net"
"os"
"os/signal"
"strconv"
"sync"
"time"
"golang.org/x/crypto/ssh"
"golang.org/x/sync/semaphore"
)
// PrivKeyLocation is the location of the private key to be used
// in the ssh server
const PrivKeyLocation string = "/home/ccerne/.ssh/id_rsa"
// RemoteUsername is the username of the remote server
const RemoteUsername string = "root"
// RemotePassword is the remote's password
const RemotePassword string = "root"
// RemotePort is the remote's port
const RemotePort uint16 = 22
// ServerAddr is the address and port to bind to
const ServerAddr string = "0.0.0.0:1337"
// Dbg is if we are in debug mode
const Dbg bool = true
// NumContainers to have available
// We don't ever need to spawn more than 255. That's crazy talk.
const NumContainers uint8 = 1
// KeepAliveTime specifies how long to keep the container alive
const KeepAliveTime string = "5m"
// PasswordAttemptData represents metadata about password attempts
type PasswordAttemptData struct {
usernamePasswords []UsernamePassword
numAttempts uint8
}
// UsernamePassword has a specific attempt information
type UsernamePassword struct {
username string
password string
}
// global channel of available containers
var availableContainers AvailableContainers
// AvailableContainers describes a list of the container names to be
// popped from.
type AvailableContainers struct {
containerEvent *semaphore.Weighted
containerNames []string
}
// Create mutex for the shared progrma data
var sharedProgramData sync.Mutex = sync.Mutex{}
// Is the program still running?
var programIsRunning bool = true
// Current password attempt data
var passwordData map[net.Addr]PasswordAttemptData
// Function to ensure that there will always be at least NumContainers
func spawnContainers() {
sharedProgramData.Lock()
for programIsRunning {
sharedProgramData.Unlock()
// Acquire a semaphore so that only the max number of containers at
// any given time is only AvailableContainers
availableContainers.containerEvent.Acquire(context.Background(), 1)
// Spawn container
str, err := CreateAndStartNewContainer()
if err != nil {
debugPrint(fmt.Sprintf("Error starting container: %v", err))
sharedProgramData.Lock()
continue
}
// Lock the list and append the container name
sharedProgramData.Lock()
availableContainers.containerNames = append(availableContainers.containerNames, str)
}
sharedProgramData.Unlock()
}
// Creates a connection to the remote SSH server
func dialSSHClient(containerID string) (*ssh.Client, string, error) {
startExistingContainer := false
if containerID != "" {
err := StartExistingContainer(containerID)
if err != nil {
debugPrint(fmt.Sprintf("Could not start existing container. Will start new: %v", err))
startExistingContainer = false
} else {
startExistingContainer = true
}
}
conn := ""
if startExistingContainer {
// Busy wait til the server is up
for {
// Busy wait til we're back in business
bool, err := IsSSHRunning(containerID)
if err != nil {
return nil, "", err
}
if bool {
break
}
}
conn = containerID
} else {
// Pop new connection, we know these are running
// TODO: We need to wait for a new container to come
// if the length of the array is 0 (data race)
sharedProgramData.Lock()
if len(availableContainers.containerNames) != 0 {
conn = availableContainers.containerNames[0]
availableContainers.containerNames = availableContainers.containerNames[1:]
availableContainers.containerEvent.Release(1)
} else {
return nil, "", errors.New("No container ready to be popped just yet")
}
sharedProgramData.Unlock()
}
// Get container IP
ip, err := GetContainerIP(conn)
if err != nil {
return nil, "", err
}
// Configure an ssh client
clientConfig := &ssh.ClientConfig{}
clientConfig.User = RemoteUsername
clientConfig.Auth = []ssh.AuthMethod{
ssh.Password(RemotePassword),
}
// Ignore host key verification
clientConfig.HostKeyCallback = ssh.InsecureIgnoreHostKey()
// Finally, redirect to docker container
client, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", ip, RemotePort), clientConfig)
return client, conn, err
}
// Serve a single SSH connection
func serveSSHConnection(connection net.Conn, sshConfig *ssh.ServerConfig) error {
serverConnection, serverChannels, serverRequests, sshErr := ssh.NewServerConn(connection, sshConfig)
// Split address
host, strPort, err := net.SplitHostPort(connection.RemoteAddr().String())
// Parse port as an integer
port, err := strconv.ParseUint(strPort, 10, 16)
if err != nil {
debugPrint(fmt.Sprintf("Could not parse port as an integer: %v", err))
return err
}
// Get geographical data
geoData := GetGeoData(host)
sharedProgramData.Lock()
// Get the password data for that connection
pwdData, ok := passwordData[connection.RemoteAddr()]
// Remove old password data
if ok {
delete(passwordData, connection.RemoteAddr())
} else {
pwdData = PasswordAttemptData{
numAttempts: 0,
usernamePasswords: []UsernamePassword{},
}
}
sharedProgramData.Unlock()
if sshErr != nil {
debugPrint(fmt.Sprintf("Could not initiate SSH handshake: %v", sshErr))
// Create SQL connection
sqlConn := NewSQLHoneypotDBConnection(host, uint16(port), geoData, pwdData, "")
sqlConn.Close()
return err
}
// Close connection when function returns
defer serverConnection.Close()
if err != nil {
debugPrint(fmt.Sprintf("Could not split host and port: %v", err))
return err
}
// See if connection already exists
existsContID, err := GetContainerIDFromConnection(host)
if err != nil {
debugPrint(fmt.Sprintf("Could not get container ID: %v", err))
return err
}
// Proxy the SSH request by dialing a new ssh client
clientConnection, containerID, err := dialSSHClient(existsContID)
if err != nil {
debugPrint(fmt.Sprintf("Could not dial SSH client to %s: %v", containerID, err))
return err
}
// Stop the container after n seconds
// TODO: Check to see if the duration is valid before spawning any connection threads
dur, _ := time.ParseDuration(KeepAliveTime)
timer := time.AfterFunc(dur, func() {
StopContainer(containerID)
})
defer timer.Stop()
// Create SQL connection
sqlConn := NewSQLHoneypotDBConnection(host, uint16(port), geoData, pwdData, containerID)
// Write debug
debugPrint(fmt.Sprintf("SSH connection authenticated for %s. Writing to database with ID %d.", host, sqlConn.ConnID))
// Close client connection on exit
defer clientConnection.Close()
defer sqlConn.Close()
defer func() {
debugPrint("Closing connection and stopping container.")
// TODO: One IP address can be connected in multiple SSH clients
// We should only stop the container if all of them disconnect.
// Dunno how to check this now, we need to maintain state better
err = StopContainer(containerID)
if err != nil {
debugPrint(fmt.Sprintf("Error closing container: %v", err))
}
}()
go ssh.DiscardRequests(serverRequests)
// Iterate through all the channels (is there just one?)
for newChannel := range serverChannels {
// Create client connection
clientChannel, clientRequests, err := clientConnection.OpenChannel(newChannel.ChannelType(), newChannel.ExtraData())
if err != nil {
debugPrint(fmt.Sprintf("Could not accept client channel: %v", err))
return err
}
serverChannel, serverRequests, err := newChannel.Accept()
if err != nil {
debugPrint(fmt.Sprintf("Could not accept channel: %v", err))
return err
}
// Threads that basically get requests
go func() {
threadLoop:
for {
var req *ssh.Request = nil
var dst ssh.Channel = nil
select {
case req = <-serverRequests:
dst = clientChannel
case req = <-clientRequests:
dst = serverChannel
}
// Resolve segmentation fault for unexpected closed connection
if dst == nil || req == nil {
debugPrint("Client closed connection unexpectedly")
return
}
b, err := dst.SendRequest(req.Type, req.WantReply, req.Payload)
if err != nil {
debugPrint(fmt.Sprintf("Request sending did not work %v", err))
return
}
if req.WantReply {
req.Reply(b, nil)
}
// TODO: Implement req.Type exec, pty-req, etc.
// exec would be pretty important for logging
if req.Type == "exit-status" {
break threadLoop
}
}
// Finally, close the connections
serverChannel.Close()
clientChannel.Close()
// We should kill the docker container after x seconds?
}()
var wrappedServerChannel io.ReadCloser = serverChannel
var wrappedClientChannel io.ReadCloser = NewSQLReadCloser(clientChannel, sqlConn)
go io.Copy(clientChannel, wrappedServerChannel)
go io.Copy(serverChannel, wrappedClientChannel)
defer wrappedServerChannel.Close()
defer wrappedClientChannel.Close()
}
return nil
}
func main() {
// Read private key file
privateKeyBytes, err := ioutil.ReadFile(PrivKeyLocation)
// If error, exit
if err != nil {
panic("Failed to read private key file.")
}
// Turn bytes into a real private key
privateKey, err := ssh.ParsePrivateKey(privateKeyBytes)
// If error, exit
if err != nil {
panic("Failed to parse private key file.")
}
// Create a map for all the clients
// TODO: is there a data race here? need to check if passwords is thread safe.
// Also probably want to find a better way to do this. Maybe create a list of
// activate connections here.
passwordData = make(map[net.Addr]PasswordAttemptData)
// Create a channel list for the new containers
// availableContainers = make(chan string, NumContainers)
availableContainers = AvailableContainers{
containerEvent: semaphore.NewWeighted(int64(NumContainers)),
containerNames: []string{},
}
// Create the initial containers
go spawnContainers()
// SigINT handling
// This cleanly stops the docker containers
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt)
go func() {
for range c {
sharedProgramData.Lock()
programIsRunning = false
sharedProgramData.Unlock()
// Pull connections from the channel and kill them. At
// this point, we shouldn't have any more additions, only
// removals.
innerLoop:
for {
sharedProgramData.Lock()
// Get container to remove and stop it
conn := availableContainers.containerNames[0]
availableContainers.containerNames = availableContainers.containerNames[1:]
StopContainer(conn)
// If we popped the last one off, break
if len(availableContainers.containerNames) == 0 {
sharedProgramData.Unlock()
break innerLoop
}
// Unlock the mutex
sharedProgramData.Unlock()
}
// TODO: Clean up actively running connections.
debugPrint("Exiting honeypot")
// Exit
os.Exit(0)
}
}()
// Configure TOR IP addresses
err = SetupExitNodeMap()
// Configure ssh server
config := &ssh.ServerConfig{
PasswordCallback: func(connMeta ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
// Lock password data
sharedProgramData.Lock()
// Unlock when the program returns
defer sharedProgramData.Unlock()
debugPrint(fmt.Sprintf("SSH password attempt from %s.", connMeta.RemoteAddr()))
debugPrint(fmt.Sprintf("Username: %s", connMeta.User()))
debugPrint(fmt.Sprintf("Password: %s", string(password)))
// See if we let them in
succeed := rand.Intn(3) == 0
// If we've not seen this connection before
if _, ok := passwordData[connMeta.RemoteAddr()]; !ok {
attemptsList := []UsernamePassword{}
attemptsList = append(attemptsList, UsernamePassword{
username: connMeta.User(),
password: string(password),
})
passwordData[connMeta.RemoteAddr()] = PasswordAttemptData{
usernamePasswords: attemptsList,
numAttempts: 1,
}
if succeed {
return nil, nil
}
} else if passwordData[connMeta.RemoteAddr()].numAttempts == 2 {
// Get password list and append to it
pwdList := passwordData[connMeta.RemoteAddr()].usernamePasswords
pwdList = append(pwdList, UsernamePassword{
username: connMeta.User(),
password: string(password),
})
// append password attempt
passwordData[connMeta.RemoteAddr()] = PasswordAttemptData{
usernamePasswords: pwdList,
numAttempts: 3,
}
// Success
return nil, nil
} else {
// Get password list and append to it
pwdList := passwordData[connMeta.RemoteAddr()].usernamePasswords
pwdList = append(pwdList, UsernamePassword{
username: connMeta.User(),
password: string(password),
})
// append password attempt
passwordData[connMeta.RemoteAddr()] = PasswordAttemptData{
usernamePasswords: pwdList,
numAttempts: passwordData[connMeta.RemoteAddr()].numAttempts + 1,
}
// we succeed
if succeed {
return nil, nil
}
}
return nil, errors.New("Incorrect SSH password")
},
}
// Add id_rsa to the ssh config
config.AddHostKey(privateKey)
// Now spin up the server
listener, err := net.Listen("tcp", ServerAddr)
defer listener.Close()
if err != nil {
panic(fmt.Sprintf("net.Listen failed: %v", err))
}
// Loop infinitaly
for {
currentConnection, err := listener.Accept()
if err != nil {
debugPrint(fmt.Sprintf("listener.Accept failed: %v", err))
continue
}
go serveSSHConnection(currentConnection, config)
}
}
func debugPrint(str string) {
if Dbg {
fmt.Printf("[DBG] %s\n", str)
}
}