-
Notifications
You must be signed in to change notification settings - Fork 15
/
views.py
988 lines (851 loc) · 46.1 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
# Create your views here.
import urllib2
import tempfile
import os
import datetime
import cgi
import random
from django.http import Http404, HttpResponse
from django.utils import simplejson as json
from django.shortcuts import render_to_response
from django.shortcuts import redirect
from django.core.urlresolvers import reverse
from django.template.context import RequestContext
from django.conf import settings
from openwitness.pcap.forms import UploadPcapForm
from openwitness.modules.file.handler import Handler as FileHandler
from openwitness.modules.traffic.pcap.handler import Handler as PcapHandler
from openwitness.modules.traffic.flow.handler import Handler as FlowHandler
from openwitness.modules.traffic.parser.tcp.handler import Handler as TcpHandler
from openwitness.modules.traffic.parser.udp.handler import Handler as UDPHandler
from openwitness.pcap.models import UserJSonFile
from openwitness.modules.md5.handler import Handler as HashHandler
from openwitness.pcap.models import Flow, Pcap, PacketDetails, FlowDetails, HTTPDetails, DNSRequest, DNSResponse, SMTPDetails
from openwitness.modules.utils.handler import translate_time, get_file_type, get_file_size
from openwitness.modules.traffic.log.logger import Logger
from django.contrib.auth.decorators import login_required
# for development purposes, when the login screen is defined this should be removed
from openwitness.api.constants import ICONS
from django.core.paginator import Paginator, InvalidPage, EmptyPage
@login_required()
def upload(request):
log = Logger("Upload form", "DEBUG")
context = {
'page_title': 'Upload your pcap file here',
'upload_status': False,
'message': request.session.get('message', False)
}
if request.method == "POST":
form = UploadPcapForm(request.POST, request.FILES)
if form.is_valid():
user_id = request.user.id
context['form'] = form
file_handler = FileHandler()
file_handler.create_dir()
mem_file = request.FILES['pcap_file']
log.message("file: %s" % mem_file.name)
file_handler.save_file(mem_file)
context['upload_status'] = True
#save the file name to the db
pcap_name = mem_file.name
upload_path = file_handler.upload_dir
# evey pcap file is saved as a flow container, there may or may not be flows, the pcaps colon will give the flow pcaps
hash_handler = HashHandler()
hash_value = hash_handler.get_hash(os.path.join(upload_path, pcap_name))
request.session['uploaded_hash'] = hash_value
request.session['uploaded_file_name'] = pcap_name
# send the file to the defined protocol handler so that it can detect
protocol_handler = settings.PROTOCOL_HANDLER
package = "openwitness.modules.traffic.detector"
module_name = ".".join([package, protocol_handler])
# from openwitness.modules.traffic.detector.x import handler as imported_module
traffic_detector_module = getattr(__import__(module_name, fromlist=["handler"]), "handler")
traffic_detector_handler = traffic_detector_module.Handler()
traffic_detector_handler.create_reassemble_information(file_handler.file_path, upload_path)
output = traffic_detector_handler.detect_proto(file_handler.file_path, upload_path)
if output == False:
request.session['message'] = "Error occured. Please try again."
return redirect('/pcap/upload')
file_type = get_file_type(file_handler.file_path)
file_size = get_file_size(file_handler.file_path)
flow_file, created = Flow.objects.get_or_create(user_id=user_id, hash_value=hash_value,file_name=pcap_name,
path=upload_path, upload_time=datetime.datetime.now(),
file_type=file_type, file_size=file_size)
if "tcp" in output:
log.message("protocol detected: %s" % "TCP")
# run tcp flow extractor
p_read_handler = PcapHandler()
p_read_handler.open_file(file_handler.file_path)
p_read_handler.open_pcap()
f_handler = FlowHandler(p_read_handler)
flow, direction = f_handler.get_tcp_flows()
p_write_handler = PcapHandler()
files = f_handler.save_flow(flow, p_write_handler, save_path=upload_path)
# save the flow pcap names to the mongo db
pcap_list = map(lambda x: Pcap.objects.create(hash_value=hash_handler.get_hash(os.path.join(upload_path, x)), file_name=x, path=upload_path), files.values()[0])
if flow_file.pcaps:
pre_li = flow_file.pcaps
pre_li.extend(pcap_list)
flow_file.pcaps = pre_li
else:
flow_file.pcaps = pcap_list
flow_file.save()
p_read_handler.close_file()
p_write_handler.close_file()
# now i should hook a protocol detector
# before that i should detect the application level protocol
for f in files.values()[0]:
packets = []
# better to save tcp level information to db here
full_path = os.path.join(upload_path, f)
p_read_handler.open_file(full_path)
p_read_handler.open_pcap()
pcap = p_read_handler.get_pcap()
# the list that will keep the tcp part of the packet
tcp_list = []
for ts, buf in pcap:
tcp_handler = TcpHandler()
tcp = tcp_handler.read_tcp(ts, buf)
# this list will be used at the layers above tcp
if tcp:
tcp_list.append((tcp, tcp_handler.ident))
else: continue
tcp_data = u"."
if tcp_handler.data:
tcp_data = tcp_handler.data
# some requests include hexadecimal info, most probably some binary info that can not be
# converted to the utf8, for now i better remove them, #TODO should handle them, though
# try with 4, tcp.data has binary request
# def get_tcp(n):
# count = 1
# f = file("milliyet.pcap", "rb")
# reader = dpkt.pcap.Reader(f)
# for ts, buf in reader:
# if count == n:
# f.close()
# return buf
# count += 1
data_li = tcp_data.split("\r\n")
tmp = []
for data in data_li:
try:
data.encode("utf-8")
tmp.append(data)
except:
tmp.append("data that can not be encoded to utf-8")
tcp_data = " \n".join(tmp)
packet = PacketDetails.objects.create(ident=tcp_handler.ident, flow_hash=hash_value, timestamp=tcp_handler.timestamp,
length=tcp_handler.length, protocol=tcp_handler.proto,
src_ip=tcp_handler.src_ip,
dst_ip=tcp_handler.dst_ip, sport=tcp_handler.sport,
dport=tcp_handler.dport, data=str(tcp_data))
packets.append(packet)
# get the pcap object
p = Pcap.objects.get(hash_value=hash_handler.get_hash(os.path.join(upload_path, f)))
log.message("pcap for packet update detected: %s" % p)
# update its packets
p.packets = list(packets) # converting a queryset to list
p.save()
p_read_handler.close_file()
if "udp" in output:
log.message("protocol detected: %s" % "UDP")
p_read_handler = PcapHandler()
file_path = os.path.join(upload_path, pcap_name)
p_read_handler.open_file(file_path)
p_read_handler.open_pcap()
udp_handler = UDPHandler()
pcap = Pcap.objects.create(hash_value=hash_handler.get_hash(os.path.join(upload_path, pcap_name)), file_name=pcap_name, path=upload_path)
pcap_list = list([pcap])
if flow_file.pcaps:
pre_li = flow_file.pcaps
pre_li.extend(pcap_list)
flow_file.pcaps = pre_li
else:
flow_file.pcaps = pcap_list
flow_file.save()
packets = []
for ts, buf in p_read_handler.get_reader():
udp = udp_handler.read_udp(ts, buf)
if udp:
udp_data = u"."
if udp_handler.data:
udp_data = udp_handler.data
try:
udp_data = udp_data.encode("utf-8")
except:
udp_data = "data that can not be encoded to utf-8"
packet = PacketDetails.objects.create(ident=udp_handler.ident, flow_hash=hash_value, timestamp=udp_handler.timestamp,
length = udp_handler.length,
protocol=udp_handler.proto, src_ip=udp_handler.src_ip,
dst_ip=udp_handler.dst_ip, sport=udp_handler.sport,
dport=udp_handler.dport, data=str(udp_data))
packets.append(packet)
# get the pcap object
p = Pcap.objects.get(hash_value=hash_handler.get_hash(os.path.join(upload_path, pcap_name)))
# update its packets
p.packets = list(packets) # converting a queryset to list
p.save()
p_read_handler.close_file()
# starting the bro related issues for the reassembled data
output = traffic_detector_handler.detect_appproto(file_handler.file_path, upload_path)
log.message("protocol detected: %s" % output)
if output and "http" in output:
log.message("protocol detected: %s" % "HTTP")
# save the reassembled http session IPs to FlowDetails
# this part is checking the http handler module name and importing the handler
http_protocol_handler = settings.HTTP_HANDLER
package = "openwitness.modules.traffic.parser.tcp"
module_name = ".".join([package, http_protocol_handler])
# from openwitness.modules.traffic.parser.tcp.x import handler as imported_module
http_handler_module = getattr(__import__(module_name, fromlist=["handler"]), "handler")
http_handler = http_handler_module.Handler()
# define a get_flow_ips function for the custom handler if required
# TODO: save the timestamps of the flows
flow_ips = http_handler.get_flow_ips(path=upload_path)
flow_detail_li = []
for detail in flow_ips:
flow_detail, create = FlowDetails.objects.get_or_create(parent_hash_value=request.session['uploaded_hash'], user_id=user_id, src_ip=detail[0], sport=int(detail[1]), dst_ip=detail[2], dport=int(detail[3]), protocol="http", timestamp = detail[4])
flow_detail_li.append(flow_detail)
if flow_file.details:
pre_li = flow_file.details
pre_li.extend(flow_detail_li)
flow_file.details = pre_li
else:
flow_file.details = flow_detail_li
flow_file.save()
# then call functions that will save request and responses that will parse dat files, save the headers and files
#http_handler.save_request(path=upload_path, hash_value=request.session['uploaded_hash'])
#http_handler.save_response(path=upload_path, hash_value=request.session['uploaded_hash'])
http_handler.save_request_response(path=upload_path, hash_value=request.session['uploaded_hash'])
# dns realted issues starts here
if output and "dns" in output:
log.message("protocol detected: %s" % "DNS")
dns_protocol_handler = settings.DNS_HANDLER
package = "openwitness.modules.traffic.parser.udp"
module_name = ".".join([package, dns_protocol_handler])
# from openwitness.modules.traffic.parser.udp.x import handler as imported_module
dns_handler_module = getattr(__import__(module_name, fromlist=["handler"]), "handler")
dns_handler = dns_handler_module.Handler()
# define a get_flow_ips function for the custom handler if required
flow_ips = dns_handler.get_flow_ips(path=upload_path, file_name=request.session['uploaded_file_name'])
flow_detail_li = []
for detail in flow_ips:
flow_detail, create = FlowDetails.objects.get_or_create(parent_hash_value=request.session['uploaded_hash'], user_id=user_id, src_ip=detail[0], sport=int(detail[1]), dst_ip=detail[2], dport=int(detail[3]), protocol="dns", timestamp = detail[4])
flow_detail_li.append(flow_detail)
if flow_file.details:
pre_li = flow_file.details
pre_li.extend(flow_detail_li)
flow_file.details = pre_li
else:
flow_file.details = flow_detail_li
flow_file.save()
dns_handler.save_request_response()
if output and "smtp" in output:
log.message("protocol detected: %s" % "SMTP")
smtp_protocol_handler = settings.SMTP_HANDLER
package = "openwitness.modules.traffic.parser.tcp"
module_name = ".".join([package, smtp_protocol_handler])
# from openwitness.modules.traffic.parser.tcp.x import handler as imported_module
smtp_handler_module = getattr(__import__(module_name, fromlist=["handler"]), "handler")
smtp_handler = smtp_handler_module.Handler()
# define a get_flow_ips function for the custom handler if required
smtp_handler.set_flow(flow_file) # i need this, to get the timestamp from a packet belongs to the flow
flow_ips = smtp_handler.get_flow_ips(path=upload_path, file_name=request.session['uploaded_file_name'])
flow_detail_li = []
for detail in flow_ips:
flow_detail, create = FlowDetails.objects.get_or_create(parent_hash_value=request.session['uploaded_hash'], user_id=user_id, src_ip=detail[0], sport=int(detail[1]), dst_ip=detail[2], dport=int(detail[3]), protocol="smtp", timestamp = detail[4])
flow_detail_li.append(flow_detail)
if flow_file.details:
pre_li = flow_file.details
pre_li.extend(flow_detail_li)
flow_file.details = pre_li
else:
flow_file.details = flow_detail_li
flow_file.save()
smtp_handler.save_request_response(upload_path=upload_path)
else:
log.message("protocol detected: %s" % "Unknown")
unknown_protocol_handler = settings.UNKNOWN_HANDLER
package = "openwitness.modules.traffic.parser"
module_name = ".".join([package, unknown_protocol_handler])
unknown_handler_module = getattr(__import__(module_name, fromlist=["handler"]), "handler")
unknown_handler = unknown_handler_module.Handler()
flow_ips = unknown_handler.get_flow_ips(path=upload_path, file_name=request.session['uploaded_file_name'], parent_hash_value=request.session['uploaded_hash'], user_id=user_id)
flow_detail_li = []
for detail in flow_ips:
flow_detail, create = FlowDetails.objects.get_or_create(parent_hash_value=request.session['uploaded_hash'], user_id=user_id, src_ip=detail[0], sport=int(detail[1]), dst_ip=detail[2], dport=int(detail[3]), protocol="unknown", timestamp = detail[4])
if created:
flow_detail_li.append(flow_detail)
if flow_file.details:
pre_li = flow_file.details
pre_li.extend(flow_detail_li)
flow_file.details = pre_li
else:
flow_file.details = flow_detail_li
flow_file.save()
else:
form = UploadPcapForm()
context['form'] = form
request.session['message'] = False
return render_to_response("pcap/upload.html",
context_instance=RequestContext(request, context))
@login_required()
def summary(request):
# to get this work, runserver should be run as bin/django runserver 127.0.0.0:8001 and another instance should be run as
# bin/django runserver
log = Logger("Summary:", "DEBUG")
context = {
'page_title': 'Summary of the uploaded pcaps',
}
user_id = request.user.id
#session_key = request.session.session_key
# TODO: i better keep the user id, login requirements is necessary in this case, for a temporary time use the development USER_ID definition
url = "".join([settings.BASE_URL, "/api/rest/protocols/?format=json&user_id=", str(user_id)])
log.message("URL: %s" % (url))
req = urllib2.Request(url, None)
opener = urllib2.build_opener()
f = None
try:
f = opener.open(req)
json_response = json.load(f)
user_id = user_id
result = []
response_dict = dict()
legend = []
protocols_found = []
for response in json_response:
# indeed i have only one response for now, i decided to put all responses in one timeline instead of multiple timelines
id = os.urandom(4)
response_dict["id"] = "".join([id.encode('hex'), str(user_id)])
response_dict['title'] = "Summary For the Uploaded PCAPs"
response_dict['focus_date'] = None # will be fixed
response_dict['initial_zoom'] = "38"
time_keeper = {'start': None, 'end': None}
importance_keeper = []
# events creation starts here
events = []
for protocol, values in response.iteritems():
count = 0
for value in values:
event_dict = dict()
event_dict['id'] = "-".join([response_dict["id"], protocol, str(count)])
event_dict['link'] = reverse('flow_details', args=(value['flow_id'],))
if value.has_key("type") and value['type']:
event_dict['title'] = value['type']
else:
event_dict['title'] = protocol
if value.has_key('description') and value['description']:
event_dict['description'] = cgi.escape(value['description'])
else:
event_dict['description'] = "No description is set"
event_dict['startdate'] = value['start']
event_dict['enddate'] = value['end']
dt_start = datetime.datetime.strptime(value['start'], "%Y-%m-%d %H:%M:%S")
dt_end = datetime.datetime.strptime(value['end'], "%Y-%m-%d %H:%M:%S")
if not time_keeper['start']:
time_keeper['start'] = dt_start
if dt_start <= time_keeper['start']:
time_keeper['start'] = dt_start
if not time_keeper['end']:
time_keeper['end'] = dt_end
if dt_end >= time_keeper['end']:
time_keeper['end'] = dt_end
event_dict['date_display'] = 'day'
ts = int(datetime.datetime.strptime(value['start'], "%Y-%m-%d %H:%M:%S").strftime("%s"))
importance = translate_time(ts)
#importance = random.randrange(1, 100)
event_dict['importance'] = importance
event_dict['high_threshold'] = int(importance) + 5
importance_keeper.append(int(importance))
if protocol not in protocols_found:
protocols_found.append(protocol)
event_dict['icon'] = ICONS[protocol]
events.append(event_dict)
count += 1
response_dict['events'] = events
# calculate the middle of the time
mid_point = time_keeper['start'] + ((time_keeper['end'] - time_keeper['start']) / 2)
response_dict['focus_date'] = mid_point.isoformat(sep=" ")
# calculate initial zoom
response_dict['initial_zoom'] = repr(int((importance_keeper[0]+importance_keeper[-1])/2))
for proto in protocols_found:
tmp = dict()
tmp['title'] = repr(proto)
tmp['icon'] = ICONS[proto]
legend.append(tmp)
response_dict['legend'] = legend
result.append(response_dict)
json_data = json.dumps(result)
json_dir = os.path.join(settings.PROJECT_ROOT, "json_files")
json_file = tempfile.NamedTemporaryFile(mode="w", dir=json_dir, delete=False)
user_json_file = UserJSonFile.objects.filter(user_id=user_id, json_type="summary")
if len(user_json_file) > 0:
user_json_file[0].delete()
file_path = os.path.join(settings.PROJECT_ROOT, "json_files", user_json_file[0].json_file_name)
try:
os.unlink(file_path)
except:
pass
file_name = os.path.basename(json_file.name)
# save the json data to the temporary file
json_file.write(json_data)
json_file.close()
user_json_file = UserJSonFile(user_id=user_id, json_type="summary", json_file_name=file_name)
user_json_file.save()
context['json_file_url'] = os.path.join(settings.ALTERNATE_BASE_URL, "json_media", file_name)
context['icon_folder'] = os.path.join(settings.ALTERNATE_BASE_URL, "/site_media/jquery_widget/js/timeglider/icons/")
context['pcap_operation'] = "summary"
context['summary_li'] = ["summary", "file_summary"]
# get the summary query infos
flow = Flow.objects.filter(user_id=request.user.id)
context['flow'] = flow
flow_details = FlowDetails.objects.filter(user_id=request.user.id)
flow_details_dict = dict()
f_d = dict()
for flow_detail in flow_details:
if not flow_details_dict.has_key(flow_detail.protocol):
flow_details_dict[flow_detail.protocol] = dict()
f_d = flow_details_dict[flow_detail.protocol]
f_d['count'] = 1
f_d['timestamps'] = [flow_detail.timestamp]
else:
f_d['count'] += 1
f_d['timestamps'].append(flow_detail.timestamp)
for key, value in flow_details_dict.items():
ts = flow_details_dict[key]['timestamps']
ts.sort()
flow_details_dict[key]['start'] = ts[0]
flow_details_dict[key]['end'] = ts[-1]
context['flow_details'] = flow_details_dict
context['ALTERNATE_BASE_URL'] = settings.ALTERNATE_BASE_URL
return render_to_response("pcap/summary.html",
context_instance=RequestContext(request, context))
#HttpResponse(json.dumps(response_dict))
except Exception, ex:
log.message(ex)
raise Http404
def visualize(request, flow_pcap_md5, protocol, type="size"):
if type == "size":
# to get this work, runserver should be run as bin/django runserver 127.0.0.0:8001 and another instance should be run as
# bin/django runserver
log = Logger("Visualize:", "DEBUG")
context = {
'page_title': 'Packet Sizes',
}
#user_id = request.user.id will use them is user is logged_ib
url = "".join([settings.BASE_URL, "/api/rest/protocol_size_by_hash/?format=json&parent_hash_value=", flow_pcap_md5, "&protocol=", protocol])
log.message("URL: %s" % (url))
req = urllib2.Request(url, None)
opener = urllib2.build_opener()
f = None
try:
f = opener.open(req)
json_response = json.load(f)
json_data = json.dumps(json_response)
context['children'] = json_response['children']
context['flow_details'] = json_response
context['pcap_operation'] = "summary-size"
json_dir = os.path.join(settings.PROJECT_ROOT, "json_files")
json_file = tempfile.NamedTemporaryFile(mode="w", dir=json_dir, delete=False)
file_name = os.path.basename(json_file.name)
# save the json data to the temporary file
json_file.write(json_data)
json_file.close()
context['json_file_url'] = os.path.join(settings.ALTERNATE_BASE_URL, "json_media", file_name)
context['measure'] = 'size'
return render_to_response("pcap/summary-size.html",
context_instance=RequestContext(request, context))
except:
# return html template
pass
else:
# to get this work, runserver should be run as bin/django runserver 127.0.0.0:8001 and another instance should be run as
# bin/django runserver
log = Logger("Visualize:", "DEBUG")
context = {
'page_title': 'Packet counts of the uploaded pcaps',
}
user_id = request.user.id
url = "".join([settings.BASE_URL, "/api/rest/protocol_count_by_hash/?format=json&parent_hash_value=", flow_pcap_md5, "&protocol=", protocol], )
log.message("URL: %s" % (url))
req = urllib2.Request(url, None)
opener = urllib2.build_opener()
f = None
try:
f = opener.open(req)
json_response = json.load(f)
json_data = json.dumps(json_response)
context['children'] = json_response['children']
context['flow_details'] = json_response
context['pcap_operation'] = "summary-size"
json_dir = os.path.join(settings.PROJECT_ROOT, "json_files")
json_file = tempfile.NamedTemporaryFile(mode="w", dir=json_dir, delete=False)
file_name = os.path.basename(json_file.name)
# save the json data to the temporary file
json_file.write(json_data)
json_file.close()
context['json_file_url'] = os.path.join(settings.ALTERNATE_BASE_URL, "json_media", file_name)
return render_to_response("pcap/summary-size.html",
context_instance=RequestContext(request, context))
except:
# return html template
pass
def flow_details(request, flow_id):
flow_details = FlowDetails.objects.get(id=flow_id)
result = []
if flow_details.protocol == "http":
http_details = filter(lambda x: x.flow_details.id == flow_details.id, HTTPDetails.objects.all())
for http_detail in http_details:
http_dict = dict()
http_dict['protocol'] = 'HTTP'
if http_detail.http_type:
http_dict['http_type'] = http_detail.http_type
if http_detail.method:
http_dict['method'] = http_detail.method
if http_detail.uri:
http_dict['uri'] = http_detail.uri
if http_detail.headers:
headers = http_detail.headers
content = headers[1:-1]
clean_content = map(lambda x: x.replace("'", "").replace("\\r", "").strip(), content.split(","))
human_readable_header = map(lambda x: str(x), clean_content)
http_dict['headers'] = human_readable_header
if http_detail.version:
http_dict['version'] = http_detail.version
if http_detail.reason:
http_dict['reason'] = http_detail.reason
if http_detail.status:
http_dict['status'] = http_detail.status
if http_detail.body:
http_dict['body'] = http_detail.body
if http_detail.content_type:
http_dict['content_type'] = http_detail.content_type
if http_detail.content_encoding:
http_dict['content_encoding'] = http_detail.content_encoding
if http_detail.file_path:
# i don't keep the file names at the db but at the directories created according to the flow information
flow_details = http_detail.flow_details
src_info = ":".join([flow_details.src_ip, str(flow_details.sport)])
dst_info = ":".join([flow_details.dst_ip, str(flow_details.dport)])
file_dir = "-".join([src_info, dst_info])
files = dict()
files['path'] = os.path.join(http_detail.file_path.split('uploads')[1], file_dir)
#files['file_list'] = os.listdir(os.path.join(http_detail.file_path, os.path.basename(files['path'])))
#files['file_list'] = http_detail.files
http_dict['files'] = files
protocol_handler = settings.VIRUS_HANDLER
package = "openwitness.modules.malware"
module_name = ".".join([package, protocol_handler])
virus_module = getattr(__import__(module_name, fromlist=["handler"]), "handler")
virus_handler = virus_module.Handler()
malware_dict = dict()
for f in http_detail.files:
path = os.path.join(http_detail.file_path, file_dir, f)
rescan_result = virus_handler.rescan(str(path))
permalink = ""
if rescan_result and rescan_result['response_code'] == 1:
permalink = rescan_result['permalink']
else:
scan_result = virus_handler.scan(str(path))
if scan_result and scan_result['response_code'] == 1:
report_result = virus_handler.get_report(str(path))
if report_result and report_result['response_code'] == 1:
permalink = report_result['permalink']
malware_dict[f] = permalink
files['file_list'] = malware_dict
result.append(http_dict)
if flow_details.protocol == "dns":
dns_request= filter(lambda x: x.flow_details.id == flow_details.id, DNSRequest.objects.all())
for dns_req in dns_request:
dns_req_dict = dict()
dns_req_dict['protocol'] = 'DNS Request'
if dns_req.human_readable_type:
dns_req_dict['human_readable_type'] = dns_req.human_readable_type
if dns_req.value:
dns_req_dict['value'] = dns_req.value
result.append(dns_req_dict)
dns_response= filter(lambda x: x.flow_details.id == flow_details.id, DNSResponse.objects.all())
for dns_res in dns_response:
dns_res_dict = dict()
dns_res_dict['protocol'] = 'DNS Request'
if dns_res.human_readable_type:
dns_res_dict['human_readable_type'] = dns_res.human_readable_type
if dns_res.value:
dns_res_dict['value'] = dns_res.value
result.append(dns_res_dict)
if flow_details.protocol == "smtp":
smtp_details= filter(lambda x: x.flow_details.id == flow_details.id, SMTPDetails.objects.all())
for smtp_detail in smtp_details:
smtp_dict = dict()
smtp_dict['protocol'] = 'SMTP'
if smtp_detail.login_data:
smtp_dict['login_data'] = smtp_detail.login_data
if smtp_detail.msg_from:
smtp_dict['msg_from'] = smtp_detail.msg_from
if smtp_detail.rcpt_to:
smtp_dict['rcpt_to'] = smtp_detail.rcpt_to
if smtp_detail.raw:
smtp_dict['raw'] = smtp_detail.raw
if smtp_detail.msgdata:
data = smtp_detail.msgdata[1:-1]
content = data.split(",")
smtp_dict['msgdata'] = content
if smtp_detail.attachment_path:
smtp_dict['attachment_path'] = smtp_detail.attachment_path
smtp_dict['get_path_dict'] = smtp_detail.get_path_dict()
attachment_type = dict()
# detect the file type for SMTP
for attachment in smtp_detail.attachment_path:
attachment_type[os.path.basename(attachment)] = get_file_type(attachment)
protocol_handler = settings.VIRUS_HANDLER
package = "openwitness.modules.malware"
module_name = ".".join([package, protocol_handler])
virus_module = getattr(__import__(module_name, fromlist=["handler"]), "handler")
virus_handler = virus_module.Handler()
for path in smtp_detail.attachment_path:
rescan_result = virus_handler.rescan(str(path))
permalink = ""
if rescan_result and rescan_result['response_code'] == 1:
permalink = rescan_result['permalink']
else:
scan_result = virus_handler.scan(str(path))
if scan_result and scan_result['response_code'] == 1:
report_result = virus_handler.get_report(str(path))
if report_result and report_result['response_code'] == 1:
permalink = report_result['permalink']
base_path = os.path.basename(path)
for content in smtp_dict['get_path_dict']:
if content['file_name'] == base_path:
content['virus_total_link'] = permalink
content['file_type'] = attachment_type[base_path]
result.append(smtp_dict)
context = dict()
context['flow_details'] = result
context['page_title'] = "Flow Details"
return render_to_response("pcap/flow_details.html",
context_instance=RequestContext(request, context))
def get_pcap_url(request, id):
pcap = Pcap.objects.get(id=id)
html = "".join(["<a href=\"/uploads/", pcap.get_upload_path(), "/", str(pcap.file_name), "\"", ">", str(pcap.file_name), "</a>"])
return HttpResponse(html)
#TODO: i should display the packet payload data as well
def get_packet_info(request, packet_ident):
packet = PacketDetails.objects.get(ident=packet_ident)
context = dict()
context['packet_details'] = packet
context['page_title'] = "Packet Details"
return render_to_response("pcap/packet_details.html",
context_instance=RequestContext(request, context))
def flow_pcap_details(request, flow_pcap_md5):
log = Logger("Pcap file details", "DEBUG")
flow = Flow.objects.get(hash_value=flow_pcap_md5)
url = "".join([settings.BASE_URL, "/api/rest/all_protocols_by_hash/?format=json", "&parent_hash_value=", flow_pcap_md5])
log.message("URL: %s" % (url))
req = urllib2.Request(url, None)
opener = urllib2.build_opener()
f = opener.open(req)
json_response = json.load(f)
json_data = json.dumps(json_response)
json_dir = os.path.join(settings.PROJECT_ROOT, "json_files")
json_file = tempfile.NamedTemporaryFile(mode="w", dir=json_dir, delete=False)
file_name = os.path.basename(json_file.name)
# save the json data to the temporary file
json_file.write(json_data)
json_file.close()
context = {
'page_title': " ".join([flow.file_name, "Details"]),
'flow': flow,
'pcap_operation': "file_details",
'json_file_url': os.path.join(settings.ALTERNATE_BASE_URL, "json_media", file_name),
'json_response': json_response,
'hash_value': flow_pcap_md5,
'select_update_li': ["file_details", "file_summary"]
}
return render_to_response("pcap/file_details.html",
context_instance=RequestContext(request, context))
def file_protocol_summary(request, hash_value, protocol, date):
if protocol not in ['UDP', 'TCP']:
summary_type = "flow"
summary_protocol = protocol
summaries = FlowDetails.objects.filter(protocol=protocol, parent_hash_value=hash_value)
else:
proto_dict = {'TCP': 6, 'UDP': 17}
summary_type = "packets"
summary_protocol = protocol
summaries = PacketDetails.objects.filter(protocol=proto_dict[protocol], flow_hash=hash_value)
summary = filter(lambda x: x.timestamp.year == int(date), summaries)
paginator = Paginator(summary, 15)
# Make sure page request is an int. If not, deliver first page.
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
# If page request (9999) is out of range, deliver last page of results.
try:
page_summary = paginator.page(page)
except (EmptyPage, InvalidPage):
page_summary = paginator.page(paginator.num_pages)
context = {
'page_title': 'Protocol Summary',
'page_summary': page_summary,
'summary_type': summary_type,
'summary_protocol': summary_protocol,
'hash_value': hash_value
}
return render_to_response("main/flow_summary.html", context,
context_instance=RequestContext(request))
def file_pcap_summary(request, hash_value):
# to get this work, runserver should be run as bin/django runserver 127.0.0.0:8001 and another instance should be run as
# bin/django runserver
log = Logger("Summary:", "DEBUG")
context = {
'page_title': 'Timeline view for the pcap',
'hash_value': hash_value
}
url = "".join([settings.BASE_URL, "/api/rest/protocols_by_hash/?format=json", "&parent_hash_value=", hash_value])
log.message("URL: %s" % (url))
req = urllib2.Request(url, None)
opener = urllib2.build_opener()
f = None
try:
f = opener.open(req)
json_response = json.load(f)
result = []
response_dict = dict()
legend = []
protocols_found = []
for response in json_response:
# indeed i have only one response for now, i decided to put all responses in one timeline instead of multiple timelines
id = os.urandom(4)
response_dict["id"] = id.encode('hex')
response_dict['title'] = "Summary For the Uploaded PCAP"
response_dict['focus_date'] = None # will be fixed
response_dict['initial_zoom'] = "38"
time_keeper = {'start': None, 'end': None}
importance_keeper = []
# events creation starts here
events = []
for protocol, values in response.iteritems():
count = 0
for value in values:
event_dict = dict()
event_dict['id'] = "-".join([response_dict["id"], protocol, str(count)])
event_dict['link'] = reverse('flow_details', args=(value['flow_id'],))
if value.has_key("type") and value['type']:
event_dict['title'] = value['type']
else:
event_dict['title'] = protocol
if value.has_key('description') and value['description']:
event_dict['description'] = cgi.escape(value['description'])
else:
event_dict['description'] = "No description is set"
event_dict['startdate'] = value['start']
event_dict['enddate'] = value['end']
dt_start = datetime.datetime.strptime(value['start'], "%Y-%m-%d %H:%M:%S")
dt_end = datetime.datetime.strptime(value['end'], "%Y-%m-%d %H:%M:%S")
if not time_keeper['start']:
time_keeper['start'] = dt_start
if dt_start <= time_keeper['start']:
time_keeper['start'] = dt_start
if not time_keeper['end']:
time_keeper['end'] = dt_end
if dt_end >= time_keeper['end']:
time_keeper['end'] = dt_end
event_dict['date_display'] = 'day'
ts = int(datetime.datetime.strptime(value['start'], "%Y-%m-%d %H:%M:%S").strftime("%s"))
importance = translate_time(ts)
#importance = random.randrange(1, 100)
event_dict['importance'] = importance
event_dict['high_threshold'] = int(importance) + 5
importance_keeper.append(int(importance))
if protocol not in protocols_found:
protocols_found.append(protocol)
event_dict['icon'] = ICONS[protocol]
events.append(event_dict)
count += 1
response_dict['events'] = events
# calculate the middle of the time
mid_point = time_keeper['start'] + ((time_keeper['end'] - time_keeper['start']) / 2)
response_dict['focus_date'] = mid_point.isoformat(sep=" ")
# calculate initial zoom
response_dict['initial_zoom'] = repr(int((importance_keeper[0]+importance_keeper[-1])/2))
for proto in protocols_found:
tmp = dict()
tmp['title'] = repr(proto)
tmp['icon'] = ICONS[proto]
legend.append(tmp)
response_dict['legend'] = legend
result.append(response_dict)
json_data = json.dumps(result)
json_dir = os.path.join(settings.PROJECT_ROOT, "json_files")
json_file = tempfile.NamedTemporaryFile(mode="w", dir=json_dir, delete=False)
file_name = os.path.basename(json_file.name)
# save the json data to the temporary file
json_file.write(json_data)
json_file.close()
context['json_file_url'] = os.path.join(settings.ALTERNATE_BASE_URL, "json_media", file_name)
context['icon_folder'] = os.path.join(settings.ALTERNATE_BASE_URL, "/site_media/jquery_widget/js/timeglider/icons/")
context['pcap_operation'] = "file_summary"
context['summary_li'] = ["summary", "file_summary"]
# get the summary query infos
flow = Flow.objects.get(hash_value=hash_value)
context['flow'] = flow
flow_details = FlowDetails.objects.filter(parent_hash_value=hash_value)
flow_details_dict = dict()
f_d = dict()
for flow_detail in flow_details:
if not flow_details_dict.has_key(flow_detail.protocol):
flow_details_dict[flow_detail.protocol] = dict()
f_d = flow_details_dict[flow_detail.protocol]
f_d['count'] = 1
f_d['timestamps'] = [flow_detail.timestamp]
else:
f_d['count'] += 1
f_d['timestamps'].append(flow_detail.timestamp)
for key, value in flow_details_dict.items():
ts = flow_details_dict[key]['timestamps']
ts.sort()
flow_details_dict[key]['start'] = ts[0]
flow_details_dict[key]['end'] = ts[-1]
context['flow_details'] = flow_details_dict
context['ALTERNATE_BASE_URL'] = settings.ALTERNATE_BASE_URL
context['select_update_li'] = ["file_details", "file_summary"]
return render_to_response("pcap/file_summary.html",
context_instance=RequestContext(request, context))
except Exception, ex:
log.message(ex)
raise Http404
def create_parallel_coordinates(request, flow_pcap_md5):
parent_flow = Flow.objects.get(hash_value=flow_pcap_md5)
flows = FlowDetails.objects.filter(parent_hash_value=flow_pcap_md5)
# name group source_port destination_port protocol
# 192.168.1.1:80-192.168.1.2:81,http,80,81
result = []
color_label = dict()
for flow in flows:
src_id = ":".join([flow.src_ip, str(flow.sport)])
dst_id = ":".join([flow.dst_ip, str(flow.dport)])
id = "-".join([src_id, dst_id])
value = ",".join([id, flow.protocol, str(flow.sport), str(flow.dport)])
result.append(value)
#create the colors
if not color_label.has_key(flow.protocol):
color_value = [random.randrange(255), random.randrange(255), random.randrange(255)]
color_label[flow.protocol] = color_value
color_dict = json.dumps(color_label)
csv_dir = os.path.join(settings.PROJECT_ROOT, "csv_files")
csv_file = tempfile.NamedTemporaryFile(mode="w", dir=csv_dir, delete=False)
csv_file.write("\"name\",\"group\",\"src_port\",\"dst_port\"")
csv_file.write("\n")
file_name = os.path.basename(csv_file.name)
content = "\n".join(result)
csv_file.write(content)
csv_file.close()
context = dict()
context['flow'] = parent_flow
context['hash_value'] = flow_pcap_md5
context['csv_file_url'] = os.path.join(settings.ALTERNATE_BASE_URL, "csv_media", file_name)
context['pcap_operation'] = "parallel_coordinates"
context['colors'] = color_dict
return render_to_response("pcap/file_parallel_coordinates.html",
context_instance=RequestContext(request, context))