Merge pull request #3634 from 94xhn/fix/json-hex-validation

Reject malformed input in mg_json_get_hex
This commit is contained in:
Sergio R. Caprile authored and GitHub committed 2026-07-24 11:36:31 -03:00
commit f8e785f56b
5 files changed
+29 -13

No files matched your search

+8 -5
View File
@@ -363,15 +363,18 @@ char *mg_json_get_b64(struct mg_str json, const char *path, int *slen) {
char *mg_json_get_hex(struct mg_str json, const char *path, int *slen) {
char *result = NULL;
int len = 0, off = mg_json_get(json, path, &len);
if (off >= 0 && json.buf[off] == '"' && len > 1 &&
if (off >= 0 && json.buf[off] == '"' && len > 1 && (len - 2) % 2 == 0 &&
(result = (char *) mg_calloc(1, (size_t) len / 2)) != NULL) {
int i;
for (i = 0; i < len - 2; i += 2) {
mg_str_to_num(mg_str_n(json.buf + off + 1 + i, 2), 16, &result[i >> 1],
sizeof(uint8_t));
if (!mg_str_to_num(mg_str_n(json.buf + off + 1 + i, 2), 16,
&result[i >> 1], sizeof(uint8_t))) break;
}
if (i < len - 2) mg_free(result), result = NULL;
if (result != NULL) {
result[len / 2 - 1] = '\0';
if (slen != NULL) *slen = len / 2 - 1;
}
result[len / 2 - 1] = '\0';
if (slen != NULL) *slen = len / 2 - 1;
}
return result;
}
+1 -1
View File
@@ -57,7 +57,7 @@ char *mg_json_get_str(struct mg_str json, const char *path);
// Decodes a hex-encoded JSON string at path into a heap-allocated byte array.
// Sets *len to the decoded byte count. Caller must mg_free() the result.
// Returns NULL if not found or not a string.
// Returns NULL if not found, not a string, or not valid hexadecimal.
char *mg_json_get_hex(struct mg_str json, const char *path, int *len);
// Decodes a base64-encoded JSON string at path into a heap-allocated byte