Вы находитесь на странице: 1из 91

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.
Development started by Guido van Rossum in
December 1989.
Conceived
Conceived in
in the
the late
late 1980s
1980s
Python
Python 2.0
2.0 was
was release
release on
on October
October 16th,
16th, 2000
2000
Python
Python 3.0
3.0 was
was released
released on
on December
December 2008

Name came from TV series Monty Pythons


Flying Circus.

binary-zone.com 7
About Python Cont.
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
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,
(Google, NASA,
NASA, Yahoo,
Yahoo, etc)
etc)
Portable
Portable
HUGE
HUGE number
number of Extensive Libraries!
Libraries!

binary-zone.com 9
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 10
What About Security?
Extensive use in theinformation securityindustry
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.com Cited [2]


11
Lets Start Working
Interactive Interpreter

Text Editors
Vim,
Vim, Nano,
Nano,
Geany
Geany (was
(was my
my favorite),
favorite),
PyCharm
PyCharm (favorite),
Gedit,
Gedit, Kate,
Kate,
Notepad++,
Notepad++, etc
binary-zone.com 12
Python Basics
Integers (int)
>>>
>>> httpPort=80
httpPort=80
>>>
>>> Subnet=24
Subnet=24

Floating Point (float)


>>>
>>> 5.2/2
5.2/2
2.6
2.6

Strings (str)
>>>
>>> url=http://www.linuxac.org/
url=http://www.linuxac.org/

binary-zone.com 13
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.split("/")
['',
['', 'var',
'var', 'log',
'log', 'messages']
'messages']

binary-zone.com 14
Playing with Strings Cont.

String Concatenation
>>>
>>> userName
userName = ali
>>>
>>> domainName
domainName = ashemery.com
>>>
>>> userEmail
userEmail = userName
userName + @
@ +
+ domainName
>>>
>>> userEmail
userEmail
'ali@ashemery.com
'ali@ashemery.com

>>>
>>> website="http://www.ashemery.com/"
website="http://www.ashemery.com/"
>>>
>>> param="?p=123"
param="?p=123"
>>>
>>> urlurl = "".join([website,param])
>>>
>>> urlurl
'http://www.ashemery.com/?p=123'
'http://www.ashemery.com/?p=123'

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

IF, ELSE, and ELIF Statements


>>>
>>> pListpList = [21,22,25,80]
>>>
>>> if if pList[0] == 21:
21:
...
... print("FTP
print("FTP Service")
Service")
...
... elif
elif pList[0]
pList[0] ==
== 22:
22:
...
... print("SSH
print("SSH Service")
...
... else:
else:
...
... print("Unknown Service") Important NOTE:
...
... Python doesnt use line
FTP
FTP terminators (ex:
semicolons), but Python
forces you to use
indents

binary-zone.com Ensures writing elegant


17
Python Controls - Loops
For and While Statements
>>>
>>> forfor port in pList:
pList:
...
... print
print "This
"This is
is port
port :: ",
", port
port
...
...
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
Python Tips and Tricks Cont.

Getting the length of an object


>>>
>>> len(pList)
len(pList)
4
4

String formatting
>>>
>>> pList
pList = [21,22,25,80]
>>>
>>> forfor member in pList:
pList:
...
... print
print "This
"This is
is port
port number
number %d"
%d" %
% member
member
...
...
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.com 20
Python Tips and Tricks Cont.

Another String formatting example


>>>
>>> ip
ip =
= "192.168.1.1"
"192.168.1.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,
(ip, mac)
mac)

The
The gateway
gateway has the
the following
following IP: 192.168.1.1 and MAC:
MAC:
AA:BB:CC:DD:EE:FF
AA:BB:CC:DD:EE:FF addresses
addresses

binary-zone.com 21
Python Tips and Tricks Cont.

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 22
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 23
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.com

>>>
>>> userEmail
userEmail
'ali@ashemery.com'
'ali@ashemery.com'

>>>
>>> type(userEmail)
type(userEmail)
<type
<type 'str'>
'str'>

binary-zone.com 24
Python User Input Cont.
From Text Files
>>>
>>> ff == open("./services.txt",
open("./services.txt", "r")
"r")
>>>
>>> for
for line in f:
...
... print
print line
line
...
...
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.close()
f.close()
binary-zone.com 25
Creating Functions
Whenever you need to repeat a block of code,
functions comes helpful
Creating a Python Function (syntax)

def fName( listOfArguments ):


Line1
Line1
Line2
Line2
.
.
Line
Line n
n
return
return something
something

binary-zone.com 26
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.com 27
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,
module1, module2,
module2, 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
Common Used Modules
The most commonly used modules with security
coding are:
string,
string, re
os,
os, sys,
sys, socket
socket
hashlib
hashlib
httplib,
httplib, urllib2
urllib2
Others?
Others? Please
Please add

binary-zone.com 29
Modules and Examples
Module sys
Check Python path, and count them
import
import sys
sys
print
print "path
"path has", len(sys.path), "members
print
print "The
"The members
members are:
are:
for
for member
member inin sys.path:
sys.path:
print
print member
member

Print all imported modules:


>>>
>>> print
print sys.modules.keys()
sys.modules.keys()

Print the platform type (linux, win32, mac, etc)


>>>
>>> print
print sys.platform
sys.platform

binary-zone.com 31
Module sys Cont.
Check application name, and list number of
passed arguments
import
import sys
sys
print
print The
The application
application name
name is:",
is:", sys.argv[0]
sys.argv[0]

if
if len(sys.argv)
len(sys.argv) > 1:
print
print You
You passed",
passed", len(sys.argv)-1,
len(sys.argv)-1, "arguments.
"arguments. They
They are:"
for
for arg
arg in
in sys.argv[1:]:
sys.argv[1:]:
print arg
else:
else:
print
print No
No arguments
arguments passed!
passed!

binary-zone.com 32
Module sys Cont.
Check the Python working version
>>>
>>> sys.version
sys.version

binary-zone.com 33
Module os
import os

Check platform name (UNIX/Linux = posix,


Windows = nt):
>>>
>>> os.name
os.name

Print the current working directory


>>>
>>> os.getcwd()
os.getcwd()

List files in specific directory


fList
fList = = os.listdir("/home")
os.listdir("/home")
for
for ff in
in fList:
fList:
print
print ff binary-zone.com 34
Module os Cont.
Remove a file (delete)
>>>
>>> os.remove(file.txt")
os.remove(file.txt")

Check the platform line terminator (Windows =


\r\n , Linux = \n , Mac = \r )
>>>
>>> os.linesep
os.linesep

Get the effective UID for current user


>>>
>>> os.geteuid()
os.geteuid()

Check if file and check if directory


>>>
>>> os.path.isfile("/tmp")
os.path.isfile("/tmp")
>>>
>>> os.path.isdir("/tmp")
os.path.isdir("/tmp")
binary-zone.com 35
Module os Cont.
Run a shell command
>>>
>>> os.system("ping
os.system("ping -c
-c 2
2 127.0.0.1")
127.0.0.1")

Execute a command & return a file object


files
files = os.popen("ls
os.popen("ls -l
-l /tmp")
/tmp")
for
for ii in
in files:
files:
print
print ii

binary-zone.com 36
Module os Cont.
os.system()
os.system() #
# Executing
Executing a a shell
shell command
command
os.stat()
os.stat() #
# Get
Get thethe status of a file
os.environ()
os.environ() #
# Get
Get thethe users environment
os.chdir()
os.chdir() #
# Move
Move focus
focus to to a
a different
different directory
directory
os.getcwd()
os.getcwd() #
# Returns
Returns the the current
current working
working directory
directory
os.getgid()
os.getgid() #
# Return
Return the real real group
group id of
of the
the current
current
process
process
os.getuid()
os.getuid() #
# Return
Return the current
current processs
processs user
user id
id
os.getpid()
os.getpid() #
# Returns
Returns the the real
real process
process ID of the
current
current process
process
os.getlogin()
os.getlogin() #
# Return
Return the name name of of the
the user
user logged
logged
os.access()
os.access() #
# Check
Check read read permissions
permissions
os.chmod()
os.chmod() #
# Change
Change the mode of path to the
numeric
numeric mode
mode
binary-zone.com 37
os.chown() # Change the owner and group id
Module os Cont.
os.path.getmtime()
os.path.getmtime() #
# Last
Last time
time a
a given
given directory was
modified
modified
os.path.getatime()
os.path.getatime() #
# Last
Last time
time a
a given
given directory was
accessed
accessed
os.environ()
os.environ() #
# Get
Get the
the users environment
os.uname()
os.uname() #
# Return
Return information about the current
OS
OS
os.chroot(path)
os.chroot(path) #
# Change
Change the root directory
directory of
of the
the
current
current process
process to
to path

os.listdir(path)
os.listdir(path) #
# List
List of
of the
the entries
entries in
in the
the directory
directory given
given
by
by path
path
os.getloadavg()
os.getloadavg() #
# Show
Show queue
queue averaged
averaged over the last 1,
5,
5, and
and 15
15 minutes
minutes
binary-zone.com 38
Module os Cont.
os.mkdir(path)
os.mkdir(path) #
# Create
Create a
a directory
directory named
named path
path with
numeric
numeric mode
mode mode

os.makedirs(path)
os.makedirs(path) #
# Recursive
Recursive directory
directory creation
creation
function
function
os.remove(path)
os.remove(path) #
# Remove
Remove (delete)
(delete) the
the file
file path
path
os.removedirs(path)
os.removedirs(path) #
# Remove
Remove directories
directories recursively
recursively
os.rename(src,
os.rename(src, dst)
dst) #
# Rename
Rename the
the file
file or directory src to
dst
dst
os.rmdir(path)
os.rmdir(path) #
# Remove
Remove (delete)
(delete) the
the directory
directory path
path

binary-zone.com 39
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/execute-external-programs-the-python-ways/

binary-zone.com 40
Execute External Programs
Cont.
The easy was is to import the os module
Provides:
Provides: popen(),
popen(), system(),
system(), startfile()
startfile()

>>> import os
>>> print os.popen("echo Hello, World!").read()

The os.popen() will treat the output (stdout,


stderr) as file object, so you can capture the
output of the external programs

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

binary-zone.com 42
Execute External Programs
Cont.
By acting like double-click in the file explorer, you
can use os.startfile() to launch external program
that is associated with this file
This
This is an asynchronous
asynchronous method
method

>>> import os
>>> os.startfile('test.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.com 43
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.WinExec('notepad.exe')
except:
pass

Windows platforms only.

binary-zone.com 44
Execute External Programs
Cont.
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.call(['notepad.exe',
subprocess.call(['notepad.exe', 'abc.txt'])
subprocess.Popen(['notepad.exe'])
subprocess.Popen(['notepad.exe'])
#
# thread
thread continues
continues ...
...
p.terminate()
p.terminate()

binary-zone.com 45
Execute External Programs
Cont.
You can use wait() to synchronous the processes

import
import subprocess
subprocess
p
p== subprocess.Popen('ls',
subprocess.Popen('ls', shell=True,
shell=True,
stdout=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
for
for line
line in
in p.stdout.readlines():
p.stdout.readlines():
print
print line
line
retval
retval = = p.wait()
p.wait()
print
print retval
retval

binary-zone.com 46
Module socket
import socket

Creating a simple TCP client


Check
Check simpleClient.py
simpleClient.py

Creating a simple TCP server


Check
Check simpleServer.py
simpleServer.py

Create a malicious FTP Client


ftpClient.py
ftpClient.py

binary-zone.com 47
Module socket Cont.
Create TCP Socket, then send and receive data
from website using the socket

import
import socket
ss =
= socket.socket(socket.AF_INET,
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.SOCK_STREAM)
s.connect(("www.ashemery.com",
s.connect(("www.ashemery.com", 80))
80))
s.send('GET
s.send('GET // HTTP/1.1\r\nHost:
HTTP/1.1\r\nHost: www.ashemery.com\r\n\r\n')
data
data == s.recv(2048)
s.recv(2048)
s.close()
s.close()
print
print data
data

Note: For UDP Sockets use SOCK_DGRAM


instead of SOCK_STREAM
binary-zone.com 48
Module pcapy
Pcapy is a Python extension module that
interfaces with the libpcap packet capture library.
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, which is a collection of Python
classes for constructing and dissecting network
packets.
Packet Capturing using pcapy example
pcapyPktCapture1.py
pcapyPktCapture1.py
pcapyEx1.py
pcapyEx1.py
pcapyDumper.py
pcapyDumper.pybinary-zone.com 49
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
Basic URL Request
import urllib2
response =
urllib2.urlopen('http://pythonforbeginners.com/')
print response.info()
html = response.read()
response.close()

binary-zone.com Cited 53
[3]
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
Scapy Overview Cont.
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


Dont need to be a Python Guru to use Scapy!

binary-zone.com 57
Scapy Basics - 1
Supported protocols:
>>>
>>> ls()
ls()

Details about a specific protocol:


>>>
>>> ls(TCP)
ls(TCP)

Available commands/functions:
>>>
>>> lsc()
lsc()

binary-zone.com 58
Scapy Basics - 2
Crafting a SYN/ACK Packet
>>>
>>> pkt
pkt =
= IP(dst="192.168.122.101")
>>>
>>> pkt
pkt /=
/= TCP(dport=80,
TCP(dport=80, flags="SA")
flags="SA")

Crafting ICMP Host Unreachable Packet


>>>
>>> pkt
pkt =
= IP(dst="192.168.122.101")
>>>
>>> pkt
pkt /=
/= ICMP(type=3,code=1)
ICMP(type=3,code=1)

binary-zone.com 59
Scapy Basics - 3
Single Line:
ICMP echo request Packet
>>>
>>> mypkt
mypkt =
= IP(dst="192.168.122.101")
IP(dst="192.168.122.101")
/ICMP(code=0,type=8)
/ICMP(code=0,type=8)

TCP FIN, Port 22, Random Source Port, and


Random Seq#
>>>
>>> mypkt
mypkt == IP(dst="192.168.122.101")
IP(dst="192.168.122.101")
/TCP(dport=22,sport=RandShort(),seq=RandShort(),flags=
/TCP(dport=22,sport=RandShort(),seq=RandShort(),flags=
"F")
"F")

binary-zone.com 60
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 61
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,unans
ans,unans =
= srp(packet)
srp(packet)

binary-zone.com 62
Displaying Packets
Get a summary of each packet:
>>>
>>> pkts.summary()
pkts.summary()

Get the whole packet list:


>>>
>>> pkts.show()
pkts.show()

binary-zone.com 63
Scapy Host Discovery
>>> ans,unans =
srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst="192.168
.122.0/24"),timeout=2)

>>> ans.summary(lambda(s,r): r.sprintf("Ether:


%Ether.src% \t\t Host: %ARP.psrc%"))

binary-zone.com 64
Scapy Port Scanning
TCP SYN Scanner
>>>
>>> sr1(IP(dst="192.168.122.101")
sr1(IP(dst="192.168.122.101")
/TCP(dport=90,flags="S"))
/TCP(dport=90,flags="S"))

>>>
>>> a,u
a,u =
= sr(IP(dst="192.168.122.101")
sr(IP(dst="192.168.122.101")
/TCP(dport=(80,100),flags="S"))
/TCP(dport=(80,100),flags="S"))

>>>
>>> a.summary(lambda(s,r):
a.summary(lambda(s,r): r.sprintf("Port: %TCP.sport% \t\t
Flags:
Flags: %TCP.flags%"))

binary-zone.com 65
Scapy Sniffing - 1
Scapy has powerful capabilities to capture and
analyze packets.
Configure the network interface to sniff packets
from:
>>>
>>> conf.iface="eth0
conf.iface="eth0

Configure
Configure the scapy sniffer to sniff only 20 packets
>>>
>>> pkts=sniff(count=20)
pkts=sniff(count=20)

binary-zone.com 66
Scapy Sniffing - 2
Sniff packets and stop after a defined time:
>>>
>>> pkts=sniff(count=100,timeout=60)
pkts=sniff(count=100,timeout=60)

Sniff only packets based on a filter:


>>>
>>> pkts
pkts = sniff(count=100,filter="tcp
sniff(count=100,filter="tcp port
port 80")
80")

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

What is that doing ???

binary-zone.com 68
Exporting Packets
Sometimes it is very useful to save the captured
packets in a PCAP file for future work:
>>>
>>> wrpcap(file1.cap",
wrpcap(file1.cap", 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.com 69
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
Create your own tools
>>> def handler(packet):
hexdump(packet.payload)

>>> sniff(count=20, prn=handler)

>>> def handler2(packet):


sendp(packet)

>>> sniff(count=20, prn=handler2)

binary-zone.com 71
Yesman
#!/usr/bin/env
#!/usr/bin/env python python
import
import sys sys
from
from scapy.all
scapy.all import
import **
def
def findSYN(p):
findSYN(p): sniff(prn=find
flags
flags = = p.sprintf("%TCP.flags%")
p.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
i.dst == ip.src
ip.src
i.src
i.src == ip.dst
ip.dst
tt =
= TCP()
TCP() #
# Outgoing
Outgoing TCP
TCP Segment
Segment
t.flags
t.flags == "SA"
"SA"
t.dport
t.dport = = tcp.sport
tcp.sport
t.sport
t.sport = = tcp.dport
tcp.dport
t.seq
t.seq = = tcp.ack
tcp.ack
new_ack
new_ack = = tcp.seq
tcp.seq +
+ 11
print
print ("SYN/ACK
("SYN/ACK sent
sent to
to ",i.dst,":",t.dport)
",i.dst,":",t.dport)
send(i/t)
send(i/t)
binary-zone.com 72
Others (not categorized
yet!)
Adding Time Delay
Delay for 5 seconds
>>>
>>> import
import 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.
time.sleep(60)
time.sleep(60)

http://stackoverflow.com/questions/510348/how-can-i-make-a-time-delay-in-python

binary-zone.com 74
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.socket(socket.AF_INET,
socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.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.connect((host,port))
s.connect((host,port))
data
data == s.recv(1024)
s.recv(1024)
s.send(payload
s.send(payload +\n)
+\n)
s.close
s.close

binary-zone.com 75
Python Tools for
Penetration Testers
Network Tools
Scapy:
Scapy: send,
send, sniff
sniff and
and dissect
dissect and
and forge
forge network
network packets.
packets. Usable
Usable
interactively
interactively or or as
as aa library
library
pypcap,
pypcap, 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,
routines, including
including interface
interface lookup
lookup and
and
Ethernet
Ethernet frame
frame transmission
transmission
dpkt:
dpkt: fast,
fast, simple
simple packet
packet creation/parsing,
creation/parsing, 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.
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,
sniffing, IP
IP defragmentation,
defragmentation, 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, enumerate
enumerate subdomains
subdomains on on aa target
target domain
domain
through
through aa wordlist
wordlist
Mallory,
Mallory, extensible
extensible TCP/UDP
TCP/UDP man-in-the-middle
man-in-the-middle proxy,proxy, 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.com Cited [5] 77
Debugging and Reverse
Engineering Tools
Paimei:
Paimei: reverse engineering framework,
framework, includes
includes PyDBG,
PyDBG,
PIDA,
PIDA, pGRAPH
pGRAPH
Immunity
Immunity Debugger:
Debugger: scriptable
scriptable GUI and
and command
command line
debugger
debugger
mona.py:
mona.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,
language, allowing
allowing scripts to run
run in
in IDA
IDA Pro
Pro
PyEMU:
PyEMU: fully
fully scriptable
scriptable IA-32
IA-32 emulator,
emulator, 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.com Cited [5] 78
Debugging and Reverse
Engineering Tools Cont.
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, and also
arbitrary
arbitrary addresses within the the executable
executable filefile in
in memory
memory
diStorm:
diStorm: disassembler
disassembler library
library for
for AMD64,
AMD64, licensed
licensed under
under
the
the BSD
BSD license
python-ptrace:
python-ptrace: debugger
debugger usingusing ptrace
ptrace (Linux,
(Linux, 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, 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


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,
TAOF, (The Art of Fuzzing) including ProxyFuzz, 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.com Cited [5] 80


Fuzzing Tools Cont.
Mistress:
Mistress: probe file
file formats
formats on on the
the fly
fly and
and protocols
protocols with
with
malformed
malformed data, 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, fuzzed file
systems,
systems, 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).
textual). Define your data structures
in
in a
a declarative
declarative manner
manner
binary-zone.com Cited [5] 81
Web Tools
Requests:
Requests: elegant
elegant and simple HTTP library, 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.
Supports
Supports automated
automated Web testing
Ghost.py:
Ghost.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.com Cited [5] 82


Web Tools Cont.
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;
engine; 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,
SSL-capable, intercepting
intercepting HTTP
HTTP proxy.
proxy. 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.com Cited [5] 83


Forensic Tools
Volatility: extract digital artifacts from volatile
memory (RAM) samples
LibForensics: library for developing digital
forensics applications
TrIDLib, identify file types from their binary
signatures. Now includes Python binding
aft: Android forensic toolkit

Lots of others which youll see them very soon ;)

binary-zone.com Cited [5] 84


Malware Analysis Tools
pyew:
pyew: command
command line hexadecimal
hexadecimal editor and disassembler,
mainly
mainly to analyze malware
Exefilter:
Exefilter: filter
filter file
file formats
formats in
in e-mails,
e-mails, web pages
pages or
or files.
files.
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,
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.com Cited [5] 85


PDF Tools
Didier Stevens' PDF tools: analyse, identify and
create PDF files (includes PDFiD, pdf-parser and
make-pdf and mPDF)
Opaf: Open PDF Analysis Framework. Converts
PDF to an XML tree that can be analyzed and
modified.
Origapy: Python wrapper for the Origami Ruby
module which sanitizes PDF files
pyPDF: pure Python PDF toolkit: extract info,
spilt, merge, crop, encrypt, decrypt...
PDFMiner: extract text from PDF files
python-poppler-qt4: Python binding for the
Poppler PDF library, including Qt4 support Cited [5] 86
binary-zone.com
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
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,
Modules, 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,
Sockets, pcapy,
pcapy, etc
etc
Using
Using Python
Python to
to work
work with
with the
the Web
Web (urllib, 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
Citation of Used Work
[1]
[1] Keith Dixon, @Tazdrumm3r,
http://tazdrumm3r.wordpress.com/
http://tazdrumm3r.wordpress.com/
[2]
[2] Python
Python Comic,
Comic, http://xkcd.com/353/,
http://xkcd.com/353/,
[3]
[3] Live Packet
Packet Capture
Capture in Python
Python with
with pcapy,
pcapy,
http://snipplr.com/view/3579/live-packet-capture-in-python-
http://snipplr.com/view/3579/live-packet-capture-in-python-
with-pcapy/
with-pcapy/
[4]
[4] How
How toto use
use urllib2
urllib2 in
in Python,
Python,
http://www.pythonforbeginners.com/python-on-the-
http://www.pythonforbeginners.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,
testers,
http://www.dirk-loss.de/python-tools.htm
http://www.dirk-loss.de/python-tools.htm

binary-zone.com 90
References
[1]
[1] Coding
Coding for
for Penetration
Penetration Testers
Testers Book,
Book,
[2]
[2] Violent
Violent Python
Python Book,
Book,
[3]
[3] Scapy
Scapy Documentation,
Documentation, http://www.secdev.org/projects/scapy/doc/
http://www.secdev.org/projects/scapy/doc/
[4]
[4] Python,
Python, http://www.python.org/
http://www.python.org/
[5]
[5] Python
Python Infosec
Infosec tools,
tools, http://www.dirk-loss.de/python-tools.htm
http://www.dirk-loss.de/python-tools.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,
Analysis,
http://www.sans.org/reading_room/whitepapers/incident/grow-foren
http://www.sans.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,
Docs, http://docs.python.org/
http://docs.python.org/
[8]
[8] Python
Python Tutorial,
Tutorial, http://www.tutorialspoint.com/python/index.htm
http://www.tutorialspoint.com/python/index.htm
[9]
[9] pcapy,
pcapy,
http://corelabs.coresecurity.com/index.php?module=Wiki&acti
http://corelabs.coresecurity.com/index.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,
Python,
http://www.voidspace.org.uk/python/articles/authentication.shtml
http://www.voidspace.org.uk/python/articles/authentication.shtml
[11]
[11] Justin
Justin Searle,
Searle, Python
Python Basics
Basics for
for Web
Web App
App Pentesters,
Pentesters,
InGuardians
InGuardians IncInc
binary-zone.com 91

Вам также может понравиться