Hacking Techniques &

Intrusion Detection

Ali Al-Shemery
(aka: B!n@ry)
arabnix
arabnix at
at gmail
gmail dot
dot com
com

All materials is licensed under a Creative
Commons “Share Alike” license.
• http://creativecommons.org/licenses/by-sa/3.0/

2

Writing Basic Security
Tools using Python

Special lecture

>>> import antigravity Cited [1] .

Cited [2] .

Outline • About Python • Python Basics –– Types –– Controls • Python Functions and Modules • Python Tips and Tricks • Coding for Penetration Testers 6 binary-zone.com 6 .

About Python •• Python is an open source programming language.0 was was released released on on December December 2008 •• Name came from TV series “Monty Python’s Flying Circus”.0 3.0 was was release release on on October October 16th. 2000 2000 –– Python Python 3. binary-zone. –– Conceived Conceived in in the the late late 1980’s 1980’s –– Python Python 2.com 7 . •• Development started by Guido van Rossum in December 1989. 16th.0 2.

•• Python is cross platform –– Linux Linux (shipped out of the box) –– Windows Windows (easy (easy to to install) install) –– Mac Mac –– Even Even work on your Droid! –– etc etc binary-zone.com 8 . About Python – Cont.

etc) etc) –– Portable Portable –– HUGE HUGE number number of Extensive Libraries! Libraries! binary-zone. NASA. Why Learn Python? •• Lot of people always ask me “Why learn Python”? •• The answer is simple: –– Simple Simple and and easy easy to to learn learn –– Free Free and and Open Open Source Source –– Powerful Powerful high-level high-level programming programming language language –– Widely Widely used (Google. Yahoo.com 9 . NASA. (Google. Yahoo.

com 10 . What is Python Good for? •• Ideal language for scripting and rapid application development in many areas on most platforms. •• All computer related subjects (IMO except system programming) •• Performing System Administration Tasks •• Encouraging and Helping Children start programming binary-zone.

com Cited [2] 11 . What About Security? •• Extensive use in the information security industry –– Exploit Exploit Development –– Networking Networking –– Debugging Debugging –– Encryption/Decription Encryption/Decription –– Reverse Reverse Engineering Engineering –– Fuzzing Fuzzing –– Web Web –– Forensics Forensics –– Malware Malware analysis analysis binary-zone.

Notepad++. etc binary-zone. Kate. Vim. Geany Geany (was (was my my favorite). Notepad++.com 12 . Nano. Gedit. Kate. Let’s Start Working •• Interactive Interpreter •• Text Editors ––Vim. PyCharm PyCharm (favorite). Gedit. Nano. favorite).

Python Basics •• Integers (int) >>> >>> httpPort=80 httpPort=80 >>> >>> Subnet=24 Subnet=24 •• Floating Point (float) >>> >>> 5.linuxac.org/” binary-zone.com 13 .6 2.2/2 5.linuxac.org/” url=“http://www.6 •• Strings (str) >>> >>> url=“http://www.2/2 2.

'var'. 'log'.Playing with Strings One of the most powerful capabilities of Python •• String Slicing >>> logFile=“/var/log/messages” >>> logFile[0] ‘/’ ‘/’ >>> logFile[1:4] ‘var’ ‘var’ >>> logFile[-8:] 'messages' >>> logFile.com 14 .split("/") [''. [''. 'messages'] 'messages'] binary-zone. 'var'. 'log'.

ashemery.com/?p=123' binary-zone.com/" website="http://www.com‘ 'ali@ashemery.join([website.param]) >>> >>> urlurl 'http://www.com 15 .ashemery.com” >>> >>> userEmail userEmail = userName userName + “@” “@” + + domainName >>> >>> userEmail userEmail 'ali@ashemery.ashemery.ashemery. Playing with Strings – Cont. •• String Concatenation >>> >>> userName userName = “ali” >>> >>> domainName domainName = “ashemery.com/?p=123' 'http://www.com/" >>> >>> param="?p=123" param="?p=123" >>> >>> urlurl = "".com‘ >>> >>> website="http://www.

22. 25.25. 25.append(443) portList. 443] 443] variables!!! binary-zone. 25.append(443) >>> >>> portList portList [21. 25. 22.22. >>> portList = [] [21. 80. 80. 443] 443] >>> portList >>> >>> portList. even list of [21.22) 21 21 >>> portList >>> [21. 80.insert(1.com 16 . 22. Python Lists •• Python lists are very useful when you have a collection of elements >>> >>> portList portList = [21. 80.remove(22) [] Lists in Python can be of >>> >>> portList portList any mixed type.80] >>> >>> >>> portList[0] portList[0] portList. 80. 443] >>> portList.remove(22) portList. [21. 25.

print("FTP print("FTP Service") Service") .. . print("Unknown Service") Important NOTE: . .. else: else: ..80] >>> >>> if if pList[0] == 21: 21: .... . and ELIF Statements >>> >>> pListpList = [21.com • Ensures writing elegant 17 . Python Controls .....25... ... .....22.... print("SSH print("SSH Service") . elif elif pList[0] pList[0] == == 22: 22: ..Decisions •• IF. ELSE.. but Python forces you to use indents binary-zone.. • Python doesn’t use line FTP FTP terminators (ex: semicolons). .

.. port port . Python Controls . print print "This "This is is port port :: "... ".Loops •• For and While Statements >>> >>> forfor port in pList: pList: . This This is port : 21 This This is port : 22 This This is port : 25 This This is port : 80 binary-zone...com 18 . . ...

Python Tips and Tricks •• Changing and checking data types >>> >>> httpPort=80 httpPort=80 >>> >>> httpPort httpPort 80 80 >>> >>> type(httpPort) type(httpPort) <type <type 'int'> 'int'> >>> >>> httpPort httpPort = str(httpPort) str(httpPort) >>> >>> type(httpPort) type(httpPort) <type <type 'str'> 'str'> >>> >>> httpPort httpPort '80’ '80’ binary-zone.com 19 .

80] >>> >>> forfor member in pList: pList: ... This This is port number 21 This This is port number 22 This This is port number 25 This This is port number 80 binary-zone. •• Getting the length of an object >>> >>> len(pList) len(pList) 4 4 •• String formatting >>> >>> pList pList = [21. print print "This "This is is port port number number %d" %d" % % member member .... . Python Tips and Tricks – Cont.. ..22.com 20 ..25.

168.1.168.1" >>> >>> mac mac == "AA:BB:CC:DD:EE:FF" "AA:BB:CC:DD:EE:FF" >>> >>> print print "The "The gateway gateway has has the the following following IP: %s %s and and MAC: MAC: %s %s addresses" % % (ip.1.1.1 and MAC: MAC: AA:BB:CC:DD:EE:FF AA:BB:CC:DD:EE:FF addresses addresses binary-zone. Python Tips and Tricks – Cont.168. mac) mac) The The gateway gateway has the the following following IP: 192.1" "192.com 21 . (ip. •• Another String formatting example >>> >>> ip ip = = "192.

Python Tips and Tricks – Cont.com 22 . •• Working with ASCII codes >>> >>> xx = = '\x41‘ '\x41‘ >>> >>> print print xx AA •• Converting to Hexadecimals >>> >>> hex(255) hex(255) '0xff' '0xff' >>> >>> hex(0) hex(0) '0x0' '0x0' >>> >>> hex(10) hex(10) '0xa' '0xa' >>> >>> hex(15) hex(15) '0xf' '0xf' binary-zone.

com 23 . Python User Input •• Python can handle user input from different sources: –– Directly Directly from the user –– From From Files –– From From GUI (not (not covered covered in in this this lecture) lecture) binary-zone.

com >>> >>> userEmail userEmail 'ali@ashemery.com' >>> >>> type(userEmail) type(userEmail) <type <type 'str'> 'str'> binary-zone.com' 'ali@ashemery.com 24 . Python User Input – Cont. •• Directly from the user using raw_input >>> >>> userEmail userEmail = raw_input("Please enter enter your your email email address: address: ") ") Please Please enter enter your email address: ali@ashemery.

..close() binary-zone..txt". •• From Text Files >>> >>> ff == open("./services.../services. print print line line .com 25 . open(". HTTP HTTP 80 80 SSH SSH 22 22 FTP FTP 21 21 Other common file HTTPS HTTPS 443 443 functions: SMTP SMTP 2525 • write POP POP 110 • read • readline >>> >>> f. ... Python User Input – Cont. "r") "r") >>> >>> for for line in f: ..txt".close() f. .

com 26 . functions comes helpful •• Creating a Python Function (syntax) def fName( listOfArguments ): Line1 Line1 Line2 Line2 …. …. Creating Functions •• Whenever you need to repeat a block of code. Line Line n n return return something something binary-zone.

com 27 . Creating Functions – Cont. •• Basic function to check for valid port numbers def def checkPortNumber(port): checkPortNumber(port): if if port port > 65535 or port < 0: return return False False else: else: return return True True •• Howto use the checkPortNumber function: print checkPortNumber(80)  print checkPortNumber(80)  True True print checkPortNumber(66000)  print checkPortNumber(66000)  False print checkPortNumber(-1)  print checkPortNumber(-1)  False False binary-zone.

module2. module1. moduleN moduleN –– import import module module as as newname newname –– from from module module import * –– from from module module import <specific> binary-zone.com 28 . module2. Working with Modules •• Modules in Python are simply any file containing Python statements! •• Python is distributed with many modules •• To use a module: –– import import module module –– import import module1.

httplib. Common Used Modules •• The most commonly used modules with security coding are: –– string. sys. socket socket –– hashlib hashlib –– httplib.com 29 . sys. re –– os. os. string. urllib2 urllib2 –– Others? Others? Please Please add … binary-zone.

Modules and Examples .

path). and count them import import sys sys print print "path "path has". mac.keys() •• Print the platform type (linux. Module “sys” •• Check Python path.modules. etc) >>> >>> print print sys.path: sys.platform binary-zone. win32.keys() sys.path: print print member member •• Print all imported modules: >>> >>> print print sys.platform sys. len(sys.modules. "members“ print print "The "The members members are:“ are:“ for for member member inin sys.com 31 .

passed".argv)-1. len(sys. sys. "arguments. •• Check application name. len(sys. is:".argv)-1. "arguments.com 32 .argv[0] sys.argv[1:]: print arg else: else: print print “No “No arguments arguments passed!“ passed!“ binary-zone. They They are:" for for arg arg in in sys.argv[0] if if len(sys.argv[1:]: sys.argv) len(sys.argv) > 1: print print “You “You passed". Module “sys” – Cont. and list number of passed arguments import import sys sys print print “The “The application application name name is:".

version binary-zone.com 33 . Module “sys” – Cont. •• Check the Python working version >>> >>> sys.version sys.

com 34 .listdir("/home") os.name os.listdir("/home") for for ff in in fList: fList: print print ff binary-zone. Module “os” import os •• Check platform name (UNIX/Linux = posix. Windows = nt): >>> >>> os.getcwd() os.getcwd() •• List files in specific directory fList fList = = os.name •• Print the current working directory >>> >>> os.

isfile("/tmp") os.linesep •• Get the effective UID for current user >>> >>> os. •• Remove a file (delete) >>> >>> os.com 35 .linesep os.txt") os.isfile("/tmp") >>> >>> os.path.remove(“file.remove(“file.geteuid() •• Check if file and check if directory >>> >>> os.txt") •• Check the platform line terminator (Windows = ‘\r\n’ .geteuid() os. Module “os” – Cont.path.path.isdir("/tmp") os. Linux = ‘\n’ .path. Mac = ‘\r’ ) >>> >>> os.isdir("/tmp") binary-zone.

system("ping -c -c 2 2 127.0.0.0.com 36 .1") •• Execute a command & return a file object files files = os.1") 127.popen("ls os.system("ping os. •• Run a shell command >>> >>> os.popen("ls -l -l /tmp") /tmp") for for ii in in files: files: print print ii binary-zone.0. Module “os” – Cont.

system() # # Executing Executing a a shell shell command command os.getcwd() os.getlogin() # # Return Return the name name of of the the user user logged logged os.getcwd() # # Returns Returns the the current current working working directory directory os. os.chmod() # # Change Change the mode of path to the numeric numeric mode mode binary-zone.stat() os.environ() os.stat() # # Get Get thethe status of a file os.chown() # Change the owner and group id .access() # # Check Check read read permissions permissions os.getlogin() os.chdir() os.system() os.access() os.environ() # # Get Get thethe users environment os.chmod() os.getuid() os.chdir() # # Move Move focus focus to to a a different different directory directory os.getpid() os.getgid() os.getpid() # # Returns Returns the the real real process process ID of the current current process process os.getuid() # # Return Return the current current process’s process’s user user id id os.getgid() # # Return Return the real real group group id of of the the current current process process os.com 37 os. Module “os” – Cont.

getatime() os.getmtime() # # Last Last time time a a given given directory was modified modified os.path.environ() os.getatime() # # Last Last time time a a given given directory was accessed accessed os.getmtime() os.path.uname() # # Return Return information about the current OS OS os.listdir(path) os.uname() os.getloadavg() os.com 38 .chroot(path) os. os.chroot(path) # # Change Change the root directory directory of of the the current current process process to to path os. 5.environ() # # Get Get the the users environment os.path. and and 15 15 minutes minutes binary-zone.path.getloadavg() # # Show Show queue queue averaged averaged over the last 1. 5.listdir(path) # # List List of of the the entries entries in in the the directory directory given given by by path path os.Module “os” – Cont.

rmdir(path) os. os.remove(path) os.rename(src. os.makedirs(path) os.makedirs(path) # # Recursive Recursive directory directory creation creation function function os.com 39 .mkdir(path) os.mkdir(path) # # Create Create a a directory directory named named path path with numeric numeric mode mode mode os. dst) dst) # # Rename Rename the the file file or directory src to dst dst os.rmdir(path) # # Remove Remove (delete) (delete) the the directory directory path path binary-zone.removedirs(path) os.rename(src.remove(path) # # Remove Remove (delete) (delete) the the file file path path os.removedirs(path) # # Remove Remove directories directories recursively recursively os.Module “os” – Cont.

com 40 .com/execute-external-programs-the-python-ways/ binary-zone.Execute External Programs • Running external programs are very useful when you need to do automation (like in scripts) • Execution could be categorized into: –– Synchronous Synchronous •• Invokes Invokes the the external external commands commands and and waits waits for for the the return return –– Asynchronous Asynchronous •• Returns Returns immediately immediately and and continue continue in in the the main main thread thread http://helloacm.

com 41 .read() • The os.Execute External Programs – Cont. World!"). popen(). startfile() startfile() >>> import os >>> print os.popen("echo Hello. • The easy was is to import the os module –– Provides: Provides: popen().popen() will treat the output (stdout. system(). system(). so you can capture the output of the external programs binary-zone. stderr) as file object.

and could returns the exit-status >>> import os >>> print os.Execute External Programs – Cont.exe') binary-zone.system() is also synchronous.com 42 .system('notepad. • The os.

com 43 .Execute External Programs – Cont.startfile() to launch external program that is associated with this file –– This This is an asynchronous asynchronous method method >>> import os >>> os. you can use os.startfile('test. • By acting like double-click in the file explorer.txt') • It will throw out an exception if file is not found –– WindowsError: WindowsError: [Error [Error 2] 2] The The system system cannot cannot find the file specified: specified: binary-zone.

exe') except: pass • Windows platforms only. binary-zone.com 44 .WinExec('notepad.Execute External Programs – Cont. • If you install the win32api package (not shipped by default). you can use the following asynchronous method: import win32api try: win32api.

txt']) subprocess.exe']) subprocess.call(['notepad. .. subprocess.com 45 .Popen(['notepad.terminate() binary-zone.exe'. 'abc.. p.exe'.terminate() p.call(['notepad. • The subprocess package provides a syncrhonous and an asynchronous methods namely call and Popen • Both methods take the first parameter as a list import import subprocess subprocess subprocess..Execute External Programs – Cont.exe']) # # thread thread continues continues ..Popen(['notepad.

stderr=subprocess. shell=True.readlines(): p.PIPE. stdout=subprocess. subprocess. • You can use wait() to synchronous the processes import import subprocess subprocess p p== subprocess.Execute External Programs – Cont.stdout. stdout=subprocess.Popen('ls'.Popen('ls'.PIPE.com 46 .stdout.wait() p.STDOUT) for for line line in in p.wait() print print retval retval binary-zone. shell=True.readlines(): print print line line retval retval = = p.

py ftpClient.com 47 .py simpleServer.py simpleClient.py •• Creating a simple TCP server –– Check Check simpleServer. Module “socket” import socket •• Creating a simple TCP client –– Check Check simpleClient.py binary-zone.py •• Create a malicious FTP Client –– ftpClient.

1\r\nHost: HTTP/1.SOCK_STREAM) socket.com". 80)) 80)) s.AF_INET.1\r\nHost: www.recv(2048) s. Module “socket” – Cont.send('GET // HTTP/1.ashemery.ashemery. socket.com\r\n\r\n') data data == s.connect(("www.close() print print data data Note: For UDP Sockets use SOCK_DGRAM instead of SOCK_STREAM binary-zone.SOCK_STREAM) s.socket(socket.socket(socket.send('GET s.connect(("www.close() s.AF_INET. s.com 48 . socket.ashemery.recv(2048) s.com". •• Create TCP Socket. then send and receive data from website using the socket import import socket ss = = socket.

py pcapyPktCapture1. •• Pcapy enables python scripts to capture packets on the network. •• Pcapy is highly effective when used in conjunction with a packet-handling package such as Impacket. Module “pcapy” •• Pcapy is a Python extension module that interfaces with the libpcap packet capture library. •• Packet Capturing using pcapy example –– pcapyPktCapture1.pybinary-zone.py –– pcapyDumper.py pcapyDumper.py pcapyEx1. which is a collection of Python classes for constructing and dissecting network packets.com 49 .py –– pcapyEx1.

Module “urllib” & “urllib2”

•• urllib2 is a Python module for fetching URLs.
•• Offers a very simple interface, in the form of the
urlopen function.
•• Capable of fetching URLs using a variety of
different protocols (http, ftp, file, etc)
•• Also offers a slightly more complex interface for
handling common situations:
–– Basic
Basic authentication
authentication
–– Cookies
Cookies
–– Proxies
Proxies
–– etc
etc

binary-zone.com 50

urllib vs urllib2
•• Both modules do URL request related stuff, but
they have different functionality.
•• urllib2 can accept a Request object to set the
headers for a URL request, urllib accepts only a
URL.
•• urllib provides the urlencode method which is
used for the generation of GET query strings,
urllib2 doesn't have such a function.
•• Because of that urllib and urllib2 are often used
together.

binary-zone.com Cited [3]
51

Example1
import urllib2
request =
urllib2.Request('http://www.ashemery.com')
response = urllib2.urlopen(request)
payload = response.read()
print(payload)

binary-zone.com Cited [3]
52

urlopen('http://pythonforbeginners.read() response.com Cited 53 [3] .Basic URL Request import urllib2 response = urllib2.close() binary-zone.info() html = response.com/') print response.

Base64 & ROT13 Encoders
Base64
#!/usr/bin/python
#!/usr/bin/python
code
code == raw_input("Enter
raw_input("Enter the data you wish to be encoded to
Base64")
Base64")
answer=code.encode('base64','strict')
answer=code.encode('base64','strict')
print
print answer
answer

ROT13
#!/usr/bin/python
#!/usr/bin/python
code = raw_input("Enter the data you wish to apply ROT13
on")
on")
answer=code.encode(‘rot13','strict')
print
print answer
binary-zone.com Cited [2]
54

Packet Crafting with
Scapy

Scapy Overview
•• Scapy is a Python program that enables the user
to send, sniff and dissect and forge network
packets
•• This capability allows construction of tools that
can probe, scan or attack networks
•• It can replace hping, arpspoof, arp-sk, arping, p0f
and even some parts of Nmap, tcpdump, and
tshark

binary-zone.com 56

com 57 . •• Scapy was created by Philippe Biondi and runs in Python: –– Can Can be be used used interactively interactively at at a a Python Python prompt prompt –– Included Included within within Python Python scripts scripts for more complex interactions interactions •• Must run with root privileges to craft packets •• Don’t need to be a Python Guru to use Scapy! binary-zone. Scapy Overview – Cont.

com 58 .1 •• Supported protocols: >>> >>> ls() ls() •• Details about a specific protocol: >>> >>> ls(TCP) ls(TCP) •• Available commands/functions: >>> >>> lsc() lsc() binary-zone. Scapy Basics .

101") >>> >>> pkt pkt /= /= TCP(dport=80.122.122.code=1) binary-zone.101") >>> >>> pkt pkt /= /= ICMP(type=3.2 •• Crafting a SYN/ACK Packet >>> >>> pkt pkt = = IP(dst="192. Scapy Basics .168.168. flags="SA") flags="SA") •• Crafting ICMP Host Unreachable Packet >>> >>> pkt pkt = = IP(dst="192.com 59 . TCP(dport=80.code=1) ICMP(type=3.

sport=RandShort().flags= /TCP(dport=22.168. and Random Seq# >>> >>> mypkt mypkt == IP(dst="192.sport=RandShort().101") /TCP(dport=22. Random Source Port.com 60 .122.3 Single Line: •• ICMP echo request Packet >>> >>> mypkt mypkt = = IP(dst="192.101") IP(dst="192.101") IP(dst="192. Scapy Basics .101") /ICMP(code=0.122. Port 22.flags= "F") "F") binary-zone.122.seq=RandShort().type=8) /ICMP(code=0.168.122.168.type=8) •• TCP FIN.168.seq=RandShort().

com 61 . Sending and Receiving Packets – @L3 •• Send packet at layer 3 >>> >>> send(packet) send(packet) •• Send packet at L3 and receive one response >>> >>> resp resp = sr1(packet) •• Send packet at L3 and receive all responses >>> >>> ans.unans ans.unans = = sr(packet) sr(packet) binary-zone.

com 62 .unans = = srp(packet) srp(packet) binary-zone.unans ans. Sending and Receiving Packets – @L2 •• Send packet at layer 2 >>> >>> sendp(Ether()/packet) sendp(Ether()/packet) •• Send packet at L2 and receive one response >>> >>> resp resp = srp1(packet) •• Send packet at L2 and receive all responses >>> >>> ans.

show() binary-zone.show() pkts.summary() pkts. Displaying Packets •• Get a summary of each packet: >>> >>> pkts.com 63 .summary() •• Get the whole packet list: >>> >>> pkts.

com 64 .psrc%")) binary-zone.src% \t\t Host: %ARP.summary(lambda(s.timeout=2) >>> ans.168 .122.unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.r): r.sprintf("Ether: %Ether.Scapy Host Discovery >>> ans.0/24").

100).sprintf("Port: %TCP.flags="S")) >>> >>> a.168.summary(lambda(s.122.168.122.com 65 .101") /TCP(dport=(80.r): a.u a.flags="S")) >>> >>> a.101") sr(IP(dst="192.sport% \t\t Flags: Flags: %TCP.168.flags="S")) /TCP(dport=90.100).flags%")) binary-zone.122.122.r): r. Scapy Port Scanning •• TCP SYN Scanner >>> >>> sr1(IP(dst="192.u = = sr(IP(dst="192.101") /TCP(dport=90.summary(lambda(s.flags="S")) /TCP(dport=(80.168.101") sr1(IP(dst="192.

•• Configure the network interface to sniff packets from: >>> >>> conf.com 66 .1 •• Scapy has powerful capabilities to capture and analyze packets. Scapy Sniffing .iface="eth0“ Configure Configure the scapy sniffer to sniff only 20 packets >>> >>> pkts=sniff(count=20) pkts=sniff(count=20) binary-zone.iface="eth0“ conf.

filter="tcp sniff(count=100. Scapy Sniffing .com 67 .timeout=60) pkts=sniff(count=100.timeout=60) •• Sniff only packets based on a filter: >>> >>> pkts pkts = sniff(count=100.2 •• Sniff packets and stop after a defined time: >>> >>> pkts=sniff(count=100.filter="tcp port port 80") 80") binary-zone.

com 68 .3 >>> pkts = sniff(count=10.sprintf("SrcIP={IP:%IP.src% -> DestIP=%IP.dst %} | Payload={Raw:%Raw.load%\n}")) •• What is that doing ??? binary-zone. Scapy Sniffing .prn=lambda x:x.

com 69 .cap". wrpcap(“file1. pkts) •• Dumping packets in HEX format: >>> >>> hexdump(pkts) hexdump(pkts) •• Dump a single packet in HEX format: >>> >>> hexdump(pkts[2]) hexdump(pkts[2]) •• Convert a packet to hex string: >>> >>> str(pkts[2]) str(pkts[2]) binary-zone. Exporting Packets •• Sometimes it is very useful to save the captured packets in a PCAP file for future work: >>> >>> wrpcap(“file1.cap".

Importing Packets •• To import from a PCAP file: >>> >>> pkts pkts = = rdpcap(“file1.cap") rdpcap(“file1.cap") •• Or use the scapy sniffer but with the offline argument: >>> >>> pkts2 pkts2 = sniff(offline="file1.cap") sniff(offline="file1.cap") binary-zone.com 70 .

payload) >>> sniff(count=20. prn=handler2) binary-zone.com 71 .Create your own tools >>> def handler(packet): hexdump(packet. prn=handler) >>> def handler2(packet): sendp(packet) >>> sniff(count=20.

dport t.sport t.":".flags%") p.dport) send(i/t) send(i/t) binary-zone.src i.sprintf("%TCP.flags%") SYN) ifif flags flags ==== "S": "S": # # Only Only respond respond to to SYN SYN Packets Packets ip ip == p[IP] p[IP] # # Received Received IPIP Packet Packet tcp tcp == p[TCP] p[TCP] # # Received Received TCP TCP Segment Segment ii = = IP() IP() # # Outgoing Outgoing IPIP Packet Packet i.dst ip.t.src == ip.all import import ** def def findSYN(p): findSYN(p): sniff(prn=find flags flags = = p.seq + + 11 print print ("SYN/ACK ("SYN/ACK sent sent to to ".seq = = tcp.dport) ".src ip.i.flags t.t.seq tcp.ack tcp.dst.dst.all scapy.dport t. Yesman #!/usr/bin/env #!/usr/bin/env python python import import sys sys from from scapy.dport = = tcp.dport tcp.com 72 .src i.sprintf("%TCP.sport tcp.seq t.dst i.i.dst == ip.sport t.":".ack new_ack new_ack = = tcp.sport = = tcp.dst tt = = TCP() TCP() # # Outgoing Outgoing TCP TCP Segment Segment t.flags == "SA" "SA" t.

Others (not categorized yet!) .

Adding Time Delay • Delay for 5 seconds >>> >>> import import time time >>> >>> time.” time.sleep(5) time.sleep(5) • Run something once a minute: import import time time while while True: True: print print "This "This prints once a minute.sleep(60) http://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python binary-zone.sleep(60) time.com 74 .

SOCK_STREAM) buffer buffer == “buffer “buffer to to send“ send“ shellcode shellcode = = “shellcode” “shellcode” Payload Payload = = cmd cmd ++ buffer buffer + + shellcode shellcode print print "\n "\n Any Any status status message message \n“ \n“ s.SOCK_STREAM) socket. socket.port)) s.close binary-zone.com 75 .AF_INET.socket(socket.send(payload s.connect((host.port)) data data == s.connect((host. Exploit Development #!/usr/bin/python #!/usr/bin/python import import socket socket host host == “target” “target” port port == <port#> <port#> cmd cmd = = “initial “initial command” command” ss = = socket.AF_INET. socket.socket(socket.recv(1024) s.recv(1024) s.close s.send(payload +”\n”) +”\n”) s.

Python Tools for Penetration Testers .

supports supports modifying modifying non-standard non-standard protocols protocols onon the the fly fly •• Pytbull: Pytbull: flexible flexible IDS/IPS IDS/IPS testing testing framework framework (shipped (shipped with with more more than than 300 300 tests) tests) binary-zone. sniff sniff and and dissect dissect and and forge forge network network packets. defragmentation. Pcapy Pcapy and and pylibpcap: pylibpcap: several several different different Python Python bindings bindings for for libpcap libpcap •• libdnet: libdnet: low-level low-level networking networking routines. creation/parsing. enumerate enumerate subdomains subdomains on on aa target target domain domain through through aa wordlist wordlist •• Mallory. routines. packets. send. pypcap. simple simple packet packet creation/parsing. Network Tools •• Scapy: Scapy: send. sniffing.proxy. with with definitions definitions for for the the basic basic TCP/IP TCP/IP protocols protocols •• Impacket: Impacket: craftcraft and and decode decode network network packets. Includes Includes support support for for higher- higher- level level protocols protocols suchsuch asas NMB NMB andand SMB SMB •• pynids: pynids: libnids libnids wrapper wrapper offering offering sniffing. fast.com Cited [5] 77 . Usable Usable interactively interactively or or as as aa library library •• pypcap. packets. Mallory. TCP TCP stream stream reassembly reassembly and and port port scan scan detection detection •• Dirtbags Dirtbags py-pcap: py-pcap: read read pcap pcap files files without without libpcap libpcap •• flowgrep: flowgrep: grepgrep through through packet packet payloads payloads using using regular regular expressions expressions •• Knock Knock Subdomain Subdomain Scan. Scan. IP IP defragmentation. extensible extensible TCP/UDP TCP/UDP man-in-the-middle man-in-the-middle proxy. including including interface interface lookup lookup and and Ethernet Ethernet frame frame transmission transmission •• dpkt: dpkt: fast.

py: PyCommand PyCommand for ImmunityImmunity Debugger Debugger that that replaces replaces and and improves improves on on pvefindaddr pvefindaddr •• IDAPython: IDAPython: IDAIDA Pro plugin that integrates the Python programming programming language. PIDA. allowing allowing scripts to run run in in IDA IDA Pro Pro •• PyEMU: PyEMU: fully fully scriptable scriptable IA-32 IA-32 emulator. framework.py: mona. pGRAPH pGRAPH •• Immunity Immunity Debugger: Debugger: scriptable scriptable GUI and and command command line debugger debugger •• mona. Debugging and Reverse Engineering Tools •• Paimei: Paimei: reverse engineering framework. PyDBG. PIDA. useful useful for for malware malware analysis analysis •• pefile: pefile: read and work with Portable Executable (aka PE) files files •• pydasm: pydasm: Python Python interface interface to to the the libdasm libdasm x86 x86 disassembling disassembling library library binary-zone. includes includes PyDBG.com Cited [5] 78 . emulator. language.

and vdb is a debugger which uses uses it •• Androguard: Androguard: reverse reverse engineering engineering and and analysis analysis of of Android Android applications applications binary-zone.com Cited [5] 79 . •• PyDbgEng: PyDbgEng: Python Python wrapper wrapper for for the the Microsoft Microsoft Windows Windows Debugging Debugging Engine Engine •• uhooker: uhooker: intercept intercept calls calls toto API calls inside DLLs. AMD64. BSDBSD and and Darwin Darwin system system call call to trace trace processes) processes) written in Python •• vdb vdb // vtrace: vtrace: vtrace vtrace isis a cross-platform cross-platform process process debugging debugging API API implemented implemented in python. licensed licensed under under the the BSD BSD license •• python-ptrace: python-ptrace: debugger debugger usingusing ptrace ptrace (Linux. Debugging and Reverse Engineering Tools – Cont. (Linux. and also arbitrary arbitrary addresses within the the executable executable filefile in in memory memory •• diStorm: diStorm: disassembler disassembler library library for for AMD64.

Fuzzing Tools •• Sulley: Sulley: fuzzer fuzzer development and fuzz testing testing framework framework consisting consisting of of multiple multiple extensible extensible components •• Peach Peach Fuzzing Fuzzing Platform: Platform: extensible extensible fuzzing framework for generation generation and and mutation mutation based fuzzing (v2 was written in Python) Python) •• antiparser: antiparser: fuzz fuzz testing testing and and fault fault injection injection API API •• TAOF.com Cited [5] 80 . a man-in- man-in- the-middle the-middle non-deterministic non-deterministic network network fuzzer fuzzer •• untidy: untidy: general purpose XML fuzzer •• Powerfuzzer: Powerfuzzer: highly highly automated automated and and fully fully customizable customizable web fuzzer fuzzer (HTTP (HTTP protocol protocol based application application fuzzer) fuzzer) •• SMUDGE SMUDGE binary-zone. TAOF. (The Art of Fuzzing) including ProxyFuzz.

textual). •• Mistress: Mistress: probe file file formats formats on on the the fly fly and and protocols protocols with with malformed malformed data. and and file file systems systems containing containing fuzzed fuzzed files files in order order to to test test the the robustness robustness of of forensics forensics tools tools and and examination examination systems systems •• Windows Windows IPC Fuzzing Fuzzing Tools: Tools: tools tools used used toto fuzz fuzz applications that that use use Windows Windows Interprocess Communication mechanisms mechanisms •• WSBang: WSBang: perform perform automated automated security security testing testing ofof SOAP SOAP based based web web services services •• Construct: Construct: library library for for parsing parsing and building building ofof data data structures structures (binary (binary or or textual). based on on pre-defined pre-defined patterns patterns •• Fuzzbox: Fuzzbox: multi-codec multi-codec media media fuzzer fuzzer •• Forensic Forensic Fuzzing Fuzzing Tools: Tools: generate generate fuzzed files. Define your data structures in in a a declarative declarative manner manner binary-zone. Fuzzing Tools – Cont.com Cited [5] 81 . fuzzed file systems. systems.

py: webkit webkit web client client written written in in Python Python •• Windmill: Windmill: web web testing testing tool tool designed designed to let let you you painlessly painlessly automate automate andand debug debug your your web web application application binary-zone. Web Tools •• Requests: Requests: elegant elegant and simple HTTP library. Supports Supports automated automated Web testing •• Ghost. built for human beings beings •• HTTPie: HTTPie: human-friendly human-friendly cURL-like cURL-like command command line HTTP client client •• ProxMon: ProxMon: processes processes proxy proxy logs logs and and reports discovered discovered issues issues •• WSMap: WSMap: find web service endpoints and discovery files •• Twill: Twill: browse browse the Web from a command-line interface.com Cited [5] 82 .py: Ghost.

Web Tools – Cont. allows allows for for the the evaluation evaluation and and calling calling of of Javascript Javascript scripts scripts and and functions functions •• mitmproxy: mitmproxy: SSL-capable. proxy. SSL-capable. Console Console interface interface allows traffic flows to be inspected and edited on the the fly fly •• pathod pathod // pathoc: pathoc: pathological daemon/client for tormenting HTTP HTTP clients clients and and servers servers binary-zone. intercepting intercepting HTTP HTTP proxy. engine.com Cited [5] 83 . •• FunkLoad: FunkLoad: functional functional and load web tester •• spynner: spynner: Programmatic Programmatic webweb browsing browsing module module for for Python Python with with Javascript/AJAX Javascript/AJAX support •• python-spidermonkey: python-spidermonkey: bridge bridge to to the the Mozilla Mozilla SpiderMonkey SpiderMonkey JavaScript JavaScript engine.

) binary-zone. identify file types from their binary signatures. Forensic Tools •• Volatility: extract digital artifacts from volatile memory (RAM) samples •• LibForensics: library for developing digital forensics applications •• TrIDLib. Now includes Python binding •• aft: Android forensic toolkit •• Lots of others which you’ll see them very soon .com Cited [5] 84 .

Detects Detects many common common file file formats formats and and can can remove remove active active content content •• pyClamAV: pyClamAV: add add virus detection capabilities capabilities to to your your Python Python software software •• jsunpack-n. generic generic JavaScript unpacker: emulates browser functionality functionality to detect exploits exploits that that target target browser browser and and browser browser plug-in plug-in vulnerabilities •• yara-python: yara-python: identify identify and and classify malware malware samples samples •• phoneyc: phoneyc: pure pure Python Python honeyclient implementation binary-zone. e-mails. files. jsunpack-n.com Cited [5] 85 . mainly mainly to analyze malware •• Exefilter: Exefilter: filter filter file file formats formats in in e-mails. web pages pages or or files. Malware Analysis Tools •• pyew: pyew: command command line hexadecimal hexadecimal editor and disassembler.

merge. PDF Tools •• Didier Stevens' PDF tools: analyse.. encrypt.com . •• Origapy: Python wrapper for the Origami Ruby module which sanitizes PDF files •• pyPDF: pure Python PDF toolkit: extract info. pdf-parser and make-pdf and mPDF) •• Opaf: Open PDF Analysis Framework. decrypt. including Qt4 support Cited [5] 86 binary-zone. •• PDFMiner: extract text from PDF files •• python-poppler-qt4: Python binding for the Poppler PDF library. spilt. Converts PDF to an XML tree that can be analyzed and modified. crop. identify and create PDF files (includes PDFiD..

Lab Time! .

DIY  This lab is a Do It Yourself (DIY) Lab that must done at home: [1] Create a TCP ACK Port Scanner [2] Create a TCP Replay Tool [3] Create a UDP Ping Tool [4] Create a Sniffer that filters based on user input [5] Create a tool for HTTP Basic Authentication –– Login Login –– Bruteforce Bruteforce [6] Create a basic Honeypot that logs all activity to a text file binary-zone.com 88 .

Modules. SUMMARY •• Discussed Discussed Why Why Learn Learn Python Python •• Discussed Discussed What What is Python Python Good Good for? for? •• Explained Explained Python Python Basics •• Some Some Quick Quick Python Python Tips Tips and Tricks •• Python Python User User Input Input •• Howto Howto Create Create Functions using using Python Python •• Working Working with with Modules. etc etc •• Using Using Python Python to to work work with with the the Web Web (urllib. pcapy. urllib2) •• Using Using Python Python to to create create simple simple Encoders Encoders •• Howto Howto use use Python Python for for Exploit Exploit Development •• Craft Craft your your own own packets packets using using Scapy Scapy •• Python Python tools tools for penetration penetration testers testers binary-zone.com 89 . and and the the Python Python Common Common Used Used Modules Modules •• Howto Howto use use the the Python Python SYS and OS Modules •• Using Using Python Python to to work work with with Networks: Networks: Sockets. pcapy. Sockets.

dirk-loss. http://snipplr.com/ http://tazdrumm3r.de/python-tools.pythonforbeginners.wordpress.com/view/3579/live-packet-capture-in-python- with-pcapy/ with-pcapy/ [4] [4] How How toto use use urllib2 urllib2 in in Python. pcapy. Citation of Used Work [1] [1] Keith Dixon. Python. http://xkcd. http://xkcd. @Tazdrumm3r.com/353/.pythonforbeginners. http://www. [3] [3] Live Packet Packet Capture Capture in Python Python with with pcapy.com/python-on-the- http://www.com/ [2] [2] Python Python Comic.com 90 .com/python-on-the- web/how-to-use-urllib2-in-python/ web/how-to-use-urllib2-in-python/ [5] [5] Python Python tools tools for for penetration penetration testers.com/353/.dirk-loss.de/python-tools.wordpress.htm binary-zone.htm http://www. Comic. http://tazdrumm3r. testers. http://www.com/view/3579/live-packet-capture-in-python- http://snipplr.

python. tools.php?module=Wiki&acti http://corelabs. http://www.dirk-loss. References [1] [1] Coding Coding for for Penetration Penetration Testers Testers Book.coresecurity.uk/python/articles/authentication. http://www. http://www.de/python-tools.python.com/index.dirk-loss. Book.com/index. Searle.tutorialspoint.org/ [8] [8] Python Python Tutorial. Tutorial.php?module=Wiki&acti on=view&type=tool&name=Pcapy on=view&type=tool&name=Pcapy [10] [10] Basic Basic Authentication Authentication Authentication Authentication with with Python.org/ [5] [5] Python Python Infosec Infosec tools.shtml [11] [11] Justin Justin Searle.sans.org/reading_room/whitepapers/incident/grow-foren http://www.voidspace.org/ http://docs.htm [6] [6] Grow Grow Your Your Own Own Forensic Forensic Tools: Tools: A A Taxonomy Taxonomy of of Python Python Libraries Libraries Helpful Helpful for for Forensic Forensic Analysis.org/projects/scapy/doc/ http://www. Python. Python.python.htm http://www.de/python-tools.htm http://www. http://www.tutorialspoint.python. http://www.sans. Analysis.org/ http://www.com/python/index.org/projects/scapy/doc/ [4] [4] Python.voidspace. Pentesters.org. [2] [2] Violent Violent Python Python Book.org/reading_room/whitepapers/incident/grow-foren sic-tools-taxonomy-python-libraries-helpful-forensic-analysis_33 sic-tools-taxonomy-python-libraries-helpful-forensic-analysis_33 453 453 [7] [7] Python Python Docs. Book.org.secdev.htm [9] [9] pcapy.secdev. Docs. [3] [3] Scapy Scapy Documentation. InGuardians InGuardians IncInc binary-zone. http://docs. Documentation. pcapy.com/python/index.com 91 . Python Python Basics Basics for for Web Web App App Pentesters.coresecurity. http://corelabs.shtml http://www. http://www.uk/python/articles/authentication.