|
| 1 | +// SPDX-License-Identifier: BSD-3 |
| 2 | +// SPDX-FileCopyrightText: 2025 Finder16 |
| 3 | +// SPDX-FileCopyrightText: 2025 Rot127 <unisono@quyllur.org> |
| 4 | + |
| 5 | +#include <stdint.h> |
| 6 | +#include <stdio.h> |
| 7 | +#include <stdlib.h> |
| 8 | + |
| 9 | +#include <capstone/platform.h> |
| 10 | +#include <capstone/capstone.h> |
| 11 | + |
| 12 | +static size_t big_skip(const uint8_t *code, size_t code_size, size_t offset, |
| 13 | + void *user_data) |
| 14 | +{ |
| 15 | + (void)code; |
| 16 | + (void)code_size; |
| 17 | + (void)offset; |
| 18 | + (void)user_data; |
| 19 | + return 1024; // larger than cs_insn.bytes (24) |
| 20 | +} |
| 21 | + |
| 22 | +/// Possible buffer overflow of cs_insn.bytes if number of skipped bytes |
| 23 | +/// is larger. |
| 24 | +/// Reported by Finder16. |
| 25 | +static void test_overflow_cs_insn_bytes() |
| 26 | +{ |
| 27 | + csh handle; |
| 28 | + if (cs_open(CS_ARCH_WASM, CS_MODE_LITTLE_ENDIAN, &handle) != |
| 29 | + CS_ERR_OK) { |
| 30 | + return; |
| 31 | + } |
| 32 | + cs_opt_skipdata skip = { .mnemonic = ".byte", |
| 33 | + .callback = big_skip, |
| 34 | + .user_data = NULL }; |
| 35 | + cs_option(handle, CS_OPT_SKIPDATA, CS_OPT_ON); |
| 36 | + cs_option(handle, CS_OPT_SKIPDATA_SETUP, (size_t)&skip); |
| 37 | + uint8_t buf[1024] = { 0 }; |
| 38 | + buf[0] = 0x06; // invalid WASM opcode to force skipdata path |
| 39 | + cs_insn *insn = NULL; |
| 40 | + // Overflowed cs_insn->bytes before the fix. |
| 41 | + cs_disasm(handle, buf, sizeof(buf), 0, 1, &insn); |
| 42 | + cs_free(insn, 1); |
| 43 | + cs_close(&handle); |
| 44 | + return; |
| 45 | +} |
| 46 | + |
| 47 | +/// Possible buffer overflow of cs_insn.bytes if number of skipped bytes |
| 48 | +/// is larger. |
| 49 | +/// Reported by Finder16. |
| 50 | +static void test_overflow_cs_insn_bytes_iter() |
| 51 | +{ |
| 52 | + csh handle; |
| 53 | + if (cs_open(CS_ARCH_WASM, CS_MODE_LITTLE_ENDIAN, &handle) != |
| 54 | + CS_ERR_OK) { |
| 55 | + return; |
| 56 | + } |
| 57 | + cs_opt_skipdata skip = { .mnemonic = ".byte", |
| 58 | + .callback = big_skip, |
| 59 | + .user_data = NULL }; |
| 60 | + cs_option(handle, CS_OPT_SKIPDATA, CS_OPT_ON); |
| 61 | + cs_option(handle, CS_OPT_SKIPDATA_SETUP, (size_t)&skip); |
| 62 | + uint64_t address = 0; |
| 63 | + uint8_t buf[1024] = { 0 }; |
| 64 | + const uint8_t *b = buf; |
| 65 | + size_t size = sizeof(buf); |
| 66 | + buf[0] = 0x06; // invalid WASM opcode to force skipdata path |
| 67 | + cs_insn *insn = cs_malloc(handle); |
| 68 | +; |
| 69 | + // Overflowed cs_insn->bytes before the fix. |
| 70 | + while (cs_disasm_iter(handle, &b, &size, &address, insn)) { |
| 71 | + continue; |
| 72 | + } |
| 73 | + cs_free(insn, 1); |
| 74 | + cs_close(&handle); |
| 75 | + return; |
| 76 | +} |
| 77 | + |
| 78 | +int main() |
| 79 | +{ |
| 80 | + test_overflow_cs_insn_bytes(); |
| 81 | + test_overflow_cs_insn_bytes_iter(); |
| 82 | + |
| 83 | + return 0; |
| 84 | +} |
0 commit comments