root@cript#
Python and Scapy
root@cript#
Python Introduction
root@cript#
Basics: Variables
Python is a dynamically-typed language: value="Hello" value=84/2 The last computed value is represented with _: 84/2 value=_ Concatenation occurs with + (or ,): value="Monty"+"Python" value="Monty","Python" Repetition occurs with *: value="Hello"*5
root@cript#
Basics: Printing
Use either set of quotation marks, but be consistent print"Hello" print'Hello' print"'Hello',saysJohn" print'"Hello",saysJohn'
Multi-line strings are easy, use triple quotes (e.g. """)
print""" Thisisamultilinesentence, whichI'dliketoprint. """
root@cript#
Basics: Strings
String indexing is very flexible in Python: value="CRIPT" value[0]#"C" value[1:3]#"RI" value[:3]#"CRI" value[3:]#"PT" value[1]#"T"(1:lastchar) value[2:]#"PT"(2:2ndlastchar) value[1:1]#"RIP"
root@cript#
Basics: Strings
Strings also have many other useful operations:
value="RIPITCRIPT" [Link]("RIP")#2 [Link]("RIP")#0 [Link]("RIP")#8 [Link]("RIP")#True [Link]("IPT")#True value2="for{0}years"#Python3.0+ [Link]("99")#'for99years' value3="for%(0)dyears"#Python2.6 value3%{"val":99}#'for99years'
root@cript#
Basics: Strings
Strings also have many other useful operations:
value="CRIPT" value2="12" value3="hitherejim" [Link]()#'cript' [Link]()#True [Link]()#True [Link](8)#'CRIPT' [Link](8)#'CRIPT' [Link]("")#['hi','there','jim']
root@cript#
Data Structures: Lists
Lists are similar to strings, but lists elements are writable
list=['i','am','hungry'] list[1:]#['am','hungry'],likestrings list=['b','e'] [Link]('f')#list:['b','e','f'] [Link](0,'a')#list:['a','b','e','f'] [Link]('b')#list:['a','e','f'] [Link]()#'f',list:['a','e'] [Link](0)#'a',list:['e']
root@cript#
Data Structures: Lists
List iteration is easy:
list=[1,2,3] foriteminlist: print'item:',item
So is list comprehension:
#allx,suchthatxisin[0..10] list1=[xforxinrange(10)] list2=[xforxinlist1if(x%2)==0andx<5]
root@cript#
Data Structures: Stacks
The list operations make it easy to implement stacks:
stack=[] [Link](1) [Link](2) [Link](3) [Link]()#3 [Link]()#2 [Link]()#1
root@cript#
Data Structures: Queues
The list operations make it easy to implement stacks
...and queues:
queue=[] [Link](1) [Link](2) [Link](3) [Link](0)#1 [Link](0)#2 [Link](0)#3
root@cript#
Data Structures: Dictionaries
Most languages have dictionaries (aka hash tables, property lists):
params={"numQueens":8,"bandwidth":3000} params["numQueens"]#8
root@cript#
Control Structures: if
Conditionals are similar to those used in scripting:
ifvalue==0: print"Thevalueiszero" elifvalue<0: print"Thevalueisnegative" else: print"Thevalueispositive"
root@cript#
Control Structures: for
Loops follow a similar syntactic structure:
list=range(10) forxinlist: print"Thevalueis{0}.".format(x) sentence='iwenttothestore' list=[Link]() fori,xinenumerate(list): printi,x forxinsorted(set(list)): printx
root@cript#
Control Structures: try
try/except/else is like try/catch/finally in Java:
userinput=raw_input("Enteranum:") value=0 try: value=int(userinput) exceptValueError: print"Invalidnumber!" else print"Value:",value
root@cript#
Modularity: functions
Functions can be defined in the traditional way:
deftimes2(n): """Thisfunctionreturnsthe numbertimestwo""" returnn*2
... or using Lambda notation
times2=lambdan:n*2#n,n2
root@cript#
Modularity: classes
Classes can be defined in the traditional way:
classChat: serverIP="" serverPort=8888 def__init__(self,ip,port): serverIP=ip serverPort=port defsendMessage(self,message): ifhasattr(self,'nickname'): [Link]+":"+message else: print"Anonymous:"+message
root@cript#
Modularity: classes
Inheritance is also possible:
classInternetChat(Chat): defsendMessage(self,message): print"Internetmessaginggoeshere!"
root@cript#
Modularity: objects
Objects can be instantiated, but are also dynamic (like other types in Python):
>>>myChat=Chat("[Link]",7777) >>>[Link]("Hello") Anonymous:Hello >>>[Link]="rfortier" >>>[Link]("Hello") rfortier:Hello >>>[Link] >>>[Link]("Hello") Anonymous:Hello
root@cript#
Extras: RegEx Matching
Regular expressions are powerful, yet very easy in Python:
importre [Link]('a[ab]*b','abaaaaabbbbb') #output:['ab','aabb']
root@cript#
Packet Construction with Scapy
root@cript#
Scapy
Scapy can be used to:
Explore network protocols and headers Write network-enabled applications Construct packets for security purposes e.g. Spoofed packets
root@cript#
Scapy: Basics
To see the supported protocols: ls() To find out details about a specific protocol: ls(DNS) To see the available commands (i.e. Python functions): lsc()
root@cript#
Scapy: Basics
Here is some sample code showing how to:
Create a TCP segment, inside an IP datagram Display the TCP segment Send it to some host ([Link]), port 22 Display any response
sendPacket=IP(dst='[Link]')/TCP(dport=22, sport=RandShort(),seq=RandShort()) sendPacket.show2() response=sr1(sendPacket) print"Receivedaresponse:" [Link]()
root@cript#
Scapy: Creating Packets
You can create packets individually or in groups:
packet=IP(dst='[Link]')/TCP(dport=22, sport=RandShort(),seq=RandShort()) packets=IP(dst='[Link]/29')/TCP(dport=[22,80], sport=RandShort(),seq=RandShort()) [pforpinpackets]
root@cript#
Scapy: Sending and Receiving
There are several ways to send (and receive) packets in Scapy:
packet=IP(dst='[Link]')/TCP(dport=22, sport=RandShort(),seq=RandShort()) //sendpacketatlayer3 send(packet) //sendpacketatlayer2 sendp(Ether()/packet) //sendpacket(L3)andreceiveoneresponse response=sr1(packet) //sendpacket(L3)andreceiveallresponses answered,unanswered=sr(packet)
root@cript#
Scapy: Ping
We have just about enough information to write our own ping function (default ICMP type is 'echo'):
defping(host,repeat=3): packet=IP(dst=host)/ICMP()
forxinrange(repeat):
response=sr1(packet) response.show2()
root@cript#
Scapy: TCP Ping
...and ping using TCP on port 22:
defsshping(host,repeat=3): packet=IP(dst=host)/TCP(dport=22, sport=RandShort(),seq=RandShort())
forxinrange(repeat):
response=sr1(packet) response.show2()
root@cript#
Scapy: Traceroute
...and traceroute:
defmytraceroute(host,maxttl=8): ipps=IP(dst=host,ttl=(1,maxttl)) ans,unans=sr(ipps/ICMP()) forsent,rcvdinans: [Link],[Link]
root@cript#
Scapy: Sniffing
...and a packet sniffer:
results=sniff(count=10) [Link]()
root@cript#
Scapy: DNS Resolution
...and a resolver:
defresolve(host): dns=DNS(rd=1,qd=DNSQR(qname=host)) response=sr1(IP(dst='[Link]')/UDP()/dns); [Link](DNS): answer=[Link](DNS).an [Link]()
root@cript#
Scapy: Port Scanning
...and a port scanner (and SYN scan, in this case):
defsynscan(host): ports=range(1000) ip=IP(dst=host) tcp=TCP(dport=ports,flags="S") ans,unans=sr(ip/tcp) forsent,rcvdinans: [Link](TCP): [Link](TCP).flags&2: [Link]
root@cript#
Scapy: ARP Poisoning
...and ARP poisoning:
defarppoison(target,spoofed_ip,mac): packet=ARP() [Link]=2 [Link]=mac [Link]=spoofed_ip [Link]='[Link]' [Link]=target send(packet)
root@cript#
Scapy: Other Possibilities
There is a whole lot more than Scapy can do:
DNS poisoning Customized port scanning Fuzzing network protocols Sending exploits (incl. Shellcode) via TCP, UDP IP spoofing (except for sequence number prediction) Network applications