Headline
CVE-2021-31875: Fix culprit for JSON heap overflow by ex0dus-0x · Pull Request #2 · 418sec/mjs
** DISPUTED ** In mjs_json.c in Cesanta MongooseOS mJS 1.26, a maliciously formed JSON string can trigger an off-by-one heap-based buffer overflow in mjs_json_parse, which can potentially lead to redirection of control flow. NOTE: the original reporter disputes the significance of this finding because “there isn’t very much of an opportunity to exploit this reliably for an information leak, so there isn’t any real security impact.”
Bounty URL: https://huntr.dev/bounties/1-other-mjs/****Description
Fixes how a heap buffer is allocates and properly copies over parsed JSON string to prevent any out-of-bounds read/writes.
It turns out that the culprit for this didn’t exist in json_get_escape_len, but rather the very first allocation that gets made before copying over the parsed JSON string to begin parsing:
https://github.com/cesanta/mjs/blob/4c870e584d2b2a538abcee5307c498cc37e7ef9d/mjs/src/mjs_json.c#L448=L449
Since a string is being copied over, the buffer allocation is made with size len + 1, and after memcpy, a null byte is written to the end.
Proof of Fix
Without the fix, mjs copies over garbage to the buffer for the previously mentioned test case:
$ ./mjs ../out/crash_offbyone
String: {"e":"1\`��;�
Length: 14
at ../out/crash_offbyone:2
MJS error: invalid JSON string
With the fix and the insertion of the null-byte, the buffer points to the correct string being parsed:
String: {"e":"1\
Length: 8
at ../out/crash_offbyone:2
MJS error: invalid JSON string