-
Notifications
You must be signed in to change notification settings - Fork 56
/
decept.py
executable file
·2241 lines (1796 loc) · 83.4 KB
/
decept.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
#------------------------------------------------------------------
# Author: Lilith Wyatt <(^,^)>
#------------------------------------------------------------------
# This is the main proxy, Decept Created with portability in mind,
# so you can set it and forget it, only uses as standard python libraries
# as possible.
#
# Can dump .fuzzer files too if you have mutiny_fuzzing_framework
# in an adjecent directory (i.e. ../mutiny_fuzzing_framework || ../mutiny)
#
# Initial idea/base from tcp proxy.py (Black Hat Python by Justin Seitz)
#
# Feature List:
# - SSL/IPv6/Unix/abstract/dtls socket support
# - Pcap dumping (sorta hacky)
# - fuzzer file dumping for Mutiny
# - L3 captures/proxying
# - L2 captures/proxying
#------------------------------------------------------------------
# Copyright (c) 2015-2017 by Cisco Systems, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# 3. Neither the name of the Cisco Systems, Inc. nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#------------------------------------------------------------------
import ssl
import sys
import socket
import struct
import select
import multiprocessing
try:
# windows
import fcntl
except:
pass
try:
# dtls
from OpenSSL import SSL
from OpenSSL import _util
except:
pass
from ctypes import *
from re import match
from time import time,sleep
from datetime import datetime
from os.path import join,isfile,abspath
from platform import system
from os import mkdir,getcwd,remove
try:
sys.path.append(abspath(join(__file__,"../../mutiny_fuzzing_framework")))
import backend.fuzzerdata as mutiny
except ImportError:
try:
sys.path.append(abspath(join(__file__, "../../mutiny-fuzzer")))
import backend.fuzzerdata as mutiny
except ImportError:
pass
DEBUGGING = False
if '-d' in sys.argv:
DEBUGGING = True
# minor hack to get decept to run on osx
if "darwin" in system().lower():
socket.AF_PACKET = -1
##########
#! <(^.^)>
class DeceptProxy():
def __init__(self,lhost,lport,rhost,rport,local_end_type,remote_end_type,receive_first=False,
local_cert=None,local_key=None):
self.lhost = lhost
self.lport = lport
self.rhost = rhost
self.rport = rport
self.srcport = 0 #for UDP when we need src port to send back to locally
self.receive_first = receive_first
self.local_end_type = local_end_type
self.remote_end_type = remote_end_type
self.conn = True
if "dtls" in local_end_type:
output("Local DTLS sockets not supported yet, sorry (^_^);;;")
sys.exit()
self.output_lock = multiprocessing.Lock()
if "udp" in local_end_type or "dtls" in local_end_type:
self.conn = False
self.protocol_blueprints = None
self.pkt_count = 0
self.max_conns = 5
self.verbose = True
# don't exit if no data (streaming)
self.dont_kill = False
# except if we get past expected_resp_count ^_^
self.expected_resp_count = -1
self.udp_port_range = None
#! verify this
if "\\x00" in self.lhost:
self.lhost = "\x00%s" % self.lhost
if "\\x00" in self.rhost:
self.rhost = "\x00%s" % self.rhost
self.rbind_addr = "0.0.0.0"
self.rbind_port = 0
# ssl options for those who care
#killswitch for closing sockets
self.killswitch = multiprocessing.Event()
# Timeout for sockets
self.timeout = 1
# Max amount of data to send per packet for
# TCP-based protocols, inbound or outbound.
self.l4_MTU = 30000
# .fuzzer Options
self.fuzz_file = ""
self.fuzzerData = ""
# assorted options
self.L3_raw = False
self.dumpraw = ''
self.l2_mtu = 1500
self.l2_filter = ""
self.l2_forward = False
self.linterface = ""
self.rinterface = ""
self.lmac = ""
self.rmac = ""
self.pcap = ""
self.pcap_file = ""
self.pcapfd = None
self.pps = False
self.snaplen = 65535
self.pcap_interface = "eth0"
self.mon_flag = None
self.tapmode = False
self.hostconf_dict = {}
self.poison_file = ""
self.poison_int = "eth0"
self.local_certfile=local_cert
self.local_keyfile=local_key
# these will get overwritten with --rkey/--rcert options
# if both are provided
self.remote_certfile=local_cert
self.remote_keyfile=local_key
self.remote_verify=""
self.remote_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
self.remote_context.verify_mode = ssl.CERT_NONE
self.remote_context.check_hostname = False
# on successful import, these will be the imported
# functions "inbound_hook()" and "outbound_hook()"
self.inbound_hook = None
self.outbound_hook = None
# Load SSL cert if creating local SSL prox
if self.local_end_type == "ssl":
try:
self.server_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
if self.local_keyfile:
self.server_context.load_cert_chain(certfile=self.local_certfile,keyfile=self.local_keyfile)
else:
self.server_context.load_cert_chain(certfile=self.local_certfile)
except Exception as e:
output("[x.x] Please generate keys before attempting to proxy ssl",RED)
output("[-_-] Protip: openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -nodes",CYAN)
output("[>_>] %s"%e,RED)
sys.exit(0)
elif self.local_end_type == "dtls":
# DTLS made sorta possible by smarter people than I, thank you Mr. Concolato ^_^;
# https://stackoverflow.com/questions/27383054/python-importerror-usr-local-lib-python2-7-lib-dynload-io-so-undefined-symb
# it's a hack and I can only get one side to work. Definiately a 'todo'.
try:
DTLSv1_server_method = 7
SSL.Context._methods[DTLSv1_server_method] = _util.lib.DTLSv1_server_method
except:
output("[x.x] Unable to import OpenSSL for DTLS!",RED)
output("[-_-] Please install `apt-get install python-openssl` or `pip install PyOpenSSL`",RED)
try:
self.server_context = SSL.Context(DTLSv1_server_method)
if self.local_keyfile:
self.server_context.use_privatekey_file(self.local_keyfile)
if self.local_certfile:
self.server_context.use_certificate_file(self.local_certfile)
except Exception as e:
output("[x.x] Please generate keys before attempting to proxy DTLS",RED)
output("[-_-] Protip: openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -nodes",CYAN)
output("[>_>] %s"%e,RED)
sys.exit(0)
if self.remote_end_type == "dtls":
DTLSv1_client_method = 8
SSL.Context._methods[DTLSv1_client_method] = _util.lib.DTLSv1_client_method
self.remote_context = SSL.Context(DTLSv1_client_method)
###########################################################
##End Decept() __init__()##################################
###########################################################
def shutdown(self):
if self.local_end_type in ConnectionBased:
server_kill = self.socket_plinko(self.lhost,self.local_end_type)
if server_kill.type != socket.AF_UNIX:
server_kill.connect((self.lhost,self.lport))
server_kill.close()
elif "unix" in self.local_end_type:
try:
remove(self.lhost)
except:
output("[?.?] Unable to delete Unix Socket: %s"%self.lhost,YELLOW)
output("[^.^] Thanks for using Decept!")
sys.exit()
def get_bytes(self,sock):
ret = ""
retip = ""
retport = -1
sock.settimeout(self.timeout)
try:
while True:
tmp = ""
if self.conn:
tmp = sock.recv(65535)
else:
# necessary for connectionless
if self.local_end_type == "udp":
ret_struct = sock.recvfrom(65535)
try:
tmp,(_,tmpport) = ret_struct
except ValueError:
# ipv6 recvfrom gives more data
tmp,(_,tmpport,_,_) = ret_struct
if tmpport != self.lport and tmpport != self.rport and not self.srcport:
self.lport = tmpport
self.lhost = _
elif self.local_end_type == "dtls":
tmp,(retip,retport) = sock.recvfrom(65535)
if len(tmp):
ret+=tmp
else:
break
except Exception as e:
#output(str(e),YELLOW)
pass
if retip and (retport >= 0):
return (ret,retip,retport)
return ret
# Takes the host (1.1.2.1, FE80::1, ab:bc:cd:ef:ab:ea)
# and endpoint type (tcp,ssl,unix,udp)
# and returns the appropriate socket
def socket_plinko(self,host,endpoint):
s_fam = socket.AF_INET
s_proto = None
if "stdin" in endpoint:
return sys.stdin
if "stdout" in endpoint:
return sys.stdout
if match(r'\d{1,3}(\.\d{1,3}){3}',host):
s_fam = socket.AF_INET
elif match(r'([0-9A-Fa-f]{2}:){5}[0-9A-Fa-f]{2}',host):
if "darwin" in system().lower():
output("[x.x] RAW packet functionality in OSX not supported.")
sys.exit()
# Automatically raw.
if endpoint == "passive":
# when we aren't bridging two interfaces
# 0x0300 => promiscuous mode
ret_socket = socket.socket(socket.AF_PACKET,socket.SOCK_RAW,0x0300)
#endpoint == "bridge"
else:
ret_socket = socket.socket(socket.AF_PACKET,socket.SOCK_RAW)
return ret_socket
elif match(r'([0-9A-Fa-f]{0,4}:?)(:[0-9A-Fa-f]{1,4}:?)+',host) and host.find("::") == host.rfind("::"):
#print repr(host)
s_fam = socket.AF_INET6
else:
s_fam = socket.AF_UNIX
if endpoint in ConnectionBased:
ret_socket = socket.socket(s_fam,socket.SOCK_STREAM)
ret_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# we don't ssl wrap here since we need to know whether or not
# the socket is server side or client side ~ <(^.^<)
if endpoint == "L3_raw":
ret_socket.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)
return ret_socket
elif "udp" in endpoint or "dtls" in endpoint:
ret_socket = socket.socket(s_fam,socket.SOCK_DGRAM)
ret_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
if self.L3_raw:
ret_socket.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)
return ret_socket
else:
# Valid endpoint choices include anything in ValidEndpoints
s_type = socket.SOCK_RAW
if endpoint in PROTO:
# e.g. if proto == ospf, s_proto => 89
s_proto = PROTO[endpoint]
elif endpoint == "raw":
s_proto = socket.IPPROTO_RAW
elif endpoint == "stdin" or endpoint == "stdout":
return
else:
s_proto = int(endpoint)
ret_socket = socket.socket(s_fam,s_type,s_proto)
# Crafting L2/L3 is hard, yo.
if self.L3_raw:
ret_socket.setsockopt(socket.IPPROTO_IP,socket.IP_HDRINCL,1)
return ret_socket
def server_socket_init(self):
if "stdin" in self.local_end_type:
return
try:
if "windows" in system().lower() or "cygwin" in system().lower():
self.server_socket.bind((self.lhost,self.lport))
elif self.server_socket.family == socket.AF_PACKET:
# case normal L2 socket
if self.server_socket.proto == 0:
return
# case promiscuous socket
if self.server_socket.proto == 0x300:
return
elif self.server_socket.family == socket.AF_UNIX:
self.server_socket.bind((self.lhost))
elif "darwin" not in system().lower() and self.server_socket.family == socket.AF_PACKET:
self.server_socket.bind((self.lhost,0))
else:
self.server_socket.bind((self.lhost,self.lport))
output("[*.*] Listening on %s:%s" % (self.lhost,str(self.lport)),CYAN)
except Exception as e:
output(str(e),YELLOW)
output("[x.x] Unable to bind to %s:%s" % (self.lhost,str(self.lport)) ,RED)
sys.exit(0)
output("[$.$] local:%s|remote:%s" % (self.local_end_type,self.remote_end_type), GREEN)
if self.local_end_type in ConnectionBased:
try:
self.server_socket.listen(self.max_conns)
except Exception as e:
output(e)
def server_loop(self):
# make sure our ssl context is set appropriately
if self.remote_verify and self.remote_end_type == "ssl":
self.remote_context.verify_mode = ssl.CERT_REQUIRED
# should prob add an option for cer file...
#self.remote_context.load_verify_locations("cert_chain.crt")
self.remote_context.check_hostname = True
#ciphers = "ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305"
#self.remote_context.set_ciphers(ciphers)
# prep for dumping raw datagrams
if self.dumpraw:
try:
mkdir(self.dumpraw)
except Exception as e:
pass
try:
sub_folder = str(datetime.now()).replace(" ","_")
sub_folder = sub_folder.replace(":","_")
self.dumpraw = join(self.dumpraw,sub_folder)
mkdir(self.dumpraw)
except Exception as e:
print e
pass
# If we're attempting to write to a pcap, shouldn't it be required to be L2?
# # Perhaps make a raw promisc regardless? for when no tcpdump/tshark?
if self.pcap:
self.pcapdir = join(getcwd(),"pcap")
try:
mkdir(self.pcapdir)
except:
pass
if not isfile(join(self.pcapdir,self.pcap)):
# if it doesn't exist, write the headers/etc
import tempfile
try:
self.pcapfd = open(join(self.pcapdir,self.pcap),"wb",0)
self.pcapfd.write((pcap_global_hdr().get_byte_array()))
except Exception as e:
# why isn't this behaving as the docs describe?
# not returnning an open fd, just a tuple of (fd, name)
# perhaps I am just dumb
output(e,YELLOW)
self.pcap = tempfile.mkstemp(suffix=".pcap",dir=self.pcapdir)
output("[i.i] Couldnt tmp pcap file %s instead!"%(self.pcap[1]),CYAN)
self.pcapfd = open(self.pcap[1],"wb",0)
self.pcapfd.write((pcap_global_hdr().get_byte_array()))
else:
# if it does exist, just append packets
self.pcapfd = open(join(self.pcapdir,self.pcap),"ab",0)
#### Set up a promiscuous monitor socket such that we can actually get more than raw data.
#### ETH_P_IP = 0x0800
#### ETH_P_ALL = 0x0300
self.pcap_sock = socket.socket(socket.AF_PACKET,socket.SOCK_RAW,0x0300)
### Set up our EBPF prog #### def create_ebpf_filter(ip,port,proto=""):
self.ebpf,self.b = create_ebpf_filter(self.lhost,self.lport)
#print "[^_^] ebpf: %s\n%s" % (repr(self.ebpf), self.b)
# SO_ATTACH_FILTER == 26
self.pcap_sock.setsockopt(socket.SOL_SOCKET, 26, self.ebpf)
self.pcap_sock.bind((self.pcap_interface,0))
self.mon_flag = multiprocessing.Event()
mon_thread = multiprocessing.Process(target = self.monitor_loop,
args = (self.pcap_sock,
self.pcapfd,
self.mon_flag
))
mon_thread.start()
if self.l2_filter:
self.l2_filter = ''.join(chr(int(x,16)) for x in filter(None,l2_filter.split("x")))
self.server_socket = self.socket_plinko(self.lhost,self.local_end_type)
# Alrighty, here's where we start to distinguish
# socket Family/type/protocol
self.server_socket_init()
if self.tapmode:
'''
# since we can't do AF_PACKET with windows, we only go down to L3.
dummy_frame = "\x00"*0xC #dst/src mac
dummy_frame += "\x80\x00" #proto IP
'''
self.dummy_packet = "\x45" #ver,headerlen
self.dummy_packet+= "\x00" # DSC
self.dummy_packet+= "L3TOTESHEADER" # Total len, will fixup
self.dummy_packet+= "??" # ID field, doesnt' matter.
self.dummy_packet+= "\x00\x00" # flags.
self.dummy_packet+= "\x80" #ttl.
if self.remote_end_type == "ssl" or self.remote_end_type == "tcp":
self.dummy_packet+= "\x06" #proto => tcp
elif self.remote_end_type == "udp":
self.dummy_packet+= "\x17" #proto => udp
else:
# if you need something else, add it yourself.
self.dummy_packet+= "\x01" # proto => ICMP
self.dummy_packet+= "\x00\x00" # header checksum, don't care.
l_ip = ''.join(chr(int(octet)) for octet in self.lhost.split("."))
r_ip = ''.join(chr(int(octet)) for octet in self.rhost.split("."))
self.inbound_dummy = self.dummy_packet + l_ip + r_ip
self.outbound_dummy = self.dummy_packet + r_ip + l_ip
self.inbound_dummy += struct.pack(">H",self.rport)
self.inbound_dummy += struct.pack(">H",self.lport)
self.outbound_dummy += struct.pack(">H",self.lport)
self.outbound_dummy += struct.pack(">H",self.rport)
self.l4_dummy = ""
if self.remote_end_type == "ssl" or self.remote_end_type == "tcp":
self.l4_dummy+="\x00\x00\x00\x00" # seq num
self.l4_dummy+="\x00\x00\x00\x00" # ack num
self.l4_dummy+="\x50" # tcp header len
self.l4_dummy+="\x18" # we only really care about [psh,ack]
self.l4_dummy+="\x01\x00" # window size => 256
self.l4_dummy+="\x00\x00" # checksum, w/e.
self.l4_dummy+="\x00\x00" # urgent pointer
elif self.remote_end_type == "udp":
l4_dummy+="L4TOTESHEADER"
l4_dummy+="\x00\x00"# checksum
else:
pass
self.inbound_dummy+=self.l4_dummy
self.outbound_dummy+=self.l4_dummy
'''
try:
'''
# No AF_PACKET support in windows.
#self.tapsock = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_RAW)
self.tapsock = socket.socket(socket.AF_INET,socket.SOCK_RAW,socket.IPPROTO_RAW)
self.tapsock.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
'''
except Exception:
# Perms yo.
output("[x.x] Could create a raw interface. Are you running as root?",RED)
'''
if self.fuzz_file:
self.fuzzerData = mutiny.FuzzerData()
if self.poison_file:
poison_thread = multiprocessing.Process(target = self.arp_poisoner,
args = (self.poison_file,
self.poison_int,
self.killswitch))
poison_thread.start()
# attempt to parse config file, if any. Should be located in 'rhost'
# will continue if not found.
try:
confbuf = ""
conflist = []
with open(self.rhost,"r") as f:
confbuf = f.read()
for line in filter(None,confbuf.split("\n")):
if line[0] != "#":
conflist.append(line)
if len(conflist) > 0:
for entry in conflist:
try:
name,ip = entry.split("|")
if len(name) and len(ip):
self.hostconf_dict[name] = ip
output("[!.!] Added %s | %s" % (name,ip),CYAN)
except Exception as e:
print e
pass
except IOError as e:
# no such file
pass
except Exception as e:
print e
pass
#! Todo, no loop for UDP...
while True:
if self.local_end_type in ConnectionBased:
csock,addr = self.server_socket.accept()
#print out conn info
if addr:
ts = datetime.now().strftime("%H:%M:%S.%f")
output("[>.>] %s Received Connection from %s" % (ts,str(addr)),GREEN,self.output_lock)
else:
output("[>.>] %s Received Connection from UnixSocket"%(ts),GREEN,self.output_lock)
if "windows" in system().lower() or "cygwin" in system().lower():
import threading
proxy_thread = threading.Thread(target = self.proxy_loop,
args = (csock,
self.rhost,
self.rport,
addr,
self.output_lock))
else:
proxy_thread = multiprocessing.Process(target = self.proxy_loop,
args = (csock,
self.rhost,
self.rport,
addr,
self.output_lock))
proxy_thread.start()
csock = None
addr = None
elif self.local_end_type == "udp" or self.local_end_type == "dtls":
self.proxy_loop(self.server_socket,self.rhost,self.rport,"",self.output_lock)
self.exit_triggers()
return
elif self.server_socket == sys.stdin:
self.proxy_loop(sys.stdin,self.rhost,self.rport,("stdin",0),"",self.output_lock)
elif self.server_socket.family == socket.AF_PACKET:
output("[>.>] L2 ready: %s:%s <=> %s:%s" % (str(self.lhost),str(self.lport),str(self.rhost),str(self.rport)),YELLOW)
self.raw_proxy_loop(self.rhost,self.rport)
if self.pcapfd:
try:
self.mon_flag.set()
except:
pass
def proxy_loop(self,local_socket,rhost,rport,cli_addr="",plock=""):
self.thread_id = multiprocessing.current_process().name.replace("Process","session")
# use for passing data between inbound and outbound handlers.
self.userdata = []
# used with hostconf_dict
initial_buff = ""
# Attempt to parse as hostname.
if len(self.hostconf_dict) <= 0:
try:
rhost = socket.gethostbyname(rhost)
except Exception as e:
if "Temporary failure in name resolution" in e or "Name or service" in e:
output(str(e),YELLOW)
output("[x.x] Unable to resolve DNS name: %s" % (rhost), RED, plock)
local_socket.close()
sys.exit()
else:
# See if we have a hostconf entry for rhost
schro_local = local_socket
hostname = ""
if self.local_end_type == "ssl":
try:
schro_local = self.server_context.wrap_socket(local_socket, server_side=True)
output("[^.^] Local ssl wrap successful",GREEN,plock)
except ssl.SSLError as e:
output("[x.x] Unable to wrap local SSL socket.",YELLOW, plock)
output(str(e),RED, plock)
schro_local.close()
sys.exit()
try:
initial_buff = self.get_bytes(schro_local)
#output(initial_buff,YELLOW, plock)
for line in initial_buff.split("\n"):
if "Host:" in line:
hostname = line.split(" ")[1].rstrip()
except Exception as e:
if len(initial_buff) > 0:
output("[x.x] No 'Host:' header from local socket with hostconf!",RED, plock)
output(initial_buff, plock)
else:
output("[x.x] Empty Message",RED, plock)
output(str(e),RED, plock)
output(initial_buff,YELLOW, plock)
schro_local.close()
sys.exit()
if len(hostname) == 0:
output("[x.x] Empty Message",RED, plock)
output(initial_buff, plock)
schro_local.close()
sys.exit()
try:
rhost = self.hostconf_dict[hostname]
except:
output("[x.x] No entry for %s in hostconf!"%hostname,RED, plock)
output(initial_buff, plock)
self.rhost = hostname
output("[-.0] Connecting to %s (%s:%d)"%(rhost,hostname,rport),ORANGE,plock)
remote_socket = self.socket_plinko(rhost,self.remote_end_type)
if (self.rbind_addr != "0.0.0.0") or (self.rbind_port > 0):
output("[!.!] Binding Rsock to %s:%d"%(self.rbind_addr,self.rbind_port),CYAN, plock)
remote_socket.bind((self.rbind_addr,self.rbind_port))
# schro == schroedinger
# simultaneuously ssl wrapped and not until afterwards
schro_remote = remote_socket
if not len(initial_buff):
schro_local = local_socket
try:
if self.remote_end_type in ConnectionBased:
if (self.local_end_type == "udp" or self.local_end_type == "dtls") and not self.receive_first:
# we need to wait for data before we connect.
pass
elif "windows" in system().lower() or "cygwin" in system().lower():
remote_socket.connect((rhost,rport))
elif remote_socket.family == socket.AF_UNIX:
remote_socket.connect((rhost))
elif remote_socket.family == socket.AF_INET6:
remote_socket.connect((rhost,rport,0,0))
# to avoid dumb lack of socket.AF_PACKET in osx
elif "darwin" not in system().lower() and remote_socket.family != socket.AF_PACKET:
remote_socket.connect((rhost,rport))
else:
remote_socket.connect((rhost,rport))
except Exception as e:
output(str(e),YELLOW, plock)
output("[x.x] Unable to connect to %s,%s" % (rhost,str(rport)), RED, plock)
sys.exit()
if self.local_end_type == "ssl" and len(initial_buff) == 0:
try:
schro_local = self.server_context.wrap_socket(local_socket, server_side=True)
except ssl.SSLError as e:
output("[x.x] Unable to wrap local SSL socket.",YELLOW, plock)
output(str(e),RED, plock)
schro_local.close()
sys.exit()
elif self.local_end_type == "dtls" and len(initial_buff) == 0:
try:
schro_local = SSL.Connection(self.server_context,local_socket)
except Exception as e:
output("[x.x] Unable to wrap local DTLS socket.",YELLOW, plock)
output(str(e),RED, plock)
schro_local.close()
sys.exit()
# need to wait for udp...
if self.remote_end_type == "ssl" and self.local_end_type != "udp":
try:
try:
self.remote_context.load_cert_chain(certfile=self.remote_certfile,keyfile=self.remote_keyfile)
#output("[!-!] Using %s and %s!"%(self.remote_certfile,self.remote_keyfile),CYAN, plock)
except:
try:
self.remote_context.load_cert_chain(certfile=self.remote_certfile)
#output("[!-!] Using %s"%(self.remote_certfile,self.remote_keyfile),CYAN, plock)
except:
output("[x.x] Unable to do SSL remote, where yo' keys at?",YELLOW, plock)
output("[!-!] Using cert %s and key %s!"%(self.remote_certfile,self.remote_keyfile),CYAN, plock)
sys.exit()
if self.remote_verify:
try:
schro_remote = self.remote_context.wrap_socket(remote_socket,server_hostname=self.remote_verify)
output("[^_^] Wrapped remote!")
except Exception as e:
output("[x.x] Unable to verify remote host as '%s' "%self.remote_verify,YELLOW, plock)
output(str(e),RED, plock)
schro_remote.close()
sys.exit()
else:
schro_remote = self.remote_context.wrap_socket(remote_socket)
except ssl.SSLError as e:
output("[x.x] Unable to do SSL remote. Did you send a non-SSL request?",YELLOW, plock)
output(str(e),RED, plock)
schro_remote.close()
sys.exit()
except Exception as e:
output("[x.x] Assorted error, yo",YELLOW, plock)
output(str(e),RED, plock)
remote_socket.close()
sys.exit()
#!Todo: add DTLS verification
if self.remote_end_type == "dtls" and self.local_end_type != "udp":
try:
schro_remote = SSL.Connection(self.remote_context,remote_socket)
schro_remote.set_connect_state()
schro_remote.connect((rhost,rport))
schro_remote.do_handshake()
except Exception as e:
output("[x.x] DTLS error, yo",YELLOW, plock)
output(str(e),RED, plock)
remote_socket.close()
sys.exit()
# we can't really know where to send the packet yet if UDP.
# maybe save it till we recv?
if self.receive_first and self.local_end_type in ConnectionBased:
remote_buffer = get_bytes(schro_remote)
remote_buffer = self.inbound_handler(remote_buffer,rhost,self.lhost)
if self.verbose:
hexdump(remote_buffer,CYAN)
self.pkt_count+=1
#if data to send to local, do so
if len(remote_buffer):
ts = datetime.now().strftime("%H:%M:%S.%f")
output("[<.<] %s Sending %d bytes inbound (%s:%d)." % (ts,len(remote_buffer),self.lhost,self.lport),ORANGE, plock)
if self.local_end_type in ConnectionBased:
self.buffered_send(schro_local,remote_buffer)
else:
self.buffered_sendto(schro_local,remote_buffer,(self.lhost,self.lport))
elif not self.receive_first and (self.local_end_type == "udp" or self.local_end_type == "dtls"):
# [>_>] port range is going to override schro_local, cuz I'm lazy
if self.udp_port_range:
schro_local = [schro_local]
schro_local_range = validateNumberRange(self.udp_port_range,True) # flatten out number range into list of integers
output("[!-!] Attempting to bind %d UDP ports : %s" %(len(schro_local_range),self.udp_port_range),GREEN, plock)
for port in schro_local_range:
tmp = self.socket_plinko(self.lhost,self.local_end_type)
# shoulda implimented server_init better to take a socket, eh.
try:
tmp.bind((self.lhost,port))
tmp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
schro_local.append(tmp)
except:
output("[x.x] Unable to bind UDP %s:%d."%(self.lhost,port),YELLOW, plock)
while True:
readable,__,__ = select.select(schro_local,[],schro_local,self.timeout)
if len(readable) > 0:
break
else: #udp && !udp_port_range
while True:
readable,__,__ = select.select([schro_local],[],[schro_local],self.timeout)
if len(readable) > 0:
break
if self.remote_end_type != "udp":
remote_socket.connect((rhost,rport))
if self.remote_end_type == "ssl":
try:
if self.remote_certfile:
self.remote_context.load_cert_chain(certfile=self.remote_certfile,keyfile=self.remote_keyfile)
if self.remote_verify:
schro_remote = self.remote_context.wrap_socket(remote_socket,server_hostname=self.remote_verify)
else:
schro_remote = self.remote_context.wrap_socket(remote_socket)
#remote_cert = schro_remote.getpeercert()
#print remote_cert
except ssl.SSLError as e:
output("[x.x] Unable to do SSL remote. Did you send a non-SSL request?",YELLOW, plock)
output(str(e),RED, plock)
schro_remote.close()
sys.exit()
if self.remote_end_type == "dtls":
try:
schro_remote = SSL.Connection(self.remote_context,remote_socket)
schro_remote.set_connect_state()
schro_remote.connect((rhost,rport))
schro_remote.do_handshake()
except Exception as e:
output("[x.x] DTLS error, yo",YELLOW, plock)
output(str(e),RED)
remote_socket.close()
sys.exit()
buf = ""
# don't know if port range or not
active_udp = None
schro_list = []
resp_count = 0
# for DTLS
remote_sock = None
remote_host = None
remote_port = -1
handshake_flag = False
try:
schro_list = schro_local[:]
schro_list.append(schro_remote)
active_udp = schro_local[0]
except:
schro_list = [schro_local, schro_remote]
if len(initial_buff):
byte_count = len(initial_buff)
buf = self.outbound_handler(initial_buff,self.lhost,self.rhost)
if byte_count > 0 and self.verbose:
if byte_count < 0x2000:
hexdump(buf,CYAN)
else:
output("[!_!] Truncated Message len %d!"%byte_count, plock)
if len(buf):
self.pkt_count+=1
ts = datetime.now().strftime("%H:%M:%S.%f")
if self.remote_end_type in ConnectionBased:
self.buffered_send(schro_remote,buf)
output("[o.o] %s Sent %d bytes to remote (%s:%d->%s:%d)\n" % (ts, len(buf),cli_addr[0],cli_addr[1],self.rhost,self.rport),CYAN, plock)
elif self.remote_end_type == "stdout" or self.local_end_type == "stdin":
sys.stdout.write(buf)
output("[o.o] %s Sent %d bytes to remote\n" % (ts, len(buf)),YELLOW)
else:
self.buffered_sendto(schro_remote,buf,(self.rhost,self.rport))
output("[o.o] %s Sent %d bytes to remote (%s:%d)\n" % (ts, len(buf),self.rhost,self.rport),CYAN)
try:
while True:
if not len(initial_buff):
byte_count = 0
else:
initial_buff = ""
if self.killswitch.is_set():