mirror of
https://github.com/nlohmann/json.git
synced 2026-07-26 12:24:54 +00:00
Enhance documentation on serializing untrusted input in dump() (#5304)
This commit is contained in:
@@ -43,6 +43,17 @@ Strong guarantee: if an exception is thrown, there are no changes to any JSON va
|
||||
Throws [`type_error.316`](../../home/exceptions.md#jsonexceptiontype_error316) if a string stored inside the JSON value
|
||||
is not UTF-8 encoded and `error_handler` is set to `strict`
|
||||
|
||||
!!! warning "Serializing untrusted input"
|
||||
|
||||
When serializing values that may contain invalid or untrusted UTF-8 (e.g., bytes taken directly from network
|
||||
input), `dump()` throws [`type_error.316`](../../home/exceptions.md#jsonexceptiontype_error316) in the default
|
||||
`strict` mode. To serialize such data without throwing, pass
|
||||
[`error_handler_t::replace`](error_handler_t.md) (substitutes U+FFFD) or
|
||||
[`error_handler_t::ignore`](error_handler_t.md). Callers that serialize untrusted input on a crash-sensitive path
|
||||
should either choose a non-strict error handler or wrap `dump()` in a `#!cpp try`/`#!cpp catch`.
|
||||
|
||||
See the [FAQ](../../home/faq.md#serializing-untrusted-or-invalid-utf-8) for details.
|
||||
|
||||
## Complexity
|
||||
|
||||
Linear.
|
||||
|
||||
@@ -194,6 +194,27 @@ The library uses `std::numeric_limits<number_float_t>::digits10` (15 for IEEE `d
|
||||
|
||||
See [this section](../features/types/number_handling.md#number-serialization) on the library's number handling for more information.
|
||||
|
||||
### Serializing untrusted or invalid UTF-8
|
||||
|
||||
!!! question "Questions"
|
||||
|
||||
- Why does `dump()` throw when I serialize data that came from the network?
|
||||
- Is CVE-2024-34363 a vulnerability in this library?
|
||||
|
||||
Crashes reported against this library that stem from an uncaught
|
||||
[`type_error.316`](exceptions.md#jsonexceptiontype_error316) while serializing unvalidated input (e.g.,
|
||||
CVE-2024-34363) are a usage issue, not a library vulnerability:
|
||||
[`dump()`](../api/basic_json/dump.md) throws in its default `strict` mode because
|
||||
[RFC 8259](https://datatracker.ietf.org/doc/html/rfc8259#section-8.1) requires JSON text to be valid UTF-8.
|
||||
|
||||
The recommended pattern is to pass a non-strict [`error_handler`](../api/basic_json/error_handler_t.md) or to handle the
|
||||
exception:
|
||||
|
||||
```cpp
|
||||
// replace invalid sequences with U+FFFD instead of throwing
|
||||
const auto s = j.dump(-1, ' ', false, json::error_handler_t::replace);
|
||||
```
|
||||
|
||||
### Using JSON values with `std::format` or `fmt`
|
||||
|
||||
!!! question
|
||||
|
||||
Reference in New Issue
Block a user