scapy学习笔记(2)--包及包的定义

转载请注明:@小五义:http://www.cnblogs/xiaowuyi

一、包

      包(Packet)是TCP/IP协议通信传输中的数据单位,一般也称“数据包”。其主要由“目的IP地址”、“源IP地址”、“净载数据”等部分构成,包括包头和包体,包头是固定长度,包体的长度不定,各字段长度固定,双方的请求数据包和应答数据包的包头结构是一致的,不同的是包体的定义。 数据包的结构与我们平常写信非常类似,目的IP地址是说明这个数据包是要发给谁的,相当于收信人地址;源IP地址是说明这个数据包是发自哪里的,相当于发信人地址;而净载数据相当于信件的内容。包沿着不同的路径在一个或多个网络中传输,并且在目的地重新组合。

二、常见的几个关键字

ICMP:Internet Control Message Protocol(Internet控制报文协议)的缩写。它是TCP/IP协议族的一个子协议,用于在IP主机、路由器之间传递控制消息。控制消息是指网络通不通、主机是否可达、路由是否可用等网络本身的消息。这些控制消息虽然并不传输用户数据,但是对于用户数据的传递起着重要的作用。

DST:目的地址

SRC:源地址

TTL:(Time To Live ) 生存时间,指定数据包被路由器丢弃之前允许通过的网段数量。TTL是IP协议包中的一个值,它告诉网络,数据包在网络中的时间是否太长而应被丢弃。有很多原因使包在一定时间内不能被传递到目的地。解决方法就是在一段时间后丢弃这个包,然后给发送者一个报文,由发送者决定是否要重发。TTL的初值通常是系统缺省值,是包头中的8位的域。TTL的最初设想是确定一个时间范围,超过此时间就把包丢弃。由于每个路由器都至少要把TTL域减一,TTL通常表示包在被丢弃前最多能经过的路由器个数。当记数到0时,路由器决定丢弃该包,并发送一个ICMP报文给最初的发送者。

三、scapy中常用的几个命令

1、ls():作用也是list show,可以显示所有支持的数据包对象。ls()可以不带参数,也可以带参数,参数可是任何一个具体的包。下面列出了一部分结果:

>>> from scapy.all import *
WARNING: No route found for IPv6 destination :: (no default route?)
>>> ls()
ARP        : ARP
ASN1_Packet : None
BOOTP      : BOOTP
CookedLinux : cooked linux
DHCP       : DHCP options
DHCP6      : DHCPv6 Generic Message)
DHCP6OptAuth : DHCP6 Option - Authentication
DHCP6OptBCMCSDomains : DHCP6 Option - BCMCS Domain Name List
DHCP6OptBCMCSServers : DHCP6 Option - BCMCS Addresses List
DHCP6OptClientFQDN : DHCP6 Option - Client FQDN
DHCP6OptClientId : DHCP6 Client Identifier Option
DHCP6OptDNSDomains : DHCP6 Option - Domain Search List option
DHCP6OptDNSServers : DHCP6 Option - DNS Recursive Name Server
DHCP6OptElapsedTime : DHCP6 Elapsed Time Option
DHCP6OptGeoConf : 

列出TCP的所有对象:
>>> from scapy.all import *
WARNING: No route found for IPv6 destination :: (no default route?)
>>> ls(TCP)
sport      : ShortEnumField       = (20)
dport      : ShortEnumField       = (80)
seq        : IntField             = (0)
ack        : IntField             = (0)
dataofs    : BitField             = (None)
reserved   : BitField             = (0)
flags      : FlagsField           = (2)
window     : ShortField           = (8192)
chksum     : XShortField          = (None)
urgptr     : ShortField           = (0)
options    : TCPOptionsField      = ({})

  列出任意包的情况如:

>>> a=IP(ttl=5)
>>> a.src
'127.0.0.1'
>>> a
<IP  ttl=5 |>
>>> a.dst
'127.0.0.1'
>>> a.dst="192.168.0.1"
>>> a
<IP  ttl=5 dst=192.168.0.1 |>
>>> ls(a)
version    : BitField             = 4               (4)
ihl        : BitField             = None            (None)
tos        : XByteField           = 0               (0)
len        : ShortField           = None            (None)
id         : ShortField           = 1               (1)
flags      : FlagsField           = 0               (0)
frag       : BitField             = 0               (0)
ttl        : ByteField            = 5               (64)
proto      : ByteEnumField        = 0               (0)
chksum     : XShortField          = None            (None)
src        : Emph                 = '27.214.7.85'   (None)
dst        : Emph                 = '192.168.0.1'   ('127.0.0.1')
options    : PacketListField      = []              ([])
>>>

2、lsc()列出所有函数。如:

>>> lsc()
arpcachepoison      : Poison target's cache with (your MAC,victim's IP) couple
arping              : Send ARP who-has requests to determine which hosts are up
bind_layers         : Bind 2 layers on some specific fields' values
corrupt_bits        : Flip a given percentage or number of bits from a string
corrupt_bytes       : Corrupt a given percentage or number of bytes from a string
defrag              : defrag(plist) -> ([not fragmented], [defragmented],
defragment          : defrag(plist) -> plist defragmented as much as possible 
dyndns_add          : Send a DNS add message to a nameserver for "name" to have a new "rdata"
dyndns_del          : Send a DNS delete message to a nameserver for "name"
etherleak           : Exploit Etherleak flaw
fragment            : Fragment a big IP datagram
fuzz                : Transform a layer into a fuzzy layer by replacing some default values by random objects
getmacbyip          : Return MAC address corresponding to a given IP address
hexdiff             : Show differences between 2 binary strings
hexdump             : --
hexedit             : --
is_promisc          : Try to guess if target is in Promisc mode. The target is provided by its ip.
linehexdump         : --
ls                  : List  available layers, or infos on a given layer
promiscping         : Send ARP who-has requests to determine which hosts are in promiscuous mode
rdpcap              : Read a pcap file and return a packet list
send                : Send packets at layer 3
sendp               : Send packets at layer 2
sendpfast           : Send packets at layer 2 using tcpreplay for performance
sniff               : Sniff packets
split_layers        : Split 2 layers previously bound
sr                  : Send and receive packets at layer 3
sr1                 : Send packets at layer 3 and return only the first answer
srbt                : send and receive using a bluetooth socket
srbt1               : send and receive 1 packet using a bluetooth socket
srflood             : Flood and receive packets at layer 3
srloop              : Send a packet at layer 3 in loop and print the answer each time
srp                 : Send and receive packets at layer 2
srp1                : Send and receive packets at layer 2 and return only the first answer
srpflood            : Flood and receive packets at layer 2
srploop             : Send a packet at layer 2 in loop and print the answer each time
traceroute          : Instant TCP traceroute
tshark              : Sniff packets and print them calling pkt.show(), a bit like text wireshark
wireshark           : Run wireshark on a list of packets
wrpcap              : Write a list of packets to a pcap file

3、hide_defaults()方法,用来删除一些用户提供的那些和default value相同的项目

>>> a=IP()/TCP()
>>> b=IP(str(a))
>>> b
<IP  version=4L ihl=5L tos=0x0 len=40 id=1 flags= frag=0L ttl=64 proto=tcp chksum=0x7ccd src=127.0.0.1 dst=127.0.0.1 options=[] |<TCP  sport=ftp_data dport=http seq=0 ack=0 dataofs=5L reserved=0L flags=S window=8192 chksum=0x917c urgptr=0 |>>
>>> b.hide_defaults()
>>> b
<IP  ihl=5L len=40 frag=0 proto=tcp chksum=0x7ccd src=127.0.0.1 |<TCP  dataofs=5L chksum=0x917c |>>

4、display():display()方法可以简单查看当前packet的各个参数的取值情况,例子见下。

5、sprintf:输出某一层某个参数的取值,如果不存在就输出??,具体的format是:%[[mt][r],][layer[:nb].]field%,参数的具体信息请参看《Security Power Tools》146页或者http://wikicode.net。例:

>>> a=IP()/TCP()
>>> b=IP(str(a))
>>> b
<IP  version=4L ihl=5L tos=0x0 len=40 id=1 flags= frag=0L ttl=64 proto=tcp chksum=0x7ccd src=127.0.0.1 dst=127.0.0.1 options=[] |<TCP  sport=ftp_data dport=http seq=0 ack=0 dataofs=5L reserved=0L flags=S window=8192 chksum=0x917c urgptr=0 |>>
>>> b.hide_defaults()
>>> b
<IP  ihl=5L len=40 frag=0 proto=tcp chksum=0x7ccd src=127.0.0.1 |<TCP  dataofs=5L chksum=0x917c |>>
>>> a.sprintf("%IP.gabuzomeu%")
'??'

四、创建包

        scapy的包创建是按照网络接口层,互联网层,传输层,应用层四层参考模型来完成,各个层都有各自的创建函数,比如IP(),TCP(),UDP()等等,不同层之间通过“/”来连接。例如 ,接前面a的例子:

例1
>>> a=IP(ttl=5) >>> a.src '127.0.0.1' >>> a <IP ttl=5 |> >>> a.dst '127.0.0.1' >>> a.dst="192.168.0.1" >>> a <IP ttl=5 dst=192.168.0.1 |> >>> packet1=a >>> packet1 <IP ttl=5 dst=192.168.0.1 |> 例2
>>> packet2=IP(dst="192.168.0.1")/TCP(dport=80) 例3
>>> packet3=IP(dst="www.baidu.com")/ICMP() >>> packet3 <IP frag=0 proto=icmp dst=Net('www.baidu.com') |<ICMP |>> >>> ls(packet3) version : BitField = 4 (4) ihl : BitField = None (None) tos : XByteField = 0 (0) len : ShortField = None (None) id : ShortField = 1 (1) flags : FlagsField = 0 (0) frag : BitField = 0 (0) ttl : ByteField = 64 (64) proto : ByteEnumField = 1 (0) chksum : XShortField = None (None) src : Emph = '27.214.7.85' (None) dst : Emph = Net('www.baidu.com') ('127.0.0.1') options : PacketListField = [] ([]) -- type : ByteEnumField = 8 (8) code : MultiEnumField = 0 (0) chksum : XShortField = None (None) id : ConditionalField = 0 (0) seq : ConditionalField = 0 (0) ts_ori : ConditionalField = 4842323 (4842323) ts_rx : ConditionalField = 4842323 (4842323) ts_tx : ConditionalField = 4842323 (4842323) gw : ConditionalField = '0.0.0.0' ('0.0.0.0') ptr : ConditionalField = 0 (0) reserved : ConditionalField = 0 (0) addr_mask : ConditionalField = '0.0.0.0' ('0.0.0.0') unused : ConditionalField = 0 (0) 例4
>>> target="www.baidu.com/30" >>> ip=IP(dst=target) >>> ip <IP dst=Net('www.baidu.com/30') |> >>> ls(ip) version : BitField = 4 (4) ihl : BitField = None (None) tos : XByteField = 0 (0) len : ShortField = None (None) id : ShortField = 1 (1) flags : FlagsField = 0 (0) frag : BitField = 0 (0) ttl : ByteField = 64 (64) proto : ByteEnumField = 0 (0) chksum : XShortField = None (None) src : Emph = '27.214.7.85' (None) dst : Emph = Net('www.baidu.com/30') ('127.0.0.1') options : PacketListField = [] ([])
>>> IP().display()
###[ IP ]###
  version   = 4
  ihl       = None
  tos       = 0x0
  len       = None
  id        = 1
  flags     = 
  frag      = 0
  ttl       = 64
  proto     = ip
  chksum    = None
  src       = 127.0.0.1
  dst       = 127.0.0.1
  \options   \

>>> TCP().display()
###[ TCP ]###
  sport     = ftp_data
  dport     = http
  seq       = 0
  ack       = 0
  dataofs   = None
  reserved  = 0
  flags     = S
  window    = 8192
  chksum    = None
  urgptr    = 0
  options   = {}
这里的display()方法可以简单查看当前packet的各个参数的取值情况.

五、包的结构

      在Scapy中,scapy为各个层都写了类,使用时,只需要将其实例化,调用类的方法或者改变类的参数取值。如IP()没有传给它参数,那么它的参数就是默认的,如果传了就覆盖了默认值:

>>> a=IP()
>>> a.display()
###[ IP ]###
  version   = 4
  ihl       = None
  tos       = 0x0
  len       = None
  id        = 1
  flags     = 
  frag      = 0
  ttl       = 64
  proto     = ip
  chksum    = None
  src       = 127.0.0.1
  dst       = 127.0.0.1
  \options   \
>>> a=IP(dst="192.168.0.1")
>>> a.display()
###[ IP ]###
  version   = 4
  ihl       = None
  tos       = 0x0
  len       = None
  id        = 1
  flags     = 
  frag      = 0
  ttl       = 64
  proto     = ip
  chksum    = None
  src       = 27.214.7.**                  //(本机IP)
  dst       = 192.168.0.1
  \options   \

注意比较这两次display()的不同,第一次是默认值,第二次传入了“192.168.0.1”。

      "/"用来连接各层,如IP()/TCP()。如:

>>> IP()
<IP  |>
>>> IP()/TCP()
<IP  frag=0 proto=tcp |<TCP  |>>
>>> Ether()/IP()/TCP()
<Ether  type=0x800 |<IP  frag=0 proto=tcp |<TCP  |>>>
>>> IP()/TCP()/"GET / HTTP/1.0\r\n\r\n"
<IP  frag=0 proto=tcp |<TCP  |<Raw  load='GET / HTTP/1.0\r\n\r\n' |>>>
>>> Ether()/IP()/IP()/UDP()
<Ether  type=0x800 |<IP  frag=0 proto=ipencap |<IP  frag=0 proto=udp |<UDP  |>>>>
>>> IP(proto=55,ttl=10)/TCP()
<IP  frag=0 ttl=10 proto=55 |<TCP  |>>
具体的参数传递过程,在scapy文档中提供了图表,如下:


 


 

posted @ 2013-09-23 11:00  小五义  阅读(15272)  评论(0编辑  收藏  举报