/
getdents.py
62 lines (45 loc) · 1.4 KB
/
getdents.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
from __future__ import absolute_import
from __future__ import division
from pwnlib.context import context
from pwnlib.util.fiddling import hexdump
from pwnlib.util.packing import unpack
class linux_dirent(object):
def __init__(self, buf):
n = context.bytes
# Long
self.d_ino = unpack(buf[:n])
buf=buf[n:]
# Long
self.d_off = unpack(buf[:n])
buf=buf[n:]
# Short
self.d_reclen = unpack(buf[:2], 16)
buf=buf[2:]
# Name
self.d_name = buf[:buf.index(b'\x00')].decode('utf-8')
def __len__(self):
return self.d_reclen # 2 * context.bytes + 2 + len(self.d_name) + 1
def __str__(self):
return "inode=%i %r" % (self.d_ino, self.d_name)
def dirents(buf):
"""unpack_dents(buf) -> list
Extracts data from a buffer emitted by getdents()
Arguments:
buf(str): Byte array
Returns:
A list of filenames.
Example:
>>> data = '5ade6d010100000010002e0000000004010000000200000010002e2e006e3d04092b6d010300000010007461736b00045bde6d010400000010006664003b3504'
>>> data = unhex(data)
>>> print(dirents(data))
['.', '..', 'fd', 'task']
"""
d = []
while buf:
try:
ent = linux_dirent(buf)
except ValueError:
break
d.append(ent.d_name)
buf = buf[len(ent):]
return sorted(d)