Skip to content

Reject malformed input in mg_json_get_hex#3634

Open
94xhn wants to merge 1 commit into
cesanta:masterfrom
94xhn:fix/json-hex-validation
Open

Reject malformed input in mg_json_get_hex#3634
94xhn wants to merge 1 commit into
cesanta:masterfrom
94xhn:fix/json-hex-validation

Conversation

@94xhn

@94xhn 94xhn commented Jul 14, 2026

Copy link
Copy Markdown

mg_json_get_hex() currently ignores failed mg_str_to_num() calls and processes odd-length strings in two-character steps. As a result, 0g succeeds as byte 0x00, and abc succeeds as byte 0xab instead of reporting invalid input.

Reject odd-length and non-hex strings while preserving valid input and the existing empty-string behavior. The unit tests now cover empty, odd-length, and non-hex inputs.

Testing:

  • make -B -C test test TFLAGS=-DLOCALHOST_ONLY (ASan/UBSan, 1796 tests)
  • make -B -C test unamalgamated TFLAGS=-DLOCALHOST_ONLY, then unit_test (ASan/UBSan, 1796 tests)
  • Regenerated mongoose.c and mongoose.h with the repository Makefile; no diff

@scaprile scaprile left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You need to sign the CLA if you want this to be merged, otherwise we will close this PR and may do something different that serves the same purpose.

Comment thread src/json.c Outdated
Comment on lines +370 to +374
if (!mg_str_to_num(mg_str_n(json.buf + off + 1 + i, 2), 16,
&result[i >> 1], sizeof(uint8_t))) {
mg_free(result);
return NULL;
}

@scaprile scaprile Jul 14, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't like this style, it shifts the attention from the algorithm to handling wreckage. I would break on a single line and check/free after the loop, also on a single line

@scaprile

Copy link
Copy Markdown
Collaborator

Please do not add those long, ugly, and useless AI-generated commit comments; and please let me know when you signed the CLA.

@scaprile
scaprile self-requested a review July 14, 2026 20:40
Reject odd-length and non-hex strings before decoding them.

Tested: 1796 ASan/UBSan tests in amalgamated and unamalgamated builds
@94xhn
94xhn force-pushed the fix/json-hex-validation branch from ae9d86f to dc52d8b Compare July 16, 2026 00:34
@94xhn

94xhn commented Jul 16, 2026

Copy link
Copy Markdown
Author

I have signed the Cesanta CLA. I also squashed the branch to one commit and shortened the commit message as requested.

@scaprile
scaprile requested a review from cpq July 16, 2026 15:18
@scaprile

Copy link
Copy Markdown
Collaborator

@cpq WDYT ? LGTM

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.

3 participants