Commit 801ab5f
committed
fix: fix UB in the scan mem blocks API
The iterators on memory blocks is unsafe as it uses pointers on freed
objects.
The `mem_block_iterator_first` and `mem_block_iterator_next` both
have this code:
```
let mut mem_block = ...;
match mem_block.as_mut() {
Some(mem_block) {
context.mem_block.write(mem_block.as_yara());
context.mem_block.as_mut_ptr()
}
...
}
```
This is unsafe because the "as_yara" method creates an object that keeps
a pointer to the mem_block object, which is freed just afterwards.
This can be seen easily by running the tests in valgrind, where the
tests using the mem blocks api have this error:
```
==23549== Invalid read of size 8
==23549== at 0x1CAAD4: yara::internals::iterator::mem_block_fetch_data (iterator.rs:160)
==23549== by 0x1E8A06: yr_scanner_scan_mem_blocks (scanner.c:479)
==23549== by 0x152458: yara::internals::scan::scanner_scan_mem_blocks_inner (scan.rs:269)
==23549== by 0x1521BF: yara::internals::scan::scanner_scan_mem_blocks (scan.rs:248)
...
```
The `mem_block_fetch_data` dereferences the pointer to the freed object,
leading to an invalid read.
This is fixed in this commit by avoiding to keep this pointer, and
instead directly storing the pointer to the slice data, since this is
the value we want to return in `mem_block_fetch_data`.
I won't pretend that this makes this API **safe**, since this has to use
the yara memory block iterator API, which is very unsafe in how it is
declared, and its safety depends on knowledge on how those objects are
used internally in YARA. But at least valgrind no longer complains :)1 parent 14ba7c9 commit 801ab5f
1 file changed
+14
-21
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
16 | 16 | | |
17 | 17 | | |
18 | 18 | | |
19 | | - | |
20 | | - | |
21 | | - | |
22 | | - | |
23 | | - | |
24 | | - | |
25 | | - | |
| 19 | + | |
26 | 20 | | |
27 | 21 | | |
28 | 22 | | |
29 | | - | |
30 | | - | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
31 | 29 | | |
32 | 30 | | |
33 | 31 | | |
| |||
119 | 117 | | |
120 | 118 | | |
121 | 119 | | |
122 | | - | |
123 | | - | |
| 120 | + | |
| 121 | + | |
124 | 122 | | |
125 | | - | |
| 123 | + | |
126 | 124 | | |
127 | 125 | | |
128 | 126 | | |
| |||
134 | 132 | | |
135 | 133 | | |
136 | 134 | | |
137 | | - | |
138 | | - | |
| 135 | + | |
| 136 | + | |
139 | 137 | | |
140 | | - | |
| 138 | + | |
141 | 139 | | |
142 | 140 | | |
143 | 141 | | |
| |||
151 | 149 | | |
152 | 150 | | |
153 | 151 | | |
154 | | - | |
155 | | - | |
156 | | - | |
157 | | - | |
158 | 152 | | |
159 | | - | |
160 | | - | |
| 153 | + | |
161 | 154 | | |
0 commit comments