Skip to content

sav: don't reuse multiple response set arrays after readstat_realloc frees them - #442

Open
ziyziy89 wants to merge 1 commit into
WizardMac:devfrom
ziyziy89:sav-mr-sets-realloc
Open

ziyziy89 wants to merge 1 commit into
WizardMac:devfrom
ziyziy89:sav-mr-sets-realloc

Conversation

@ziyziy89

Copy link
Copy Markdown
Contributor

parse_mr_line and parse_mr_string grow the multiple response set arrays (a set's subvariables, and ctx->mr_sets) one entry at a time with readstat_realloc, and on NULL they keep the old pointer. readstat_realloc frees the old block when it refuses a size above its 16 MiB cap, unlike realloc. So a type 7 subtype 7/19 record whose set lists more than 2^21 variables (about 4 MiB of $a=C 0 b b b ...), or that holds more than 16 MiB / sizeof(mr_set_t) sets (about 2 MiB of $a=C 0 \n lines on 64-bit), leaves a freed array in place. mr_set_free_contents then reads and frees every subvariable through it and frees it again. For the set array, sav_ctx_free does the same with ctx->mr_sets. ASan reports heap-use-after-free at readstat_sav_parse_mr_name.c:30 and readstat_sav.c:101, followed by the double free, and a plain build segfaults. Any readstat_parse_sav call on an untrusted .sav reaches this.

The fix counts a set's variables, and a record's sets, before allocating, then allocates each array once with readstat_malloc, which frees nothing when it fails. The set array is copied into the new block rather than handed to readstat_realloc, so sets parsed from an earlier record are still there when the size is refused. Valid, malformed and blank-line records parse exactly as before; I compared the parsed sets before and after. The new test in test_readstat builds both oversized records and expects READSTAT_ERROR_MALLOC. Without the fix it crashes, and with it the test finishes in about a second.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant