-
Notifications
You must be signed in to change notification settings - Fork 3
/
views.py
1996 lines (1718 loc) · 80.9 KB
/
views.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
# Standard Library Imports
import os
import re
import csv
import sys
import math
import json
import socket
import random
import urllib
import urllib2
import commands
import datetime
import threading
import subprocess
import collections
from PIL import Image
from StringIO import StringIO
from time import sleep
from urlparse import urlparse
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot
from pylab import figure, axes, pie, title
from matplotlib.backends.backend_agg import FigureCanvasAgg
import mpl_toolkits.axisartist as AA
import numpy as np
import matplotlib.mlab as mlab
import sklearn
from sklearn import svm
from sklearn.svm import SVC
from sklearn.svm import SVR
from sklearn.cross_validation import StratifiedKFold
from sklearn.feature_selection import RFECV
from sklearn.datasets import make_classification
from sklearn.metrics import zero_one_loss
from sklearn import datasets, linear_model
from sklearn import datasets, svm
from sklearn.feature_selection import SelectPercentile, f_classif
import pylab as pl
# django Imports
from django.views.decorators.csrf import csrf_exempt
from django.template import *
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
from django.template import RequestContext
from django.http import *
from django.core.urlresolvers import reverse
from django.core.exceptions import *
import models
import forms
import settings
# from runserver import printOpenFiles
# Tornado Imports
import tornado.web
import tornado.websocket
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application, asynchronous, RequestHandler
from multiprocessing.pool import ThreadPool
# from tornado.options import options, define, parse_command_line
# Third Party Imports
# from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
# from matplotlib.figure import Figure
from HTMLParser import HTMLParser
def read_and_close_stdout(self):
op = self.stdout.read()
try:
self.stdout.close()
except:
pass
try:
self.stdin.close()
except:
pass
try:
self.stderr.close()
except:
pass
return op
setattr(subprocess.Popen, 'read_and_close_stdout', read_and_close_stdout)
def open_subprocess(cmd):
return subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
def apply(fns, values):
assert len(fns) == len(values)
return list(fns[i](values[i]) for i in xrange(len(fns)))
def meanvariance(l):
s2 = 0
s = 0
l = map(float, l)
for e in l:
s += e
s2 += e * e
N = len(l)
return (s/N, math.sqrt((s2 - (s*s)/N)/N))
def ip_to_int(ip):
try:
parts = map(int, ip.split("."))
x = (parts[0] << 24) + (parts[1] << 16) + (parts[2] << 8) + (parts[3])
return x
except:
return -1
def int_to_ip(i):
parts = []
parts.insert(0, i % (1 << 8))
i //= (1 << 8)
parts.insert(0, i % (1 << 8))
i //= (1 << 8)
parts.insert(0, i % (1 << 8))
i //= (1 << 8)
parts.insert(0, i % (1 << 8))
i //= (1 << 8)
return ".".join(map(str, parts))
def whois(ip):
p = subprocess.Popen(" ".join(["whois", ip]), stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
op = p.read_and_close_stdout()
if op.find("Unknown AS number or IP network") == 0:
print "UNKNOWN"
h = urllib.urlopen("http://whois.net/ip-address-lookup/%s" % ip).read()
class MYHTMLParser(HTMLParser):
pre = False
def handle_starttag(self, tag, attrs):
if tag == "pre" and dict(attrs)['class'] == "bodyMed":
self.pre = True
def handle_endtag(self, tag):
self.pre = False
def handle_data(self, data):
if self.pre:
self.data = data
# print h
par = MYHTMLParser()
par.feed(h)
op = par.data
result = {}
for line in op.split("\n"):
if len(line.strip()) == 0:
continue
if line[0] in ["#", "%", "["]:
continue
if ":" not in line:
continue
k, v = line.split(":", 1)
result[k.strip()] = v.strip()
if len(result.keys()) == 0:
# Another format
for line in op.split("\n"):
if len(line.strip()) == 0:
continue
if line[0] in ["#", "%", "["]:
continue
else:
b1, b2 = line.rfind("("), line.rfind(")")
result['role'] = line[:b1].strip()
result['inetnum'] = line[b2 + 1:].strip()
return result
def filebasename(fn):
return os.path.splitext(os.path.basename(fn))[0]
def homepage(request):
mydict = {}
return render_to_response('wperf_index.html', mydict)
def nextsite(request):
last = models.Website.objects.count() - 1
rand_index = random.randint(0, last)
chosenOne = models.Website.objects.all()[rand_index]
return HttpResponse(chosenOne.address)
@csrf_exempt
def addobservation(request, pk):
if True or request.method == 'POST':
datas = request.POST['data']
# print "addobservation"
data = eval(datas)
# print data
for i in ['0', '1']:
data_i = (data[i])
for key in data_i:
# print "key=", key
w = models.Website()
w.user_agent = int(i)
# print "key=", key
w.testId = models.Test.objects.get(pk=int(pk))
# print "key=", key
w.url = key.replace('\/', '/')
# print "key=", key
data_i_key = eval(data_i[key])
w.pageLoadTime = data_i_key['pageLoadTime']
# print "key=", key
w.rating = data_i_key['rating']
w.signalStrength = data_i_key['signalStrength']
# print "key=", key
w.progressTimeMap = data_i_key['partialPageLoadTimes']
# print "key=", key
# print "Saving ", key
w.save()
# print "Saved ", key
return HttpResponse("")
@csrf_exempt
def addobservation_adcomparison(request, pk):
# print "hello"
if True or request.method == 'POST':
datas = request.POST['data']
# print "addobservation"
data = eval(datas)
# print data
for i in ['0', '1']:
data_i = (data[i])
for key in data_i:
# print "key=", key
w = models.Website_AdComparison()
w.ads_blocked = int(i)
# print "key=", key
w.testId = models.Test.objects.get(pk=int(pk))
# print "key=", key
w.url = key.replace('\/', '/')
# print "key=", key
data_i_key = eval(data_i[key])
w.pageLoadTime = data_i_key['pageLoadTime']
# print "key=", key
w.rating = data_i_key['rating']
w.signalStrength = data_i_key['signalStrength']
# print "key=", key
w.progressTimeMap = data_i_key['partialPageLoadTimes']
# print "key=", key
# print "Saving ", key
w.save()
# print "Saved ", key
return HttpResponse("")
@csrf_exempt
def getnewobsid(request):
if request.method == 'POST':
w = models.Test()
w.tester = request.POST['tester']
w.gsmCellId = request.POST['gsmCellId']
w.operator = request.POST['operator']
w.networkType = request.POST['networkType']
w.save()
return HttpResponse("id:" + str(w.pk))
def test(request):
mydict = {}
return render_to_response('test.html', mydict)
def listfiles(request):
form = forms.UploadForm()
return render_to_response(
'list.html',
{'uploadedfiles': models.UploadedFile.objects.all(), 'form': form},
context_instance=RequestContext(request)
)
def upload(request):
if request.method == 'POST':
form = forms.UploadForm(request.POST, request.FILES)
if form.is_valid():
newfile = models.UploadedFile(filetype="None", uploadedfile=request.FILES['uploadfile'], shortfilename=request.FILES['uploadfile'].name, processed=False)
newfile.save()
s = newfile.uploadedfile.name
s = s[s.rfind('/') + 1:]
newfile.shortfilename = s
newfile.save()
return HttpResponseRedirect(reverse(listfiles))
else:
form = forms.UploadForm()
return render_to_response(
'list.html',
{'uploadedfiles': [], 'form': form},
context_instance=RequestContext(request)
)
def pcap_list(request):
form = forms.UploadForm()
return render_to_response('pcap_list.html', {'pcap_files': models.PcapFile.objects.all(), 'form': form}, context_instance=RequestContext(request))
def pcap_upload(request):
if request.method == 'POST':
form = forms.UploadForm(request.POST, request.FILES)
if form.is_valid():
newpcap = models.PcapFile(uploadedfile=request.FILES['uploadfile'], shortfilename=request.FILES['uploadfile'].name)
newpcap.save()
s = newpcap.uploadedfile.name
s = s[s.rfind('/') + 1:]
newpcap.shortfilename = s
newpcap.save()
return HttpResponseRedirect(reverse(pcap_list))
else:
form = forms.UploadForm()
return render_to_response('obs_pcap_list.html', {'pcap_files': [], 'form': form}, context_instance=RequestContext(request))
def obs_pcap_list(request):
form = forms.UploadForm()
return render_to_response('obs_pcap_list.html', {'pcap_files': models.ObsPcapFile.objects.all(), 'form': form}, context_instance=RequestContext(request))
def obs_pcap_upload(request):
if request.method == 'POST':
form = forms.UploadForm(request.POST, request.FILES)
if form.is_valid():
newpcap = models.ObsPcapFile(uploadedfile=request.FILES['uploadfile'], shortfilename=request.FILES['uploadfile'].name)
newpcap.save()
s = newpcap.uploadedfile.name
s = s[s.rfind('/') + 1:]
newpcap.shortfilename = s
newpcap.save()
return HttpResponseRedirect(reverse(obs_pcap_list))
else:
form = forms.UploadForm()
return render_to_response('obs_pcap_list.html', {'pcap_files': [], 'form': form}, context_instance=RequestContext(request))
def ads_vs_no_ads_pcap_list(request):
form = forms.UploadForm()
return render_to_response('ads_vs_no_ads_pcap_list.html', {'pcap_files': models.AdsVsNoAdsPcapFile.objects.all(), 'form': form}, context_instance=RequestContext(request))
def ads_vs_no_ads_pcap_upload(request):
if request.method == 'POST':
form = forms.UploadForm(request.POST, request.FILES)
if form.is_valid():
newpcap = models.AdsVsNoAdsPcapFile(uploadedfile=request.FILES['uploadfile'], shortfilename=request.FILES['uploadfile'].name)
newpcap.save()
s = newpcap.uploadedfile.name
s = s[s.rfind('/') + 1:]
newpcap.shortfilename = s
newpcap.save()
return HttpResponseRedirect(reverse(ads_vs_no_ads_pcap_list))
else:
form = forms.UploadForm()
return render_to_response('ads_vs_no_ads_pcap_list.html', {'pcap_files': [], 'form': form}, context_instance=RequestContext(request))
class DNS(object):
def __init__(self, dns_id):
self.dns_id = dns_id
self.queries = []
self.queryhosts = []
self.responses = []
def getDNSPackets(filename, dnspath=None):
if not dnspath:
a, b = os.path.splitext(filename)
dnspath = a + "_dns.txt"
if not os.path.exists(dnspath):
print "Writing dns file"
cmd1 = """tshark -n -R "dns" -r %s""" % (filename)
p = subprocess.Popen(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
with open(dnspath, 'w') as f:
r = p.read_and_close_stdout()
p.stdout.close()
p.stderr.close()
f.write(r)
print "Done writing dns file"
dns_list = {}
ip_to_dns_id = {}
with open(dnspath) as f:
for line in f.read().split("\n"):
if(len(line.strip()) == 0):
continue
m = re.match(r'\s*(\d+)\s+(.*?)\s+(\d+\.\d+\.\d+\.\d+)\s+->\s+(\d+\.\d+\.\d+\.\d+)\s+DNS\s+\d+\s+Standard\s+query\s+(response\s+)?(.*?)\s+(.*)', line.strip())
# print m.groups()
# return
if m:
packet_no, packetTime, fromIp, toIp, whetherResponse, dns_id, dns_string = m.groups()
dns_list.setdefault(dns_id, DNS(dns_id))
if whetherResponse:
dns_list[dns_id].responses.append((packetTime, fromIp, toIp, dns_string))
m1 = re.findall(r'A\s+(\d+\.\d+\.\d+\.\d+)', dns_string)
for ip in m1:
ip_to_dns_id.setdefault(ip, [])
ip_to_dns_id[ip].append(dns_id)
else:
dns_list[dns_id].queries.append((packetTime, fromIp, toIp, dns_string))
if dns_string[:2] == "A ":
dns_list[dns_id].queryhosts.append(dns_string[2:].strip())
return (dns_list, ip_to_dns_id)
def makeStats(filename, csvpath, bandwidth_path):
print "makeStats: Beginning"
a, b = os.path.splitext(filename)
csvpath = a + ".csv"
all_streams_csvpath = a + "_all_streams.csv"
csv2_path = a + "_ip.csv"
cmd1 = "tshark -n -r %s -T fields -e tcp.stream" % (filename)
cmd1_ip = "tshark -r %s -q -z conv,ip" % (filename)
p = subprocess.Popen(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
p_ip = subprocess.Popen(cmd1_ip, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
streams = sorted(list(set(map(int, filter(lambda x: len(x) > 0, map(lambda x: x.strip(), p.read_and_close_stdout().split('\n')))))))
if not os.path.exists(csvpath) or not os.path.exists(all_streams_csvpath):
print "makeStats: Writing stream csvs"
with open(csvpath, "wb") as csvfile:
with open(all_streams_csvpath, "wb") as all_streams_csvfile:
writer = csv.writer(csvfile)
all_streams_writer = csv.writer(all_streams_csvfile)
stream_processes = {}
print "makeStats: Writing stream csvs"
for s in streams:
cmd2 = """tshark -r %s -q -z conv,tcp,tcp.stream==%d""" % (filename, s)
cmd3 = """tshark -n -R "tcp.stream==%d && http.request==1" -r %s -T fields -e http.request.full_uri -e frame.time_relative """ % (s, filename)
q1 = subprocess.Popen(cmd2, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
q2 = subprocess.Popen(cmd3, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stream_processes[s] = [q1, q2]
# for s in streams:
sys.stdout.write("\rmakeStats: Writing stream csvs (%04d/%04d)" % (s, streams[-1]))
sys.stdout.flush()
q1, q2 = stream_processes[s]
l = q1.read_and_close_stdout().split("\n")[5]
m = re.match(r'\s*(\d+\.\d+\.\d+\.\d+):.*?\s+<->\s+(\d+\.\d+\.\d+\.\d+):.*?\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)\s+(.*?)\s+(.*?)\s+', l + " ") # trailing space so that last \s+ can act as delimiter
ip1, ip2, transfer, startTime, duration = m.groups(0)
objects = map(lambda x: x, filter(lambda x: len(x) > 0, map(lambda x: x.strip(), q2.read_and_close_stdout().strip().split('\n'))))
objs = []
num_objects = len(objects)
for o in objects:
url, start_time = o.split()
objs.append("'%s'::%s" % (url, start_time))
urls = ", ".join(objs)
url = "%d objects" % num_objects
if num_objects > 0:
url += " with urls like: %s..." % objects[0][:50]
writer.writerow([ip1, ip2, transfer, startTime, duration, url])
all_streams_writer.writerow([s, ip1, ip2, transfer, startTime, duration, num_objects, urls])
if not os.path.exists(csv2_path):
print "makeStats: Writing ip csvs"
with open(csv2_path, 'wb') as csv2_file:
writer = csv.writer(csv2_file)
for line in p_ip.read_and_close_stdout().split("\n")[5:]:
m = re.match(r'\s*(\d+\.\d+\.\d+\.\d+).*?\s+<->\s+(\d+\.\d+\.\d+\.\d+).*?\s+\d+\s+\d+\s+\d+\s+\d+\s+\d+\s+(\d+)\s+(.*?)\s+(.*?)\s+?', line)
if not m:
continue
ip1, ip2, transfer, startTime, duration = m.groups(0)
writer.writerow([ip1, ip2, transfer, startTime, duration])
print "makeStats: Finished"
def makeBandwidthStats(filename, csvpath=None, bandwidth_path=None, bandwidth_uplink_path=None, bandwidth_downlink_path=None, retransmit_path=None, myip=None, debug=True):
if debug:
print "makeBandwidthStats: Beginning"
if debug:
print "makeBandwidthStats: Bandwidth"
if bandwidth_path and not os.path.exists(bandwidth_path):
cmd4 = """tshark -r %s -q -z io,stat,0.5""" % (filename)
q4 = subprocess.Popen(cmd4, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
with open(bandwidth_path, 'w') as f:
f.write(q4.read_and_close_stdout())
if debug:
print "makeBandwidthStats: Uplink Bandwidth"
if bandwidth_uplink_path and not os.path.exists(bandwidth_uplink_path):
cmd5 = """tshark -r %s -q -z io,stat,0.5,ip.src==%s""" % (filename, myip) # uplink
q5 = subprocess.Popen(cmd5, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
with open(bandwidth_uplink_path, 'w') as f:
f.write(q5.read_and_close_stdout())
if debug:
print "makeBandwidthStats: Downlink Bandwidth"
if bandwidth_downlink_path and not os.path.exists(bandwidth_downlink_path):
cmd6 = """tshark -r %s -q -z io,stat,0.5,ip.dst==%s""" % (filename, myip) # downlink
q6 = subprocess.Popen(cmd6, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
with open(bandwidth_downlink_path, 'w') as f:
f.write(q6.read_and_close_stdout())
if debug:
print "makeBandwidthStats: Retransmissions"
if retransmit_path and not os.path.exists(retransmit_path):
cmd7 = """tshark -r %s -R "tcp.analysis.retransmission" -T fields -e frame.time_relative""" % (filename)
q7 = subprocess.Popen(cmd7, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
with open(retransmit_path, 'w') as f:
f.write(q7.read_and_close_stdout())
if debug:
print "makeBandwidthStats: Finished"
def intersect(l1, l2):
return [x for x in l1 if x in l2] if l2 is not None else l1
def other(x, l):
return l[1] if x == l[0] else l[0]
def get_org_from_ip(ip):
try:
i = ip_to_int(ip)
orgs = models.Organization.objects.filter(lower__lt=i, higher__gt=i)
if len(orgs) == 1:
return orgs[0]
except Exception as e:
print e
s = ip
# print "trying whois"
whois_result = whois(s)
# print "whois_result:", whois_result
ip_range, org_name = None, None
try:
ip_range = whois_result['NetRange']
org_name = whois_result['OrgName']
except KeyError:
try:
ip_range = whois_result['inetnum']
org_name = whois_result['role']
except KeyError:
try:
org_name = whois_result['person']
except KeyError:
print "Unknown Organization for ip : %s" % ip
ip_range = "Unknown"
org_name = "Unknown"
org = None
if not ip_range or ip_range == "Unknown":
try:
ip_range = whois_result['route']
if "/" in ip_range:
a, b = ip_range.split("/")
a_int = ip_to_int(a)
# begin = a_int & (1<<(32-int(b)))
begin = a_int
end = a_int | ((1 << (32 - int(b))) - 1)
print int_to_ip(begin), int_to_ip(end)
ip_range = "%s - %s" % (int_to_ip(begin), int_to_ip(end))
except:
pass
if ip_range and org_name:
# print "ip_range and org_name found"
hyphen = ip_range.find('-')
lower, higher = ip_range[:hyphen].strip(), ip_range[hyphen + 1:].strip()
lower_int, higher_int = map(ip_to_int, (lower, higher))
org, org_created = models.Organization.objects.get_or_create(name=org_name, ip_range=ip_range, lower=lower_int, higher=higher_int)
if org_created:
org.save()
# print "org:", org
return org
def summarize_har(harpath):
with open(harpath) as harfile:
hardata = json.loads(harfile.read()[12: -2])
totalSize = 0
contentTypes = {}
for entry in hardata['log']['entries']:
# print entry
size = int(entry['response']['bodySize'])
totalSize += size
mT = entry['response']['content']['mimeType']
# print size, mT
contentTypes.setdefault(mT, [0, 0])
contentTypes[mT][0] += 1
contentTypes[mT][1] += size
categories_2 = {}
for ct in contentTypes:
cat_name = "other"
for n in ['html', 'image', 'css', 'xml', 'json', 'flash', 'javascript', 'json']:
if n in ct:
cat_name = n
break
if cat_name == "other":
print ct
categories_2.setdefault(cat_name, [0, 0])
categories_2[cat_name][0] += contentTypes[ct][0]
categories_2[cat_name][1] += contentTypes[ct][1]
for ct in categories_2:
categories_2[ct][1] /= 1024.0
categories_2[ct][1] = round(categories_2[ct][1], 3)
return totalSize, contentTypes, categories_2
def parse_bandwidth_data(bandwidth_path, threshold, retransmission_times): # Threshold -- the speed that generally is available on mobile network.
bandwidth_data = []
with open(bandwidth_path) as f:
lines = f.read().split("\n")[7:]
for line in lines:
match = re.match(r'\|\s+(.*?)\s+<>\s+(.*?)\s+\|\s+(.*?)\s+\|\s+(.*?)\s+\|', line)
if match:
startTime, endTime, frames, bytes = match.groups(0)
endTime = (float(endTime))
startTime = (float(startTime))
no_retransmissions = len(filter(lambda x: True if float(startTime) <= x < float(endTime) else False, retransmission_times))
bandwidth_data.append((startTime, endTime, int(frames), int(bytes), (float(bytes) / (float(endTime) - float(startTime)) / 1000.0), threshold, no_retransmissions*10))
return bandwidth_data
def makeRttStats(filename, rtt_csv_path):
if not os.path.exists(rtt_csv_path):
cmd_rtt = """tshark -r %s -R "tcp.analysis.ack_rtt" -T fields -e frame.number -e frame.time_relative -e tcp.analysis.ack_rtt -E separator=, -E quote=n -E occurrence=f""" % (filename)
p_rtt = subprocess.Popen(cmd_rtt, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
with open(rtt_csv_path, "w") as csv3_file:
csv3_file.write(p_rtt.read_and_close_stdout())
rtt_data = []
with open(rtt_csv_path) as csv3_file:
csvreader = csv.reader(csv3_file)
for row in csvreader:
rtt_data.append(apply([int, float, float], row))
return rtt_data
def pcap_analyze(request, pcap_name):
mydict = {}
m = models.PcapFile.objects.get(shortfilename=pcap_name)
a, b = os.path.splitext(m.uploadedfile.path)
c, d = os.path.splitext(pcap_name)
harpath = a + ".har"
if True or not os.path.exists(harpath):
try:
cmd = "python %s/main.py %s %s" % (settings.PCAP2HAR_LOC, m.uploadedfile.path, harpath)
print cmd
harmaker = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print harmaker.read_and_close_stdout()
mydict['totalSize'], mydict['categories'], mydict['categories_2'] = summarize_har(harpath)
mydict['categories'] = mydict['categories'].items()
mydict['categories_2'] = mydict['categories_2'].items()
except Exception as e:
print e
csvpath = a + ".csv"
csv2_path = a + "_ip.csv"
csv3_path = a + "_rtt.csv"
# csv4_path = a + "_streams.csv"
all_streams_csvpath = a + "_all_streams.csv"
bandwidth_path = a + "_bandwidth.txt"
if not os.path.exists(csvpath) or not os.path.exists(csv2_path) or not os.path.exists(bandwidth_path) or not os.path.exists(all_streams_csvpath):
makeStats(m.uploadedfile.path, csvpath, bandwidth_path)
rtt_data = makeRttStats(m.uploadedfile.path, csv3_path)
# print rtt_data
mydict['rtt_data'] = rtt_data
d = {}
streams = []
dns_list, ip_to_dns_id = getDNSPackets(m.uploadedfile.path)
with open(csvpath) as csvfile:
csvreader = csv.reader(csvfile)
for row in csvreader:
streams.append(row)
ip1, ip2, transfer, startTime, duration, url = row
d.setdefault((ip1, ip2), [])
d[(ip1, ip2)].append([transfer, startTime, duration, url])
no_ip_streams, no_tcp_streams, total_data_transfer, total_data_waste, no_tcp_waste_streams = 0, 0, 0, 0, 0
myip = None
maxlen = 0
for k in d:
myip = intersect(k, myip)
maxlen = max(maxlen, len(d[k]))
total_data_transfer += sum(int(xx[0]) for xx in d[k])
total_data_waste += sum(int(xx[0]) for xx in d[k] if xx[3].find('No objects') == 0)
no_tcp_waste_streams += sum(1 for xx in d[k] if xx[3].find('No objects') == 0)
no_ip_streams += 1
no_tcp_streams += len(d[k])
_myip = myip[0]
d2 = []
ips = []
for k in d:
# l = len(d[k])
xx = []
o_ip = other(_myip, k)
if o_ip in ip_to_dns_id:
for dns_query_id in ip_to_dns_id[o_ip]:
if dns_list[dns_query_id].queries and dns_list[dns_query_id].responses:
query_time = min(float(q[0]) for q in dns_list[dns_query_id].queries)
response_time = min(float(q[0]) for q in dns_list[dns_query_id].responses)
xx.append([response_time + 5, response_time, query_time, query_time - 5, 'DNS Qusadfadfery for ' + dns_list[dns_query_id].queries[0][3]])
maxlen = max(maxlen, len(d[k]) + len(xx))
stream_events = [] # opening/closing times
for ind, stream in enumerate(streams):
ip1, ip2, transfer, startTime, duration, url = stream
startTime = float(startTime)
duration = float(duration)
stream_events.append((startTime, ind, other(_myip, [ip1, ip2]), 0))
stream_events.append((startTime + duration, ind, other(_myip, [ip1, ip2]), 1))
stream_events.sort(lambda x, y: (cmp(x[0], y[0])))
no_streams_with_time = []
no_toi_connections_with_time = []
n = 0
t = 0
# toi_ips = ["96.17.181.16", "96.17.181.27", "96.17.181.18", "96.17.182.25", "125.252.226.152"]
toi_ips = ["96.17.182.25", "125.252.226.152"]
for stream_event in stream_events:
if stream_event[-1] == 0:
n += 1
if stream_event[-2] in toi_ips:
t += 1
else:
n -= 1
if stream_event[-2] in toi_ips:
t -= 1
no_streams_with_time.append((stream_event[0], n))
if stream_event[-2] in toi_ips:
no_toi_connections_with_time.append((stream_event[0], t))
mydict['no_streams_with_time'] = no_streams_with_time
mydict['no_toi_connections_with_time'] = no_toi_connections_with_time
mydict['no_ip_streams'] = no_ip_streams
mydict['no_tcp_streams'] = no_tcp_streams
mydict['no_tcp_waste_streams'] = no_tcp_waste_streams
mydict['percent_waste_streams'] = 100.0 * no_tcp_waste_streams / float(no_tcp_streams)
mydict['total_data_transfer'] = total_data_transfer
mydict['total_data_waste'] = total_data_waste
mydict['percent_data_waste'] = 100 * total_data_waste / float(total_data_transfer)
mydict['total_dns_requests'] = len(dns_list)
mydict['mean_dns_response_time'] = (sum(min(float(q[0]) for q in dns_list[k].responses) - min(float(q[0]) for q in dns_list[k].queries) for k in dns_list if dns_list[k].queries and dns_list[k].responses)) / len(dns_list)
cmd1 = "tshark -n -r %s -T fields -e tcp.stream" % (m.uploadedfile.path)
streams_data = {}
p = subprocess.Popen(cmd1, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
op = p.read_and_close_stdout()
streams = sorted(list(set(map(int, filter(lambda x: len(x) > 0, map(lambda x: x.strip(), op.split('\n')))))))
all_streams_data = []
if False or all((not os.path.exists(a + "_streams_%d.csv" % i)) for i in xrange(11)):
print "Writing Individual stream csvs"
for s in streams:
sys.stdout.write("\rWriting Individual stream csvs: (%04d/%04d)" % (s, streams[-1]))
sys.stdout.flush()
cmd_stream = "tshark -r %s -R 'tcp.analysis.ack_rtt and tcp.stream == %d' -T fields -e ip.dst -e tcp.analysis.ack_rtt -E separator=, -E quote=n -E occurrence=f" % (m.uploadedfile.path, s)
p_stream = subprocess.Popen(cmd_stream, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
stream_csv = a + "_streams_%d.csv" % s
with open(stream_csv, 'w') as f:
f.write(p_stream.read_and_close_stdout())
for s in streams:
stream_csv = a + "_streams_%d.csv" % s
with open(stream_csv) as f:
csvreader = csv.reader(f)
streams_data.setdefault(s, ["", [], []]) # uplink, downlink
for row in csvreader:
if row[0] == _myip:
streams_data[s][2].append(row[1])
else:
streams_data[s][0] = row[0]
streams_data[s][1].append(row[1])
streams_stats = {}
pingTimes = {'74.125.135.84': '1407.641', '122.160.242.176': '336.872', '50.19.220.231': '661.241', '96.17.182.43': '582.973', '96.17.182.42': '393.474', '96.17.182.65': '337.767', '96.17.182.66': '297.358', '96.17.182.40': '415.109', '184.30.50.110': '432.948', '74.125.236.31': '1465.920', '74.125.236.13': '336.650', '74.125.236.16': '348.960', '74.125.236.15': '1052.792', '204.236.220.251': '713.480', '74.125.236.9': '337.358', '118.214.111.144': '386.384', '96.17.182.10': '330.836', '96.17.182.17': '340.267', '96.17.182.50': '343.809', '2.18.147.206': '676.308', '96.17.182.74': '344.712', '31.13.79.23': '398.418', '96.17.182.58': '337.766', '107.20.164.42': '1697.474', '74.125.236.28': '315.357', '74.125.236.27': '338.574', '74.125.236.26': '1697.778', '74.125.236.25': '185.296', '199.59.148.86': '636.341', '107.20.176.85': '658.544', '23.35.84.211': '502.709', '184.30.63.139': '1673.310', '202.79.210.121': '1535.599'}
def searchPingTime(ip):
try:
return float(pingTimes[ip])
except:
return 0
for s in streams_data:
if len(streams_data[s][0]) == 0 or len(streams_data[s][1]) == 0 or len(streams_data[s][2]) == 0:
continue
streams_stats.setdefault(s, ["", 0, 0, 0, 0, 0]) # ip, upstream-mean, upstream-variance, downstream-mean, downstream-variance, Ping time
streams_stats[s][0] = streams_data[s][0]
streams_stats[s][1:3] = meanvariance(streams_data[s][1])
streams_stats[s][3:5] = meanvariance(streams_data[s][2])
streams_stats[s][5] = searchPingTime(streams_stats[s][0])
mydict['streams_stats'] = streams_stats.items()
all_objects_data = []
content_wise_data = {}
host_wise_data = {}
def short_url(url):
return url if len(url) < 200 else (url[:50] + "...")
with open(all_streams_csvpath) as all_streams_csvfile:
reader = csv.reader(all_streams_csvfile)
for row in reader:
if int(row[6]) == 0: # No objects downloaded
continue
urls_and_times = row[7].split(", ")
url_starttime_list = []
for ut in urls_and_times:
url, start_time = ut.split("::")
url_starttime_list.append((url[1:-1], float(start_time)))
url_time_list = []
for i, u_st in enumerate(url_starttime_list):
url, starttime = u_st
try:
h = models.Host.objects.get(name=urlparse(url).netloc)
except ObjectDoesNotExist:
sock_addrs = socket.gethostbyname_ex(urlparse(url).netloc)[-1]
s = sock_addrs[0]
org = get_org_from_ip(s)
h = models.Host.objects.create(org=org, stream_type=None, name=urlparse(url).netloc)
h.save()
for s in sock_addrs:
ip = models.HostIp.objects.get_or_create(hostId=h, ip=s)[0]
ip.save()
host = h
content_type = "Unknown"
if host:
if host.stream_type:
content_type = host.stream_type.name
dt = 0
if i == len(url_starttime_list) - 1:
dt = float(row[4]) + float(row[5]) - starttime
else:
u2, st2 = url_starttime_list[i + 1]
dt = st2 - starttime
url_time_list.append([row[0], short_url(url), url, starttime, dt, content_type])
row.append(float(row[3]) / 1000 * float(row[5])) # bandwidth
try:
row += streams_stats[int(row[0])]
except KeyError:
# row += ([streams_data[s][0]] + (["No Data"] * 4) + [0])
row += ([s] + (["No Data"] * 4) + [0])
row.append(url_time_list)
all_objects_data += url_time_list
row[7] = list([x[1], x[2]] for x in url_time_list)
all_streams_data.append(row)
host = models.Host.objects.get(name=urlparse(row[7][0][0]).netloc)
content_type = "Unknown"
if host:
if host.stream_type:
content_type = host.stream_type.name
content_wise_data.setdefault(content_type, [0, [], 0]) # data transferred, no. of hosts, no. of objects
content_wise_data[content_type][0] += int(row[3])
content_wise_data[content_type][1].append(urlparse(row[7][0][0]).netloc)
content_wise_data[content_type][2] += len(row[7])
row.append(content_type)
mydict['all_streams_data'] = all_streams_data
mydict['all_objects_data'] = sorted(all_objects_data, cmp=lambda x, y: cmp(float(x[3]), float(y[3])))
mydict['content_wise_data'] = list([x[0], x[1][0] / 1024.0, len(list(set(x[1][1]))), x[1][2]] for x in content_wise_data.items())
bandwidth_uplink_path = a + "_bandwidth_uplink.txt"
bandwidth_downlink_path = a + "_bandwidth_downlink.txt"
retransmit_path = a + "_retransmit.txt"
makeBandwidthStats(m.uploadedfile.path, csvpath, bandwidth_path, bandwidth_uplink_path, bandwidth_downlink_path, retransmit_path, _myip)
retransmission_times = []
with open(retransmit_path) as retransmit_file:
retransmission_times = map(float, retransmit_file.read().split())
print "Evaluated list of retransmission times"
mydict['bandwidth_data'] = parse_bandwidth_data(bandwidth_path, m.uploadLimit + m.downloadLimit, retransmission_times)
mydict['bandwidth_uplink_data'] = parse_bandwidth_data(bandwidth_uplink_path, m.uploadLimit, retransmission_times)
mydict['bandwidth_downlink_data'] = parse_bandwidth_data(bandwidth_downlink_path, m.downloadLimit, retransmission_times)
print "parsed bandwidth data (total, uplink, downlink)"
#combined b/w and no. of streams figure
# ax = axes([0.1, 0.1, 0.8, 0.8])
# labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
# fracs = [15,30,45, 10]
# explode=(0, 0.05, 0, 0)
# pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
# title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})
bandwidth_data_x = list(float(a[1]) for a in mydict['bandwidth_data'])
bandwidth_data_y = list(float(a[4]) for a in mydict['bandwidth_data'])
bandwidth_cdf_y = list(bandwidth_data_y)
for i in xrange(1, len(bandwidth_cdf_y)):
bandwidth_cdf_y[i] = bandwidth_cdf_y[i] + bandwidth_cdf_y[i - 1]
no_streams_with_time_x = list(float(a[0]) for a in no_streams_with_time)
no_streams_with_time_y = list(float(a[1]) for a in no_streams_with_time)
f = figure(figsize=(16,6))
plt1 = f.add_subplot(111)
pyplot.subplots_adjust(right=0.75)
plt2 = plt1.twinx()
plt1.set_xlim(0, max(bandwidth_data_x[-1], no_streams_with_time_x[-1]))
plt1.set_ylim(0, max(bandwidth_data_y)*1.1)
plt2.set_ylim(0, max(no_streams_with_time_y)*1.1)
plt1.set_xlabel("Time")
plt1.set_ylabel("Bandwidth")
plt2.set_ylabel("No. of Streams")
p1, = plt1.plot(bandwidth_data_x, bandwidth_data_y, label="Bandwidth")
p2, = plt2.plot(no_streams_with_time_x, no_streams_with_time_y, label="No. Streams", color="r")
plt1.legend([p1, p2], ["Bandwidth", "No. of Streams"])
# plt1.axis["left"].label.set_color(p1.get_color())
# plt2.axis["right"].label.set_color(p2.get_color())
canvas = FigureCanvasAgg(f)
output = StringIO()
# x.save(output, "PNG")
canvas.print_png(output)
contents = output.getvalue().encode("base64")
output.close()
# f.close()
mydict['bandwidth_numstreams_image_data'] = contents
f = figure(figsize=(16,6))
plt1 = f.add_subplot(111)
pyplot.subplots_adjust(right=0.75)
plt2 = plt1.twinx()
plt1.set_xlim(0, max(bandwidth_data_x[-1], no_streams_with_time_x[-1]))
plt1.set_ylim(0, max(bandwidth_cdf_y)*1.1)
plt2.set_ylim(0, max(no_streams_with_time_y)*1.1)
plt1.set_xlabel("Time")
plt1.set_ylabel("Bandwidth cdf")
plt2.set_ylabel("No. of Streams")
p1, = plt1.plot(bandwidth_data_x, bandwidth_cdf_y, label="Bandwidth CDF")
p2, = plt2.plot(no_streams_with_time_x, no_streams_with_time_y, label="No. Streams", color="r")
plt1.legend([p1, p2], ["Bandwidth CDF", "No. of Streams"])
# plt1.axis["left"].label.set_color(p1.get_color())
# plt2.axis["right"].label.set_color(p2.get_color())
canvas = FigureCanvasAgg(f)
output = StringIO()
# x.save(output, "PNG")
canvas.print_png(output)
contents = output.getvalue().encode("base64")
output.close()
# f.close()
mydict['bandwidthcdf_numstreams_image_data'] = contents
for k in d:
# l = len(d[k])
xx = []
o_ip = other(_myip, k)
if o_ip in ip_to_dns_id:
for dns_query_id in ip_to_dns_id[o_ip]:
# print o_ip, dns_query_id, dns_list[dns_query_id].queries
if dns_list[dns_query_id].queries and dns_list[dns_query_id].responses:
query_time = min(float(q[0]) for q in dns_list[dns_query_id].queries)
response_time = min(float(q[0]) for q in dns_list[dns_query_id].responses)
xx.append([response_time + 5, response_time, query_time, query_time - 5, 'DNS Query for ' + dns_list[dns_query_id].queries[0][3]])
for v in d[k]:
url1 = v[3]
if(len(url1) > 0):
url1 = url1[:50]
xx.append([float(v[1]), float(v[1]), float(v[1]) + float(v[2]), float(v[1]) + float(v[2]), url1])
xx += (maxlen - len(xx)) * [[0, 0, 0, 0, '']]
ips.append(other(_myip, k))
d2.append([other(_myip, k), xx])
print "evaluated candle_sticks"
# print d2
mydict['ips'] = sorted(ips)
mydict['myip'] = myip[0] if len(myip) == 1 else "Could not be determined!"
mydict['pcap_url'] = m.uploadedfile.url
mydict['HARVIEWER_URL'] = settings.HARVIEWER_URL
mydict['har_url'] = m.uploadedfile.url[:-4] + "har"
mydict['pcap_file'] = pcap_name
mydict['csv_file'] = c + ".csv"
mydict['csv_url'] = m.uploadedfile.url[:m.uploadedfile.url.rfind('.')] + '.csv'
mydict['candle_sticks'] = d2
ip_stats = []
with open(csv2_path) as csv2_file:
reader = csv.reader(csv2_file)
for row in reader:
ip1, ip2, transfer, startTime, duration = row
ip_stats.append([other(_myip, [ip1, ip2]), transfer])
print "Evaluated ip_stats from csv2_path"
org_stats = {}
print "starting to get organization for ips"
for ctr, [ip, transfer] in enumerate(ip_stats):
sys.stdout.write("\rcalling get_org_from_ip for %15s......%04d/%04d" % (ip, ctr, len(ip_stats)))
sys.stdout.flush()
org = get_org_from_ip(ip)
org_stats.setdefault(org.name, [0, 0, 0]) # data transferred, streams, no. dns requests
org_stats[org.name][0] += int(transfer)
print "Evaluated org_stat from ip_stats"