-
Notifications
You must be signed in to change notification settings - Fork 10
/
blackhole.py
executable file
·236 lines (209 loc) · 8.33 KB
/
blackhole.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
from gevent.server import StreamServer
from gevent import ssl
from gevent import socket
from datetime import datetime
from gevent.server import DatagramServer
import requests
import gevent
import os
import time
global ttl, httpData
ttl = 10
httpData = "HTTP/1.1 200 OK\nContent-Type: text/html; charset=utf-8\nContent-Length: 0\n\n"
#iptables -t nat -A PREROUTING -p tcp --dport 1:65535 -j REDIRECT --to-ports 5000
#iptables -t nat -A PREROUTING -p udp --dport 1:65535 -j REDIRECT --to-ports 5000
def grabHTTP(input, protocol, srcip, srcport, dport):
if "http://" in input:
for linechunk in input.split(" "):
fc = 1
try:
if "http://" == linechunk[:7]:
url = linechunk.split(';', 1)[0].split("&", 1)[0].split("|", 1)[0].replace("\r","").replace("\n","")
local_filename = "captures/binary/%s_%d_%s_%d_%d_%s" % (protocol, dport, srcip, srcport, fc, datetime.utcnow().isoformat().replace(":", "-").replace(".", "-"))
log = "[+] Downloading URL: %s Filename: %s Connection %s:%d Protocol: %s Time: %s\n" % (url, local_filename, srcip, srcport, protocol, datetime.utcnow().isoformat())
print log,
with open("logs.txt", "a") as f:
f.write(log)
f.close()
geturl = requests.get(url)
with open(local_filename, 'wb') as f:
for chunk in geturl.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
f.close()
except Exception as e:
print "[-] Error in grapHTTP: %s" % (e,)
def telnetparse(input):
if "echo" in input and "-e" in input:
for ino in input.split(" "):
if '"' in ino:
if "\\x" in ino:
ino = ino.replace('"','').replace("\\x", "").replace("\r", "").replace("\n","")
return ino.decode("hex")
elif "'" in ino:
if "\\x" in ino:
ino = ino.replace("'",'').replace("\\x", "").replace("\r", "").replace("\n","")
return ino.decode("hex")
elif "\\\\x" in ino:
ino = ino.replace("\\\\x", "").replace("\r", "").replace("\n","")
return ino.decode("hex")
elif "echo " == input[:5]:
toout = input[5:]
if '"' in toout:
ino = ino.replace('"','').replace("\r", "").replace("\n","")
elif "'" in toout:
ino = ino.replace("'",'').replace("\r", "").replace("\n","")
else:
ino = toout
return ino
return None
def checkHTTP(input):
if "HTTP/" in input and ( input[-4:] == "\r\n\r\n" or input[-2:] == "\n\n" ):
return True
return False
def recv(sock):
buf = ""
try:
buf = sock.recv(1)
except socket.timeout:
buf = ""
return buf
def handleTCP(socket, address):
global ttl, httpData
socket.settimeout(ttl)
httpFlag = False
ip, port = address
buf = ""
dport = 0
try:
dport = int(os.popen("grep \"src=%s\" /proc/net/nf_conntrack | grep tcp | grep \"sport=%d\"| tail -n 1" % (ip, port,)).read().split("dport=", 1)[1].split(" ", 1)[0])
except:
pass
if dport == 0:
try:
dport = int(os.popen("grep \"src=%s\" /proc/net/ip_conntrack | grep tcp | grep \"sport=%d\"| tail -n 1" % (ip, port,)).read().split("dport=", 1)[1].split(" ", 1)[0])
except:
pass
log = "[+] TCP Connection on Port: %d from %s:%d Time: %s\n" % (dport, ip, port, datetime.utcnow().isoformat())
print log,
with open("logs.txt", "a") as f:
f.write(log)
f.close()
try:
if dport in [443] or 443 == dport%1000:
context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
context.load_cert_chain(certfile="ssl.crt", keyfile="ssl.key")
context.options = ssl.OP_ALL
try:
sslsock = context.wrap_socket(socket, server_side=True)
while True:
buffer = sslsock.read()
if not buffer:
sslsock.send(httpData)
break
buf+=buffer
if checkHTTP(buf):
httpFlag = True
except Exception as e:
print "[-] Error: %s" % (e,)
finally:
try:
sslsock.close()
except:
pass
elif dport in [23]:
socket.send("login: ")
while not socket.closed:
buffer = recv(socket)
if not buffer:
socket.close()
break
elif buffer == "\n":
buf+= buffer
break
else:
buf+=buffer
if not socket.closed:
socket.send("Password: ")
while not socket.closed:
buffer = recv(socket)
if not buffer:
socket.close()
break
elif buffer == "\n":
buf+= buffer
socket.send("XM# ")
break
else:
buf+=buffer
while not socket.closed:
buffer = recv(socket)
if not buffer:
socket.close()
break
elif buffer == "\n":
tosend = telnetparse(buf.split("\n")[-1])
if tosend <> None:
socket.send(tosend)
socket.send("\n")
buf+= buffer
socket.send("XM# ")
else:
buf+= buffer
else:
while not socket.closed:
buffer = recv(socket)
if not buffer:
if httpFlag:
socket.send(httpData)
socket.close()
break
else:
buf+= buffer
if checkHTTP(buf):
httpFlag = True
except Exception as e:
print "[-] Error : %s " % (e,)
with open("captures/tcp/%d_%s_%d_%s.txt" % (dport, ip, port, datetime.utcnow().isoformat().replace(":", "-").replace(".", "-"),) , "wb") as file:
file.write(buf)
file.close()
grabHTTP(buf, "tcp", ip, port, dport)
class UDPServer(DatagramServer):
def handle(self, data, address):
global ttl
self.socket.settimeout(ttl)
ip, port = address
dport = 0
try:
dport = int(os.popen("grep \"src=%s\" /proc/net/nf_conntrack | grep udp | grep \"sport=%d\"| tail -n 1" % (ip, port,)).read().split("dport=", 1)[1].split(" ", 1)[0])
except:
pass
if dport == 0:
try:
dport = int(os.popen("grep \"src=%s\" /proc/net/ip_conntrack | grep udp | grep \"sport=%d\"| tail -n 1" % (ip, port,)).read().split("dport=", 1)[1].split(" ", 1)[0])
except:
pass
log = "[+] UDP Connection on Port: %d from %s:%d Time: %s\n" % (dport, ip, port, datetime.utcnow().isoformat())
self.socket.close()
print log,
with open("logs.txt", "a") as f:
f.write(log)
f.close()
with open("captures/udp/%d_%s_%d_%s.txt" % (dport, ip, port, datetime.utcnow().isoformat().replace(":", "-").replace(".", "-"),) , "wb") as file:
file.write(data)
file.close()
grabHTTP(data, "udp", ip, port, dport)
if not os.path.exists("captures"):
os.makedirs("captures")
if not os.path.exists("captures/tcp"):
os.makedirs("captures/tcp")
if not os.path.exists("captures/udp"):
os.makedirs("captures/udp")
if not os.path.exists("captures/binary"):
os.makedirs("captures/binary")
tcpserver = StreamServer(('', 5000), handleTCP)
udpserver = UDPServer(('', 5000))
try:
gevent.joinall( [gevent.spawn(tcpserver.serve_forever, () ), gevent.spawn(udpserver.serve_forever,() )] )
except KeyboardInterrupt as e:
pass