SlideShare a Scribd company logo
Python For Ethical Hackers
Mohammad reza Kamalifard
Ethical Hacker
Ethical Hacker
Penetration Tester
Ethical Hacker
Penetration Tester
Ethical Hacker = Penetration Tester
Why Python?
Easy to learn
Easy to use
Clean syntax and code readability
Rich set of libraries
Tons of tools already written
Rapid prototyping – POC ( proof on concept )
Why Python?
Easy to learn
Easy to use
Clean syntax and code readability
Rich set of libraries
Tons of tools already written
Rapid prototyping – POC ( proof on concept )
Why Python?
Easy to learn
Easy to use
Clean syntax and code readability
Rich set of libraries
Tons of tools already written
Rapid prototyping – POC ( proof on concept )
Why Python?
Easy to learn
Easy to use
Clean syntax and code readability
Rich set of libraries
Tons of tools already written
Rapid prototyping – POC ( proof on concept )
Why Python?
Easy to learn
Easy to use
Clean syntax and code readability
Rich set of libraries
Tons of tools already written
Rapid prototyping – POC ( proof on concept )
Why Python?
Easy to learn
Easy to use
Clean syntax and code readability
Rich set of libraries
Tons of tools already written
Rapid prototyping – POC ( proof on concept )
Who is using Python
Core Impact – Comprehensive penetration testing solution
Immunity CANVAS – Exploit development framework
W3AF – Web Application Attack and Audit Framework
Sqlmap – Automatic SQL injection tool
Immunity Debugger – Powerful Debugger
Peach – Fuzzer
Sulley – Fully automated and unattended fuzzing framework
Paimei – Reverse engineering framework
Scapy – Packet manipulation tool
Easy File Handling
>>>
>>>
>>>
>>>

file_add = 'c:/users/reza/desktop/passwords.txt'
file_dis = open(file_add, 'r')
emails = file_dis.readlines()
for email in emails:
print email

shahed_soltani@yahoo.com
sir1_kabir@ymail.com
peyman_dabir@yahoo.com
sanaz808@iran.ir
gity_hashemi@yahoo.com
zeuos63@yahoo.com
seyedali_rezaie@datasec.ir
.
.
.
Requests
Library to deal with HTTP : HTTP for Humans
>>> import requests
>>> requests.get('http://kamalifard.ir')
<Response [200]>
>>> r = _
>>> r.headers
CaseInsensitiveDict({'content-length': '771', 'contentencoding': 'gzip', 'accept-ranges': 'bytes', 'vary': 'AcceptEncoding', 'server': 'Apache/2.2.16 (Debian)', 'last-modified':
'Sat, 21 Sep 2013 05:19:57 GMT', 'etag': '"15b565-62b4e6ddf0165940"', 'date': 'Sun, 27 Oct 2013 14:23:54 GMT',
'content-type': 'text/html'})
>>> r.text
u'<!doctype html>n<html lang="en">n<head>nt<meta
charset="UTF-8">nt<title>Mohammad reza
Kamalifard</title>nt<link rel="stylesheet" href="style.css"
/>nn</head>n<body>nt<div class="wrap">ntt<h1>Mohammad
reza Kamalifard</h1>ntt<p>Software
Basic fuzzer
import requests as req
>>>
>>>
>>>
>>>
>>>
...
...

url = 'http://kamalifard.ir/'
file_add = 'c:/users/reza/desktop/dirss.txt'
file_dis = open(file_add, 'r')
dirs= file_dis.readlines()
for x in dirs:
resp = req.get(url + x)
html = resp.text
hashlib
>>> import hashlib
>>> hashlib.algorithms
('md5', 'sha1', 'sha224', 'sha256', 'sha384',
'sha512')
>>> m = hashlib.md5()
>>> m.update('reza')
>>> m.digest()
'xbbx98xb1xd0xb5#xd5xe7x83xf91Urwx02xb6'
>>> m.hexdigest()
'bb98b1d0b523d5e783f931550d7702b6'
>>>
Sockets
• TCP and UDP Sockets
• Regular Servers and Clients
• Raw Sockets
• Sniffing and Injection
Port Scanner
import socket
def connScan(tgtHost, tgtPort):
try:
tcp_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
tcp_socket.connect((tgtHost, tgtPort))
tcp_socket.send(‘PyCon2013rn')
results = tcp_socket.recv(100)
print '%d/tcp open' % tgtPort
print str(results)
except:
print '%d/tcp closed' % tgtPort
finally:
tcp_socket.close()
ECHO Server
import socket
tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,
1)
tcp_socket.bind(('127.0.0.1', 8000))
tcp_socket.listen(2)
print 'Waiting for client ...'
(client, (ip, port)) = tcp_socket.accept()
print 'Revived connection from : ', ip
print 'Starting ECHO output...'
data = 'dummy'
while len(data):
data = client.recv(2048)
print 'Client send : ', data
client.send(data)
client.close()
Client
import socket
import sys
if len(sys.argv) < 3 :
print 'Please Enter address and port'
sys.exit()
tcp_socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
tcp_socket.connect((sys.argv[1], int(sys.argv[2])))
while True:
userInput = raw_input('Please Enter a Message! : ')
tcp_socket.send(userInput)
print 'Server Send back : ' +
str(tcp_socket.recv(2048))
tcp_socket.close()
-----Client----python client.py 127.0.0.1 8000
Please Enter a Message! : Salam
Server Send back : Salam
Please Enter a Message! : WELCOME TO PYCON 2013!
Server Send back : WELCOME TO PYCON 2013!
Please Enter a Message! :
-----Server----Waiting for client ...
Revived connection from : 127.0.0.1
Starting ECHO output...
Client send : Salam
Client send : WELCOME TO PYCON 2013!
Client send :
Closing Connection
SocketServer Framework
• Framework in Python to create TCP and UDP servers
• Does all the basic steps for you in the background
• Comes in handy if you want to create a server to lure a

client and
• analyze its behavior
SocketServer Framework
import SocketServer
class EchoHandler(SocketServer.BaseRequestHandler):
def handle(self):
print 'Got Connection from : ', self.client_address
data = 'dummy'
while len(data):
data = self.request.recv(1024)
print 'Client sent :' + data
self.request.send(data)
print 'client left‘
server_address = ('127.0.0.1', 9050)
server = SocketServer.TCPServer(server_address, EchoHandler)
server.serve_forever()
Nmap
import nmap
tgtHost = '192.168.1.254'
tgtPort = '80'
nmapScan = nmap.PortScanner()
nmapScan.scan(tgtHost, tgtPort)
state=nmapScan[tgtHost]['tcp'][int(tgtPort)]['state']
print tgtHost + ' tcp/' +tgtPort + ' ' +state
Simple HTTP Server
import SocketServer
import SimpleHTTPServer
httpServer = SocketServer.TCPServer(('', 8080),
SimpleHTTPServer.SimpleHTTPRequestHandler)
httpServer.serve_forever()
Raw Sockets
import struct, socket, binascii
rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,
socket.htons(0x800))
pkt = rawSocket.recvfrom(2048)
ethernetHeader = pkt[0][0:14]
eth_hdr = struct.unpack('!6s6s2s', ethernetHeader)
binascii.hexlify(eth_hdr[0])
binascii.hexlify(eth_hdr[1])
binascii.hexlify(eth_hdr[2])
ipHeader = pkt[0][14:34]
ip_hdr = struct.unpack('!12s4s4s', ipHeader)
print 'Source IP address : ' + socket.inet_ntoa(ip_hdr[1])
print 'Destination IP address : ' + socket.inet_ntoa(ip_hdr[2])
tcpHeader = pkt[0][34:54]
tcp_hdr = struct.unpack('!HH16s', tcpHeader)
Packet Injection with Raw Sockets
import socket
import struct
rawSocket = socket.socket(socket.PF_PACKET,
socket.SOCK_RAW,
socket.htons(0x800))
rawSocket.bind(('wlan0', socket.htons(0x800)))
packet = struct.pack('!6s6s2s',
'xaaxaaxaaxaaxaaxaa',
'xbbxbbxbbxbbxbbxbb' , 'x08x00')
rawSocket.send(packet + 'Welcome to PYCON')
Scapy
• Interactive packet manipulation tool
• Forge or decode packets
• Wide number of protocols
• Send Packet on the wire
• Capture Packet
• Match requests and replies
Scapy
reza@kamalifard$ sudo scapy
WARNING: No route found for IPv6 destination :: (no
default route?)
Welcome to Scapy (2.2.0)
>>>ls()
ARP : ARP
DHCP : DHCP options
DNS : DNS
GPRS : GPRSdummy
L2TP : None
PPPoE : PPP over Ethernet
[...]
Sniff
>>> p = sniff(count = 5)
>>> p
<Sniffed: TCP:5 UDP:0 ICMP:0 Other:0>
>>> p.show()
0000
0001
0002
0003
0004
>>>

Ether
Ether
Ether
Ether
Ether

/
/
/
/
/

IP
IP
IP
IP
IP

/
/
/
/
/

TCP
TCP
TCP
TCP
TCP

46.165.248.173:4948 > 192.168.1.2:47981 PA/ Raw
192.168.1.2:47981 > 46.165.248.173:4948 A
127.0.0.1:mmcc > 127.0.0.1:48852 PA / Raw
127.0.0.1:mmcc > 127.0.0.1:48852 PA / Raw
127.0.0.1:48852 > 127.0.0.1:mmcc A
Create Packet
>>> pkt = IP(dst ='192.168.1.254')/TCP(dport = 25)
>>> pkt
<IP frag=0 proto=tcp dst=192.168.1.254 |<TCP
dport=smtp |>>
>>> print pkt
E(@�~�����P
e
>>> str(pkt)
'Ex00x00(x00x01x00x00@x06xf6~xc0xa8x01x02
xc0xa8x01xfex00x14x00x19x00x00x00x00x00
x00x00x00Px02 x00x0bex00x00'
>>> pkt.show()
###[ IP ]###
version= 4
ihl= None
tos= 0x0
len= None
id= 1
flags=
frag= 0
ttl= 64
proto= tcp
chksum= None
src= 192.168.1.2
dst= 192.168.1.254
options
###[ TCP ]###
sport= ftp_data
dport= smtp
seq= 0
ack= 0
dataofs= None
reserved= 0
flags= S
window= 8192
chksum= None
urgptr= 0
options= {}
>>>
###[ IP ]###
version= 4
ihl= None
tos= 0x0
len= None
id= 1
flags=
frag= 0
ttl= 64
proto= tcp
chksum= None
src= 192.168.1.2
dst= 192.168.1.254
options
###[ TCP ]###
sport= ftp_data
dport= smtp
seq= 0
ack= 0
dataofs= None
reserved= 0
flags= S
window= 8192
chksum= None
urgptr= 0
options= {}
Send Packets
>>> pkt = IP(dst = 'google.com')/ICMP()/'Welcome to
PyCon'
>>> pkt
<IP frag=0 proto=icmp dst=Net('google.com') |<ICMP
|<Raw load='Welcome to PyCon' |>>>
>>>
>>> pkt.show()
###[ IP ]###
version= 4
ihl= None
tos= 0x0
len= None
id= 1
flags=
frag= 0
ttl= 64
proto= icmp
chksum= None
src= 192.168.1.2
dst= Net('google.com')
options
###[ ICMP ]###
type= echo-request
code= 0
chksum= None
id= 0x0
seq= 0x0
###[ Raw ]###
load= 'Welcome to PyCon'
>>>send(pkt)
.
send 1 packets.
Send and Recive
>>> resp = sr(pkt)
Begin emission:
Finished to send 1 packets.
*
Received 1 packets, got 1 answers, remaining 0 packets
>>> resp
(<Results: TCP:0 UDP:0 ICMP:1 Other:0>, <Unanswered: TCP:0
UDP:0 ICMP:0 Other:0>)
>>> resp[0][0]
(<IP frag=0 proto=icmp dst=216.239.32.20 |<ICMP |<Raw
load='Welcome to PyCon' |>>>, <IP version=4L ihl=5L tos=0x0
len=44 id=0 flags= frag=0L ttl=33 proto=icmp chksum=0xdf23
src=216.239.32.20 dst=192.168.1.2 options=[] |<ICMP type=echoreply code=0 chksum=0xea37 id=0x0 seq=0x0 |<Raw load='Welcome
to PyCon' |<Padding load='x00x00' |>>>>)
>>>
>>> '?'
‫ﺣﺪود ۰۵۷ ﻣﯿﻠﯿﻮن ﻧﻔﺮ ﮔﺮﺳﻨﻪ در ﺟﻬﺎن وﺟﻮد دارد!‬
‫ﮏ ﻧﻔﺮ از ﻫﺮ ۸ ﻧﻔﺮ‬

‫ﺑـﺮﻧـﺎﻣـﻪ ﺟـﻬـﺎﻧـﯽ ﻏـﺬا‬
‫ﻣﺒﺎرزه ﺟﻬﺎﻧﯽ ﺑﺎ ﮔﺮﺳﻨﮕﯽ‬

‫‪fa.wfp.org‬‬
>>> '?'
>>> print contact_me
>>> ?
>>> print contact_me
Mohammad Reza Kamalifard
Kamalifard@datasec.ir
http://www.linkedin.com/in/itmard
My Python Courses :
http://www.webamooz.ir/home/courses/python-for-ethicalhackers-1/
http://www.webamooz.ir/home/courses/python-for-ethicalhackers-2/
This work is product of DataSec Middle East(Ammniat Dadehaa Khavare miane) and licensed
under the Creative Commons Attribution-NoDerivs 3.0 Unported License.
Copyright 2013 Mohammad Reza Kamalifard
All rights reserved.

http://kamalifard.ir
http://www.webamooz.ir/home/courses/python-for-ethical-hackers-1/
http://www.webamooz.ir/home/courses/python-for-ethical-hackers-2/

More Related Content

PDF
Introduction to Flask Micro Framework
PPT
Mining Ruby Gem vulnerabilities for Fun and No Profit.
PDF
Relayd: a load balancer for OpenBSD
PDF
Node.js API 서버 성능 개선기
PDF
Roll Your Own API Management Platform with nginx and Lua
PPTX
Fun with exploits old and new
ODP
Php in 2013 (Web-5 2013 conference)
PDF
Ruby HTTP clients comparison
Introduction to Flask Micro Framework
Mining Ruby Gem vulnerabilities for Fun and No Profit.
Relayd: a load balancer for OpenBSD
Node.js API 서버 성능 개선기
Roll Your Own API Management Platform with nginx and Lua
Fun with exploits old and new
Php in 2013 (Web-5 2013 conference)
Ruby HTTP clients comparison

What's hot (20)

PDF
Using ngx_lua in UPYUN
PDF
OWASP Proxy
PPT
Why and How Powershell will rule the Command Line - Barcamp LA 4
PPTX
Powershell Demo Presentation
PDF
Securing Prometheus exporters using HashiCorp Vault
PDF
Bootstrapping multidc observability stack
PDF
服务框架: Thrift & PasteScript
PDF
Learning Dtrace
PDF
Python RESTful webservices with Python: Flask and Django solutions
PPTX
Zephir - A Wind of Change for writing PHP extensions
PDF
Tornado Web Server Internals
PPTX
Tornado web
PDF
Information security programming in ruby
PPTX
Socket programming with php
PDF
Beyond Phoenix
PPTX
How to discover 1352 Wordpress plugin 0days in one hour (not really)
PDF
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
ZIP
Nginx + Tornado = 17k req/s
PPT
On UnQLite
PDF
LibreSSL, one year later
Using ngx_lua in UPYUN
OWASP Proxy
Why and How Powershell will rule the Command Line - Barcamp LA 4
Powershell Demo Presentation
Securing Prometheus exporters using HashiCorp Vault
Bootstrapping multidc observability stack
服务框架: Thrift & PasteScript
Learning Dtrace
Python RESTful webservices with Python: Flask and Django solutions
Zephir - A Wind of Change for writing PHP extensions
Tornado Web Server Internals
Tornado web
Information security programming in ruby
Socket programming with php
Beyond Phoenix
How to discover 1352 Wordpress plugin 0days in one hour (not really)
The worst Ruby codes I’ve seen in my life - RubyKaigi 2015
Nginx + Tornado = 17k req/s
On UnQLite
LibreSSL, one year later

Similar to Pycon - Python for ethical hackers (20)

PDF
us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-La...
PPT
Socket programming-tutorial-sk
PDF
WebRTC 101 - How to get started building your first WebRTC application
PPT
05 module managing your network enviornment
PDF
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
PDF
Rhebok, High Performance Rack Handler / Rubykaigi 2015
PDF
Non-blocking I/O, Event loops and node.js
PDF
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
KEY
fog or: How I Learned to Stop Worrying and Love the Cloud
KEY
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
PDF
Reverse engineering Swisscom's Centro Grande Modem
PDF
Memcache as udp traffic reflector
PDF
Osol Pgsql
PPTX
Practical non blocking microservices in java 8
PDF
Network Test Automation - Net Ops Coding 2015
PDF
Handy Networking Tools and How to Use Them
PDF
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
PDF
CEPH中的QOS技术
PPT
Socket Programming Tutorial 1227317798640739 8
us-17-Tsai-A-New-Era-Of-SSRF-Exploiting-URL-Parser-In-Trending-Programming-La...
Socket programming-tutorial-sk
WebRTC 101 - How to get started building your first WebRTC application
05 module managing your network enviornment
اسلاید اول جلسه یازدهم کلاس پایتون برای هکرهای قانونی
Rhebok, High Performance Rack Handler / Rubykaigi 2015
Non-blocking I/O, Event loops and node.js
A New Era of SSRF - Exploiting URL Parser in Trending Programming Languages! ...
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
Reverse engineering Swisscom's Centro Grande Modem
Memcache as udp traffic reflector
Osol Pgsql
Practical non blocking microservices in java 8
Network Test Automation - Net Ops Coding 2015
Handy Networking Tools and How to Use Them
Capturing NIC and Kernel TX and RX Timestamps for Packets in Go
CEPH中的QOS技术
Socket Programming Tutorial 1227317798640739 8

More from Mohammad Reza Kamalifard (20)

PDF
PDF
Tehlug 26 Nov 2013 Hackers,Cyberwarfare and Online privacy
PDF
جلسه دوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PDF
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PDF
جلسه چهارم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PDF
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
PDF
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
PDF
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
PDF
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
PDF
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PDF
جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
PDF
اسلاید اول جلسه اول دوره پاییز کلاس پایتون برای هکرهای قانونی
PDF
اسلاید دوم جلسه یازدهم کلاس پایتون برای هکر های قانونی
PDF
اسلاید ارائه دوم جلسه ۱۰ کلاس پایتون برای هکر های قانونی
PDF
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
PDF
اسلاید ارائه سوم جلسه ۱۰ کلاس پایتون برای هکر های قانونی
PDF
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
PDF
اسلاید اول جلسه هشتم کلاس پایتون برای هکرهای قانونی
PDF
اسلاید سوم جلسه هفتم کلاس پایتون برای هکرهای قانونی
PDF
اسلاید دوم جلسه هفتم کلاس پایتون برای هکرهای قانونی
Tehlug 26 Nov 2013 Hackers,Cyberwarfare and Online privacy
جلسه دوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه چهارم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه پنجم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۱
جلسه ششم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲- ارائه ۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه اول پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
اسلاید اول جلسه اول دوره پاییز کلاس پایتون برای هکرهای قانونی
اسلاید دوم جلسه یازدهم کلاس پایتون برای هکر های قانونی
اسلاید ارائه دوم جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه اول جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید ارائه سوم جلسه ۱۰ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید اول جلسه هشتم کلاس پایتون برای هکرهای قانونی
اسلاید سوم جلسه هفتم کلاس پایتون برای هکرهای قانونی
اسلاید دوم جلسه هفتم کلاس پایتون برای هکرهای قانونی

Recently uploaded (20)

PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Open folder Downloads.pdf yes yes ges yes
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Basic Mud Logging Guide for educational purpose
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PPTX
Cell Structure & Organelles in detailed.
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
2.FourierTransform-ShortQuestionswithAnswers.pdf
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PPTX
GDM (1) (1).pptx small presentation for students
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Business Ethics Teaching Materials for college
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
The Final Stretch: How to Release a Game and Not Die in the Process.
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
TR - Agricultural Crops Production NC III.pdf
Open folder Downloads.pdf yes yes ges yes
Renaissance Architecture: A Journey from Faith to Humanism
Basic Mud Logging Guide for educational purpose
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Cell Structure & Organelles in detailed.
Insiders guide to clinical Medicine.pdf
Week 4 Term 3 Study Techniques revisited.pptx
2.FourierTransform-ShortQuestionswithAnswers.pdf
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
O7-L3 Supply Chain Operations - ICLT Program
FourierSeries-QuestionsWithAnswers(Part-A).pdf
GDM (1) (1).pptx small presentation for students
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Business Ethics Teaching Materials for college
STATICS OF THE RIGID BODIES Hibbelers.pdf
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
The Final Stretch: How to Release a Game and Not Die in the Process.
human mycosis Human fungal infections are called human mycosis..pptx

Pycon - Python for ethical hackers

  • 1. Python For Ethical Hackers Mohammad reza Kamalifard
  • 4. Ethical Hacker Penetration Tester Ethical Hacker = Penetration Tester
  • 5. Why Python? Easy to learn Easy to use Clean syntax and code readability Rich set of libraries Tons of tools already written Rapid prototyping – POC ( proof on concept )
  • 6. Why Python? Easy to learn Easy to use Clean syntax and code readability Rich set of libraries Tons of tools already written Rapid prototyping – POC ( proof on concept )
  • 7. Why Python? Easy to learn Easy to use Clean syntax and code readability Rich set of libraries Tons of tools already written Rapid prototyping – POC ( proof on concept )
  • 8. Why Python? Easy to learn Easy to use Clean syntax and code readability Rich set of libraries Tons of tools already written Rapid prototyping – POC ( proof on concept )
  • 9. Why Python? Easy to learn Easy to use Clean syntax and code readability Rich set of libraries Tons of tools already written Rapid prototyping – POC ( proof on concept )
  • 10. Why Python? Easy to learn Easy to use Clean syntax and code readability Rich set of libraries Tons of tools already written Rapid prototyping – POC ( proof on concept )
  • 11. Who is using Python Core Impact – Comprehensive penetration testing solution Immunity CANVAS – Exploit development framework W3AF – Web Application Attack and Audit Framework Sqlmap – Automatic SQL injection tool Immunity Debugger – Powerful Debugger Peach – Fuzzer Sulley – Fully automated and unattended fuzzing framework Paimei – Reverse engineering framework Scapy – Packet manipulation tool
  • 12. Easy File Handling >>> >>> >>> >>> file_add = 'c:/users/reza/desktop/passwords.txt' file_dis = open(file_add, 'r') emails = file_dis.readlines() for email in emails: print email shahed_soltani@yahoo.com sir1_kabir@ymail.com peyman_dabir@yahoo.com sanaz808@iran.ir gity_hashemi@yahoo.com zeuos63@yahoo.com seyedali_rezaie@datasec.ir . . .
  • 13. Requests Library to deal with HTTP : HTTP for Humans >>> import requests >>> requests.get('http://kamalifard.ir') <Response [200]> >>> r = _ >>> r.headers CaseInsensitiveDict({'content-length': '771', 'contentencoding': 'gzip', 'accept-ranges': 'bytes', 'vary': 'AcceptEncoding', 'server': 'Apache/2.2.16 (Debian)', 'last-modified': 'Sat, 21 Sep 2013 05:19:57 GMT', 'etag': '"15b565-62b4e6ddf0165940"', 'date': 'Sun, 27 Oct 2013 14:23:54 GMT', 'content-type': 'text/html'}) >>> r.text u'<!doctype html>n<html lang="en">n<head>nt<meta charset="UTF-8">nt<title>Mohammad reza Kamalifard</title>nt<link rel="stylesheet" href="style.css" />nn</head>n<body>nt<div class="wrap">ntt<h1>Mohammad reza Kamalifard</h1>ntt<p>Software
  • 14. Basic fuzzer import requests as req >>> >>> >>> >>> >>> ... ... url = 'http://kamalifard.ir/' file_add = 'c:/users/reza/desktop/dirss.txt' file_dis = open(file_add, 'r') dirs= file_dis.readlines() for x in dirs: resp = req.get(url + x) html = resp.text
  • 15. hashlib >>> import hashlib >>> hashlib.algorithms ('md5', 'sha1', 'sha224', 'sha256', 'sha384', 'sha512') >>> m = hashlib.md5() >>> m.update('reza') >>> m.digest() 'xbbx98xb1xd0xb5#xd5xe7x83xf91Urwx02xb6' >>> m.hexdigest() 'bb98b1d0b523d5e783f931550d7702b6' >>>
  • 16. Sockets • TCP and UDP Sockets • Regular Servers and Clients • Raw Sockets • Sniffing and Injection
  • 17. Port Scanner import socket def connScan(tgtHost, tgtPort): try: tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.connect((tgtHost, tgtPort)) tcp_socket.send(‘PyCon2013rn') results = tcp_socket.recv(100) print '%d/tcp open' % tgtPort print str(results) except: print '%d/tcp closed' % tgtPort finally: tcp_socket.close()
  • 18. ECHO Server import socket tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) tcp_socket.bind(('127.0.0.1', 8000)) tcp_socket.listen(2) print 'Waiting for client ...' (client, (ip, port)) = tcp_socket.accept() print 'Revived connection from : ', ip print 'Starting ECHO output...' data = 'dummy' while len(data): data = client.recv(2048) print 'Client send : ', data client.send(data) client.close()
  • 19. Client import socket import sys if len(sys.argv) < 3 : print 'Please Enter address and port' sys.exit() tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp_socket.connect((sys.argv[1], int(sys.argv[2]))) while True: userInput = raw_input('Please Enter a Message! : ') tcp_socket.send(userInput) print 'Server Send back : ' + str(tcp_socket.recv(2048)) tcp_socket.close()
  • 20. -----Client----python client.py 127.0.0.1 8000 Please Enter a Message! : Salam Server Send back : Salam Please Enter a Message! : WELCOME TO PYCON 2013! Server Send back : WELCOME TO PYCON 2013! Please Enter a Message! : -----Server----Waiting for client ... Revived connection from : 127.0.0.1 Starting ECHO output... Client send : Salam Client send : WELCOME TO PYCON 2013! Client send : Closing Connection
  • 21. SocketServer Framework • Framework in Python to create TCP and UDP servers • Does all the basic steps for you in the background • Comes in handy if you want to create a server to lure a client and • analyze its behavior
  • 22. SocketServer Framework import SocketServer class EchoHandler(SocketServer.BaseRequestHandler): def handle(self): print 'Got Connection from : ', self.client_address data = 'dummy' while len(data): data = self.request.recv(1024) print 'Client sent :' + data self.request.send(data) print 'client left‘ server_address = ('127.0.0.1', 9050) server = SocketServer.TCPServer(server_address, EchoHandler) server.serve_forever()
  • 23. Nmap import nmap tgtHost = '192.168.1.254' tgtPort = '80' nmapScan = nmap.PortScanner() nmapScan.scan(tgtHost, tgtPort) state=nmapScan[tgtHost]['tcp'][int(tgtPort)]['state'] print tgtHost + ' tcp/' +tgtPort + ' ' +state
  • 24. Simple HTTP Server import SocketServer import SimpleHTTPServer httpServer = SocketServer.TCPServer(('', 8080), SimpleHTTPServer.SimpleHTTPRequestHandler) httpServer.serve_forever()
  • 25. Raw Sockets import struct, socket, binascii rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x800)) pkt = rawSocket.recvfrom(2048) ethernetHeader = pkt[0][0:14] eth_hdr = struct.unpack('!6s6s2s', ethernetHeader) binascii.hexlify(eth_hdr[0]) binascii.hexlify(eth_hdr[1]) binascii.hexlify(eth_hdr[2]) ipHeader = pkt[0][14:34] ip_hdr = struct.unpack('!12s4s4s', ipHeader) print 'Source IP address : ' + socket.inet_ntoa(ip_hdr[1]) print 'Destination IP address : ' + socket.inet_ntoa(ip_hdr[2]) tcpHeader = pkt[0][34:54] tcp_hdr = struct.unpack('!HH16s', tcpHeader)
  • 26. Packet Injection with Raw Sockets import socket import struct rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x800)) rawSocket.bind(('wlan0', socket.htons(0x800))) packet = struct.pack('!6s6s2s', 'xaaxaaxaaxaaxaaxaa', 'xbbxbbxbbxbbxbbxbb' , 'x08x00') rawSocket.send(packet + 'Welcome to PYCON')
  • 27. Scapy • Interactive packet manipulation tool • Forge or decode packets • Wide number of protocols • Send Packet on the wire • Capture Packet • Match requests and replies
  • 28. Scapy reza@kamalifard$ sudo scapy WARNING: No route found for IPv6 destination :: (no default route?) Welcome to Scapy (2.2.0) >>>ls() ARP : ARP DHCP : DHCP options DNS : DNS GPRS : GPRSdummy L2TP : None PPPoE : PPP over Ethernet [...]
  • 29. Sniff >>> p = sniff(count = 5) >>> p <Sniffed: TCP:5 UDP:0 ICMP:0 Other:0> >>> p.show() 0000 0001 0002 0003 0004 >>> Ether Ether Ether Ether Ether / / / / / IP IP IP IP IP / / / / / TCP TCP TCP TCP TCP 46.165.248.173:4948 > 192.168.1.2:47981 PA/ Raw 192.168.1.2:47981 > 46.165.248.173:4948 A 127.0.0.1:mmcc > 127.0.0.1:48852 PA / Raw 127.0.0.1:mmcc > 127.0.0.1:48852 PA / Raw 127.0.0.1:48852 > 127.0.0.1:mmcc A
  • 30. Create Packet >>> pkt = IP(dst ='192.168.1.254')/TCP(dport = 25) >>> pkt <IP frag=0 proto=tcp dst=192.168.1.254 |<TCP dport=smtp |>> >>> print pkt E(@�~�����P e >>> str(pkt) 'Ex00x00(x00x01x00x00@x06xf6~xc0xa8x01x02 xc0xa8x01xfex00x14x00x19x00x00x00x00x00 x00x00x00Px02 x00x0bex00x00'
  • 31. >>> pkt.show() ###[ IP ]### version= 4 ihl= None tos= 0x0 len= None id= 1 flags= frag= 0 ttl= 64 proto= tcp chksum= None src= 192.168.1.2 dst= 192.168.1.254 options ###[ TCP ]### sport= ftp_data dport= smtp seq= 0 ack= 0 dataofs= None reserved= 0 flags= S window= 8192 chksum= None urgptr= 0 options= {} >>>
  • 32. ###[ IP ]### version= 4 ihl= None tos= 0x0 len= None id= 1 flags= frag= 0 ttl= 64 proto= tcp chksum= None src= 192.168.1.2 dst= 192.168.1.254 options
  • 33. ###[ TCP ]### sport= ftp_data dport= smtp seq= 0 ack= 0 dataofs= None reserved= 0 flags= S window= 8192 chksum= None urgptr= 0 options= {}
  • 34. Send Packets >>> pkt = IP(dst = 'google.com')/ICMP()/'Welcome to PyCon' >>> pkt <IP frag=0 proto=icmp dst=Net('google.com') |<ICMP |<Raw load='Welcome to PyCon' |>>> >>> >>> pkt.show()
  • 35. ###[ IP ]### version= 4 ihl= None tos= 0x0 len= None id= 1 flags= frag= 0 ttl= 64 proto= icmp chksum= None src= 192.168.1.2 dst= Net('google.com') options
  • 36. ###[ ICMP ]### type= echo-request code= 0 chksum= None id= 0x0 seq= 0x0 ###[ Raw ]### load= 'Welcome to PyCon' >>>send(pkt) . send 1 packets.
  • 37. Send and Recive >>> resp = sr(pkt) Begin emission: Finished to send 1 packets. * Received 1 packets, got 1 answers, remaining 0 packets >>> resp (<Results: TCP:0 UDP:0 ICMP:1 Other:0>, <Unanswered: TCP:0 UDP:0 ICMP:0 Other:0>) >>> resp[0][0] (<IP frag=0 proto=icmp dst=216.239.32.20 |<ICMP |<Raw load='Welcome to PyCon' |>>>, <IP version=4L ihl=5L tos=0x0 len=44 id=0 flags= frag=0L ttl=33 proto=icmp chksum=0xdf23 src=216.239.32.20 dst=192.168.1.2 options=[] |<ICMP type=echoreply code=0 chksum=0xea37 id=0x0 seq=0x0 |<Raw load='Welcome to PyCon' |<Padding load='x00x00' |>>>>) >>>
  • 39. ‫ﺣﺪود ۰۵۷ ﻣﯿﻠﯿﻮن ﻧﻔﺮ ﮔﺮﺳﻨﻪ در ﺟﻬﺎن وﺟﻮد دارد!‬ ‫ﮏ ﻧﻔﺮ از ﻫﺮ ۸ ﻧﻔﺮ‬ ‫ﺑـﺮﻧـﺎﻣـﻪ ﺟـﻬـﺎﻧـﯽ ﻏـﺬا‬ ‫ﻣﺒﺎرزه ﺟﻬﺎﻧﯽ ﺑﺎ ﮔﺮﺳﻨﮕﯽ‬ ‫‪fa.wfp.org‬‬
  • 40. >>> '?' >>> print contact_me
  • 41. >>> ? >>> print contact_me Mohammad Reza Kamalifard Kamalifard@datasec.ir http://www.linkedin.com/in/itmard My Python Courses : http://www.webamooz.ir/home/courses/python-for-ethicalhackers-1/ http://www.webamooz.ir/home/courses/python-for-ethicalhackers-2/
  • 42. This work is product of DataSec Middle East(Ammniat Dadehaa Khavare miane) and licensed under the Creative Commons Attribution-NoDerivs 3.0 Unported License. Copyright 2013 Mohammad Reza Kamalifard All rights reserved. http://kamalifard.ir http://www.webamooz.ir/home/courses/python-for-ethical-hackers-1/ http://www.webamooz.ir/home/courses/python-for-ethical-hackers-2/