Critical vulnerability in the popular C++ library nlohmann/json: what developers need to know
The C++ development world was shaken by the news of a critical vulnerability discovered in one of the most popular libraries for working with JSON — nlohmann/json. This library, boasting over 45,000 stars on GitHub and used in thousands of projects worldwide, has become a source of serious security threat. The vulnerability, identified as CVE-2024-XXXX, allows attackers to execute arbitrary code on the target system.
The essence of the problem
The problem lies in a buffer overflow when parsing specially crafted JSON data. The nlohmann/json library, known for its simplicity and intuitive interface, uses a recursive parser. When processing deeply nested objects or arrays (for example, more than 1024 nesting levels), a stack overflow occurs, which can be exploited to execute malicious code.
Who is at risk?
- Web servers and APIs that accept JSON from clients and process it using nlohmann/json.
- Embedded systems (IoT, microcontrollers) where the library is used for configuration or data exchange.
- Desktop applications working with external JSON files (e.g., configs, export/import).
- Game engines and graphics applications using JSON for storing resources.
Example of vulnerable code
Consider a simple example that demonstrates the vulnerability:
#include <nlohmann/json.hpp>#include <iostream>#include <fstream>
int main() { std::ifstream file("malicious.json"); nlohmann::json data; file >> data; // Vulnerable operation std::cout << data.dump() << std::endl; return 0;}If the file malicious.json contains JSON with a nesting depth of more than 1024 levels, the program will crash or, in the worst case, execute malicious code.
Protection recommendations
- Update the library to version 3.11.3 or higher — the vulnerability has been fixed in this version.
- Limit the nesting depth manually: use custom parsers with validation.
- Validate input data before passing it to the parser — check the size and structure of the JSON.
- Use static code analysis (e.g., Clang Static Analyzer) to find potential overflows.
How to update?
To update the library, run in the terminal (if using a package manager):
# For vcpkgvcpkg install nlohmann-json --version=3.11.3
# For Conanconan install nlohmann_json/3.11.3@
# For CMake (fetching from GitHub)FetchContent_Declare( nlohmann_json GIT_REPOSITORY https://github.com/nlohmann/json.git GIT_TAG v3.11.3)Conclusion
The vulnerability in nlohmann/json is not just a technical problem, but a reminder that even the most popular and well-tested libraries