Skip to content

Commit 04de5a2

Browse files
committed
Initial commit
0 parents  commit 04de5a2

File tree

14 files changed

+3711
-0
lines changed

14 files changed

+3711
-0
lines changed

.gitignore

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
*~
2+
.*.swp
3+
*.pyc
4+
*.egg-info
5+
.DS_Store
6+
.tox
7+
.pytest_cache

LICENSE

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2018 Fox-IT Security Research Team <srt@fox-it.com>
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

README.md

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# dissect.cstruct
2+
Structure parsing in Python made easy. With cstruct, you can write C-like structures and use them to parse binary data, either as file-like objects or bytestrings.
3+
4+
Parsing binary data with cstruct feels familiar and easy. No need to learn a new syntax or the quirks of a new parsing library before you can start parsing data. The syntax isn't strict C but it's compatible with most common structure definitions. You can often use structure definitions from open-source C projects and use them out of the box with little to no changes. Need to parse an EXT4 super block? Just copy the structure definition from the Linux kernel source code. Need to parse some custom file format? Write up a simple structure and immediately start parsing data, tweaking the structure as you go.
5+
6+
By design cstruct is incredibly simple. No complex syntax, filters, pre- or postprocessing steps. Just structure parsing.
7+
8+
## Installation
9+
```
10+
pip install dissect.cstruct
11+
```
12+
13+
## Usage
14+
All you need to do is instantiate a new cstruct instance and load some structure definitions in there. After that you can start using them from your Python code.
15+
16+
```python
17+
from dissect import cstruct
18+
19+
# Default endianness is LE, but can be configured using a kwarg or setting the 'endian' attribute
20+
# e.g. cstruct.cstruct(endian='>') or cparser.endian = '>'
21+
cparser = cstruct.cstruct()
22+
cparser.load("""
23+
#define SOME_CONSTANT 5
24+
25+
enum Example : uint16 {
26+
A, B = 0x5, C
27+
};
28+
29+
struct some_struct {
30+
uint8 field_1;
31+
char field_2[SOME_CONSTANT];
32+
char field_3[field_1 & 1 * 5]; // Some random expression to calculate array length
33+
Example field_4[2];
34+
};
35+
""")
36+
37+
data = b'\x01helloworld\x00\x00\x06\x00'
38+
result = cparser.some_struct(data) # Also accepts file-like objects
39+
assert result.field_1 == 0x01
40+
assert result.field_2 == b'hello'
41+
assert result.field_3 == b'world'
42+
assert result.field_4 == [cparser.Example.A, cparser.Example.C]
43+
44+
assert cparser.Example.A == 0
45+
assert cparser.Example.C == 6
46+
assert cparser.Example(5) == cparser.Example.B
47+
48+
assert result.dumps() == data
49+
50+
# You can also instantiate structures from Python by using kwargs
51+
# Note that array sizes are not enforced
52+
instance = cparser.some_struct(field_1=5, field_2='lorem', field_3='ipsum', field_4=[cparser.Example.B, cparser.Example.A])
53+
assert instance.dumps() == b'\x05loremipsum\x05\x00\x00\x00'
54+
```
55+
56+
By default, all structures are compiled into classes that provide optimised performance. You can disable this by passing a `compiled=False` keyword argument to the `.load()` call. You can also inspect the resulting source code by accessing the source attribute of the structure: `print(cparser.some_struct.source)`.
57+
58+
More examples can be found in the `examples` directory.
59+
60+
## Features
61+
### Structure parsing
62+
Write simple C-like structures and use them to parse binary data, as can be seen in the examples.
63+
64+
### Type parsing
65+
Aside from loading structure definitions, any of the supported types can be used individually for parsing data. For example, the following is all supported:
66+
67+
```python
68+
from dissect import cstruct
69+
cs = cstruct.cstruct()
70+
# Default endianness is LE, but can be configured using a kwarg or setting the attribute
71+
# e.g. cstruct.cstruct(endian='>') or cs.endian = '>'
72+
assert cs.uint32(b'\x05\x00\x00\x00') == 5
73+
assert cs.uint24[2](b'\x01\x00\x00\x02\x00\x00') == [1, 2] # You can also parse arrays using list indexing
74+
assert cs.char[None](b'hello world!\x00') == b'hello world!' # A list index of None means null terminated
75+
```
76+
77+
### Parse bit fields
78+
Bit fields are supported as part of structures. They are properly aligned to their boundaries.
79+
80+
```python
81+
bitdef = """
82+
struct test {
83+
uint16 a:1;
84+
uint16 b:1; # Read 2 bits from an uint16
85+
uint32 c; # The next field is properly aligned
86+
uint16 d:2;
87+
uint16 e:3;
88+
};
89+
"""
90+
bitfields = cstruct.cstruct()
91+
bitfields.load(bitdef)
92+
93+
d = b'\x03\x00\xff\x00\x00\x00\x1f\x00'
94+
a = bitfields.test(d)
95+
96+
assert a.a == 0b1
97+
assert a.b == 0b1
98+
assert a.c == 0xff
99+
assert a.d == 0b11
100+
assert a.e == 0b111
101+
assert a.dumps() == d
102+
```
103+
104+
### Enums
105+
The API to access enum members and their values is similar to that of the native Enum type in Python 3. Functionally, it's best comparable to the IntEnum type.
106+
107+
### Custom types
108+
You can implement your own types by subclassing `BaseType` or `RawType`, and adding them to your cstruct instance with `addtype(name, type)`
109+
110+
### Custom definition parsers
111+
Don't like the C-like definition syntax? Write your own syntax parser!
112+
113+
## Todo
114+
- Nested structure definitions
115+
- Unions

dissect/cstruct/__init__.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
from dissect.cstruct.cstruct import (
2+
cstruct,
3+
ctypes,
4+
dumpstruct,
5+
hexdump,
6+
Instance,
7+
PointerInstance,
8+
Parser,
9+
RawType,
10+
BaseType,
11+
Error,
12+
ParserError,
13+
CompilerError,
14+
ResolveError,
15+
NullPointerDereference,
16+
)
17+
18+
__all__ = [
19+
"cstruct",
20+
"ctypes",
21+
"dumpstruct",
22+
"hexdump",
23+
"Instance",
24+
"PointerInstance",
25+
"Parser",
26+
"RawType",
27+
"BaseType",
28+
"Error",
29+
"ParserError",
30+
"CompilerError",
31+
"ResolveError",
32+
"NullPointerDereference",
33+
]

0 commit comments

Comments
 (0)