How to Fix Insecure Deserialization Vulnerabilities
In this tutorial, you'll learn about How to Fix Insecure Deserialization Vulnerabilities. We cover key concepts, practical examples, and best practices.
Insecure deserialization occurs when user-controlled serialized data is deserialized without integrity verification. Attackers can craft payloads that execute code, inject objects, or tamper with application state.
Quick Fix
Wrong
std::string data = receiveUntrustedData();
Message msg = Message::deserialize(data);
process(msg);
Crafted serialized data can execute arbitrary code during deserialization.
Right
std::string data = receiveUntrustedData();
if (!validateMessageFormat(data)) {
throw std::runtime_error("Invalid data");
}
Message msg = Message::deserialize(data);
process(msg);
Fix with HMAC signing
std::string signedData = hmac_sha256(secret, data) + ":" + data;
// Store or transmit signedData
// On receive:
auto parts = split(signedData, ":");
if (parts.size() != 2) reject();
if (!constantTimeEquals(parts[0], hmac_sha256(secret, parts[1]))) reject();
Message msg = Message::deserialize(parts[1]);
Fix for JSON deserialization
nlohmann::json json = nlohmann::json::parse(data);
if (!json.contains("type") || json["type"] != "Message") {
throw std::runtime_error("Invalid type");
}
auto msg = json.get<Message>();
Fix with allowlist
std::set<std::string> allowedTypes = {"Message", "Event", "Command"};
if (!allowedTypes.contains(msg.type())) {
throw std::runtime_error("Unknown message type");
}
Prevention
- Never deserialize data from untrusted sources.
- Use HMAC signing or encryption for integrity.
- Validate deserialized types against an allowlist.
- Use safe formats (JSON, Protocol Buffers) with schema validation.
- Run deserialization in sandboxed environments.
DodaTech Tools
Doda Browser's deserialization scanner tests for gadget chains and object injection. DodaZIP encrypts serialized data with integrity verification. Durga Antivirus Pro detects untrusted deserialization in network traffic.
Common Mistakes with deserialization
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists
These mistakes appear frequently in real-world INSECURE code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro