Skip to content

Commit c4b1d16

Browse files
authored
Final Commit before presentation at DefCon 26!
1 parent 997b384 commit c4b1d16

File tree

11 files changed

+6409
-0
lines changed

11 files changed

+6409
-0
lines changed

Defcon26/config.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
API_KEY = 'SHODAN_API_KEY'
2+
3+
static_ip = "127.0.0.1"
4+
listening_port = 2303
5+
6+
VirusTotalAPIKey = "VIRUS_TOTAL_API_KEY"
7+
8+
# TWILIO Configuration Items
9+
# account_sid = "TWILIO SID"
10+
# auth_token = "TWILIO AUTH_TOKEN"
11+
# RECV NUMBER
12+
# TWILIO_NUMBER

Defcon26/db_test.py

Lines changed: 170 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,170 @@
1+
import requests
2+
from config import *
3+
import sqlite3
4+
from flask import Flask, render_template, request
5+
app = Flask(__name__)
6+
7+
# Edit database file to reflect the right name/location of the netflow DB
8+
conn = sqlite3.connect('netflow2.db')
9+
conn.row_factory = sqlite3.Row
10+
#conn.row_factory = sqlite3.Row
11+
c = conn.cursor()
12+
print("Deleting rows...")
13+
# Blacklist considers Google DNS malicious.. cuz.. bad guys use it...
14+
# Remove it from our database..
15+
c.execute("DELETE FROM shodan WHERE dest=?", ("8.8.8.8",))
16+
conn.commit()
17+
18+
# Prints all of the junk in the shodan table.. for debugging.
19+
for i in c.execute("SELECT * FROM shodan"):
20+
for j in i:
21+
pass
22+
#print(j)
23+
c.execute("SELECT name FROM sqlite_master WHERE type='table';")
24+
#print(c.fetchone())
25+
numSamples = 0
26+
'''
27+
# Converts
28+
def dict_factory(cursor, row):
29+
d = {}
30+
for idx, col in enumerate(cursor.description):
31+
d[col[0]] = row[idx]
32+
return d
33+
'''
34+
35+
portNumber = "*"
36+
def getData():
37+
global result1
38+
conn = sqlite3.connect('netflow2.db')
39+
#conn.row_factory = sqlite3.Row
40+
c = conn.cursor()
41+
#print(numSamples)
42+
c.execute("SELECT COUNT(*) FROM (SELECT DISTINCT dest, src FROM shodan LIMIT ?)", (numSamples,))
43+
unique = c.fetchall()
44+
for row in unique:
45+
print("Total unique IP Addresses: " + str(row[0]))
46+
unique_IPs = str(row[0])
47+
bytes = 0
48+
#c.execute("SELECT * FROM traffic WHERE src!=? ORDER BY time DESC LIMIT ?", (home, numSamples))
49+
c.execute("SELECT * FROM shodan ORDER BY time DESC LIMIT ?", (numSamples,))
50+
#print(result1)
51+
result1 = [i for i in c.fetchall()]
52+
#for i in result1:
53+
#print(i)
54+
#print(result1)
55+
print("Outbound: " + humansize(bytes))
56+
outbound = humansize(bytes)
57+
bytes = 0
58+
print(portNumber)
59+
for row in c.execute("SELECT * FROM shodan WHERE dest!=? AND dport=? ORDER BY time DESC LIMIT ?", (home, portNumber, numSamples)):
60+
totalbytes = int(row[3]) * int(row[2])
61+
bytes = bytes + totalbytes
62+
result2 = c.fetchall()
63+
#print(result2)
64+
result2 = {item[6]: item for item in result2}
65+
66+
print("Inbound: " + humansize(bytes))
67+
inbound = humansize(bytes)
68+
#print(inbound.split()[0])
69+
total = float(inbound.split()[0]) + float(outbound.split()[0])
70+
#print(str(total))
71+
return unique_IPs, outbound.split()[0], outbound.split()[1], \
72+
inbound.split()[0], inbound.split()[1], str(total)
73+
74+
try:
75+
home = requests.get('http://ipquail.com/ip').text.strip("\n\r")
76+
print(home)
77+
except:
78+
home = static_ip
79+
80+
suffixes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB']
81+
82+
# Sweet function that converts bytes into readable form
83+
def humansize(nbytes):
84+
i = 0
85+
while nbytes >= 1024 and i < len(suffixes)-1:
86+
nbytes /= 1024.
87+
i += 1
88+
f = ('%.2f' % nbytes).rstrip('0').rstrip('.')
89+
return '%s %s' % (f, suffixes[i])
90+
91+
# DO MATH.
92+
def sqlStats():
93+
#for row in c.execute("SELECT COUNT (DISTINCT src) FROM traffic"):
94+
for row in c.execute("SELECT COUNT(*) FROM (SELECT DISTINCT dest, src FROM shodan)"):
95+
print("Total unique IP Addresses: " + str(row[0]))
96+
unique_IPs = str(row[0])
97+
bytes = 0
98+
99+
for row in c.execute("SELECT * FROM shodan WHERE src=?", (home,)):
100+
totalbytes = int(row[3]) * int(row[2])
101+
bytes = bytes + totalbytes
102+
print("Outbound: " + humansize(bytes))
103+
outbound = humansize(bytes)
104+
bytes = 0
105+
for row in c.execute("SELECT * FROM shodan WHERE src!=?", (home,)):
106+
totalbytes = int(row[3]) * int(row[2])
107+
bytes = bytes + totalbytes
108+
print("Inbound: " + humansize(bytes))
109+
inbound = humansize(bytes)
110+
return unique_IPs, outbound, inbound
111+
112+
#sqlStats()
113+
114+
def maxRowsTable():
115+
for row in c.execute("SELECT COUNT(time) FROM shodan"):
116+
maxNumberRows=row[0]
117+
return maxNumberRows
118+
119+
## Flask Web Page Handling
120+
@app.route("/")
121+
def index():
122+
unique_IPs, outbound, outlabel, inbound, inlabel, total = getData()
123+
iframe = 'iframe.html'
124+
templateData = {
125+
'unique' : unique_IPs,
126+
'outbound' : outbound,
127+
'inbound' : inbound,
128+
'total' : total,
129+
'outlabel' : outlabel,
130+
'inlabel' : inlabel,
131+
'result1': result1,
132+
'iframe' : iframe
133+
}
134+
return render_template('index.html', **templateData)
135+
136+
@app.route('/', methods=['POST'])
137+
def formPost():
138+
global numSamples
139+
global portNumber
140+
global IPAddress
141+
142+
try:
143+
portNumber = int(request.form['portNumber'])
144+
except:
145+
portNumber = 8888
146+
try:
147+
numSamples = int(request.form['numSamples'])
148+
except:
149+
numSamples = "1000000000"
150+
try:
151+
IPAddress = str(request.form['IPAddress'])
152+
except:
153+
IPAddress = "*"
154+
numMaxSamples = maxRowsTable()
155+
if (int(numSamples) > int(numMaxSamples)):
156+
numSamples = (int(numMaxSamples) -1)
157+
unique_IPs, outbound, outlabel, inbound, inlabel, total = getData()
158+
templateData = {
159+
'unique': unique_IPs,
160+
'outbound': outbound,
161+
'inbound': inbound,
162+
'total': total,
163+
'outlabel': outlabel,
164+
'inlabel': inlabel,
165+
'result1': result1
166+
}
167+
return render_template('index.html', **templateData)
168+
169+
if __name__ == "__main__":
170+
app.run(host="0.0.0.0", port=80, debug=False)

Defcon26/netflow_collectorDB.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import socket, struct # Raw socket access
2+
import time # Time..
3+
from config import listening_port # uses config file to save configurable data
4+
import sqlite3 # SQLlite database interaction
5+
from socket import inet_ntoa # For parsing packets
6+
import requests # Makes web requests to retrieve WAN IP address
7+
8+
# Retrieve WAN IP Address for later parsing
9+
try:
10+
home = requests.get('http://ipquail.com/ip').text.strip("\n\r")
11+
print(home)
12+
with open("ip.txt", "w") as text_file:
13+
print(home, file=text_file)
14+
except:
15+
file = open("ip.txt","r")
16+
home = file.readline()
17+
print('Using old IP of ' + str(home))
18+
19+
WAN_IP = home
20+
21+
conn = sqlite3.connect('netflow.db')
22+
conn.execute("CREATE TABLE IF NOT EXISTS traffic (src text, sport int, packet int, \
23+
bytes int, dest text, dport int , time text)")
24+
25+
SIZE_OF_HEADER = 24
26+
SIZE_OF_RECORD = 48
27+
28+
print("Collector started at: ", time.strftime("%H:%M:%S %d-%m-%Y"))
29+
30+
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
31+
s.bind(('0.0.0.0', listening_port))
32+
current_day = time.strftime("%d-%b-%Y")
33+
34+
35+
while True:
36+
buf, addr = s.recvfrom(1500)
37+
38+
(version, count) = struct.unpack('!HH',buf[0:4])
39+
if version != 5:
40+
print("Not NetFlow v5!")
41+
continue
42+
43+
uptime = socket.ntohl(struct.unpack('I',buf[4:8])[0])
44+
epochseconds = socket.ntohl(struct.unpack('I',buf[8:12])[0])
45+
46+
for i in range(0, count):
47+
try:
48+
base = SIZE_OF_HEADER+(i*SIZE_OF_RECORD)
49+
50+
data = struct.unpack('!IIIIHH',buf[base+16:base+36])
51+
nfdata = {}
52+
nfdata['saddr'] = inet_ntoa(buf[base + 0:base + 4])
53+
nfdata['daddr'] = inet_ntoa(buf[base + 4:base + 8])
54+
nfdata['pcount'] = data[0]
55+
nfdata['bcount'] = data[1]
56+
nfdata['stime'] = data[2]
57+
nfdata['etime'] = data[3]
58+
nfdata['sport'] = data[4]
59+
nfdata['dport'] = data[5]
60+
nfdata['protocol'] = inet_ntoa(buf[base + 39])
61+
except:
62+
continue
63+
#print(nfdata)
64+
65+
66+
current_day = time.strftime("%H:%M:%S %d-%m-%Y")
67+
#print(current_day)
68+
sourceIP = nfdata['saddr']
69+
destIP = nfdata['daddr']
70+
71+
if sourceIP == WAN_IP:
72+
sourceIP = 'HOME'
73+
else:
74+
destIP = 'HOME'
75+
print("%s:%s %s bytes -> %s:%s" % (sourceIP, nfdata['sport'],
76+
nfdata['bcount'], destIP,
77+
nfdata['dport']))
78+
79+
conn.execute("INSERT INTO traffic VALUES (?, ?, ?, ?, ?, ?, ?)", (sourceIP, nfdata['sport'],
80+
nfdata['pcount'], nfdata['bcount'],
81+
destIP, nfdata['dport'],
82+
current_day))
83+
conn.commit()
84+
85+
#print("db write..")
86+
#print("Wrote data to netflowData-" + current_day + ".csv at " + time.strftime("%H:%M:%S %d-%m-%Y"))

0 commit comments

Comments
 (0)