Python 使用dpkt分析数据包

上周Lightless放了一题数据包分析的题,挺有意思的

题目地址: http://7xscw6.com1.z0.glb.clouddn.com/hahaha.pcapng

数据包分析这部分很简单,随便看看可以看出来这是个用sqlmap去艹服务器的数据包,然后flag使用盲注注出来的.

最简单的方法就是手工把盲注的包提取出来,手工分析得到flag.

不过我觉得手工太low了,所以有了这篇文章,使用Python的dpkt包对pcap包进行分析.

直接先贴代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#!/usr/bin/env Python
# -*- coding:utf-8 -*-

from dpkt.ethernet import Ethernet
import dpkt
import re
import urllib

result = []
f = file("test.pcapng")
pcap = dpkt.pcapng.Reader(f)
(ts, buf) = pcap.next()
while True:
http_data = Ethernet(buf).data.data.data
request = dpkt.http.Request(http_data)
(ts, buf) = pcap.next()
http_data = Ethernet(buf).data.data.data
response = dpkt.http.Response(http_data)
payload = urllib.unquote(request.uri)
entity_body = response.entity_body
if "ctf.flag " in payload:
if "123456" in entity_body:
result.append({"payload": payload, "result": True})
else:
result.append({"payload": payload, "result": False})
try:
(ts, buf) = pcap.next()
except StopIteration:
break
number = 1
flag = ""
c = 0
for y in result:
[(x, h)] = re.findall("1\),(\d+).+>(\d+)", y['payload'])
x, h = int(x), int(h)
if x > number:
number = x
flag += chr(c)
else:
if y['result']:
c = h + 1

print flag

因为dpkt包的setfilter方法是没用的,感觉是作者还没把dpkt写完

1
2
def setfilter(self, value, optimize=1):
return NotImplementedError

所以我用wireshark过滤出了http包:http://7xscw6.com1.z0.glb.clouddn.com/test.pcapng

然后由于http包实体内容使用了gzip压缩,所以我魔改了http.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Response(Message):
"""Hypertext Transfer Protocol Response."""
__hdr_defaults__ = {
'version': '1.0',
'status': '200',
'reason': 'OK'
}
__proto = 'HTTP'

def __init__(self, *args, **kwargs):
Message.__init__(self, *args, **kwargs)
try:
import gzip
enti = gzip.Gzip(self.body)
self.entity_body = gzip.Gzip.decompress(enti)
except:
self.entity_body = ""

加了一个__init__

然后,代码短,也容易看懂,不过还有需要优化的地方,不过跑这题确是没问题的

Python 使用dpkt分析数据包

https://nobb.site/2016/04/04/0x17/

Author

Hcamael

Posted on

2016-04-04

Updated on

2017-08-08

Licensed under