Jackson 3 series companion code
37 runnable examples covering the eight feature posts on ankurm.com, verified against Jackson 3.2.1 on Temurin 21.0.5. Every output committed under docs/ was produced by run-all.sh. Also documents 11 places where the published snippets do not compile or do not behave as printed against a real Jackson 3 build - most notably that writeValueAsString(List<Base>) silently drops the polymorphic type discriminator, so the post's serialised output cannot be read back.
This commit is contained in:
@@ -0,0 +1,49 @@
|
||||
package com.ankurm.jackson3.part7security;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonSubTypes;
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* Post: Jackson Security Best Practices — https://ankurm.com/jackson-security-best-practices/
|
||||
* Section: "Use @JsonTypeInfo Instead of Default Typing"
|
||||
*
|
||||
* The safe pattern: the permitted types are fixed at compile time, so no JSON payload
|
||||
* can introduce a class name of its own.
|
||||
*/
|
||||
public class H01SafePolymorphismByAnnotation {
|
||||
|
||||
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
|
||||
@JsonSubTypes({
|
||||
@JsonSubTypes.Type(value = EmailNotification.class, name = "email"),
|
||||
@JsonSubTypes.Type(value = SmsNotification.class, name = "sms")
|
||||
})
|
||||
public abstract static class Notification { }
|
||||
|
||||
public static class EmailNotification extends Notification {
|
||||
public String recipientEmail;
|
||||
@Override public String toString() { return "EmailNotification[" + recipientEmail + "]"; }
|
||||
}
|
||||
|
||||
public static class SmsNotification extends Notification {
|
||||
public String recipientPhone;
|
||||
@Override public String toString() { return "SmsNotification[" + recipientPhone + "]"; }
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
System.out.println("email : " + mapper.readValue(
|
||||
"{\"type\":\"email\",\"recipientEmail\":\"[email protected]\"}", Notification.class));
|
||||
System.out.println("sms : " + mapper.readValue(
|
||||
"{\"type\":\"sms\",\"recipientPhone\":\"+441234567890\"}", Notification.class));
|
||||
|
||||
// A class name supplied by an attacker is not a registered logical name.
|
||||
try {
|
||||
mapper.readValue("{\"type\":\"com.malicious.Gadget\"}", Notification.class);
|
||||
System.out.println("attack: UNEXPECTEDLY ACCEPTED");
|
||||
} catch (Exception e) {
|
||||
System.out.println("attack: rejected with " + e.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.ankurm.jackson3.part7security;
|
||||
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* Post: Jackson Security Best Practices — https://ankurm.com/jackson-security-best-practices/
|
||||
* Section: "The Safe Alternative: PolymorphicTypeValidator"
|
||||
*
|
||||
* CORRECTION TO THE POST. The post shows the remediation as
|
||||
*
|
||||
* ObjectMapper mapper = new ObjectMapper();
|
||||
* mapper.activateDefaultTyping(validator, DefaultTyping.NON_FINAL, As.PROPERTY);
|
||||
*
|
||||
* That is Jackson 2 code. In Jackson 3 BOTH enableDefaultTyping and
|
||||
* activateDefaultTyping are absent from the mapper — the mapper has no mutators at
|
||||
* all. activateDefaultTyping survives only on JsonMapper.Builder. This prints the
|
||||
* reflective proof for each claim rather than asserting it.
|
||||
*
|
||||
* See H03PolymorphicTypeValidatorAllowlist for the working builder-based form.
|
||||
*/
|
||||
public class H02DefaultTypingRemoved {
|
||||
|
||||
public static void main(String[] args) {
|
||||
System.out.println("--- tools.jackson.databind.ObjectMapper ---");
|
||||
report(ObjectMapper.class, "enableDefaultTyping");
|
||||
report(ObjectMapper.class, "activateDefaultTyping");
|
||||
report(ObjectMapper.class, "setSerializationInclusion");
|
||||
report(ObjectMapper.class, "registerModule");
|
||||
report(ObjectMapper.class, "addMixIn");
|
||||
System.out.println("total set*() mutators: " + Arrays.stream(ObjectMapper.class.getMethods())
|
||||
.filter(m -> m.getName().startsWith("set")).count());
|
||||
|
||||
System.out.println();
|
||||
System.out.println("--- tools.jackson.databind.json.JsonMapper.Builder ---");
|
||||
report(JsonMapper.Builder.class, "activateDefaultTyping");
|
||||
report(JsonMapper.Builder.class, "deactivateDefaultTyping");
|
||||
report(JsonMapper.Builder.class, "polymorphicTypeValidator");
|
||||
report(JsonMapper.Builder.class, "changeDefaultPropertyInclusion");
|
||||
report(JsonMapper.Builder.class, "serializationInclusion");
|
||||
}
|
||||
|
||||
private static void report(Class<?> type, String methodName) {
|
||||
boolean present = Arrays.stream(type.getMethods())
|
||||
.map(Method::getName)
|
||||
.anyMatch(methodName::equals);
|
||||
System.out.printf(" %-32s %s%n", methodName, present ? "present" : "ABSENT");
|
||||
}
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package com.ankurm.jackson3.part7security;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonTypeInfo;
|
||||
import tools.jackson.databind.DefaultTyping;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
import tools.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
|
||||
import tools.jackson.databind.jsontype.PolymorphicTypeValidator;
|
||||
|
||||
/**
|
||||
* Post: Jackson Security Best Practices — https://ankurm.com/jackson-security-best-practices/
|
||||
* Section: "The Safe Alternative: PolymorphicTypeValidator"
|
||||
*
|
||||
* The post's snippet in working Jackson 3 form. Note DefaultTyping is a top-level
|
||||
* enum in tools.jackson.databind, not ObjectMapper.DefaultTyping as in Jackson 2.
|
||||
*
|
||||
* Default typing remains a last resort. Prefer H01. This exists because legacy object
|
||||
* graphs and plugin systems sometimes genuinely need it, and when they do, the
|
||||
* allowlist has to be provable — hence the negative test at the bottom.
|
||||
*/
|
||||
public class H03PolymorphicTypeValidatorAllowlist {
|
||||
|
||||
public abstract static class BasePayload { }
|
||||
public static class SafePayload extends BasePayload {
|
||||
public String note;
|
||||
public SafePayload() { }
|
||||
public SafePayload(String n) { note = n; }
|
||||
@Override public String toString() { return "SafePayload[" + note + "]"; }
|
||||
}
|
||||
|
||||
/** Deliberately outside the allowlisted base type. */
|
||||
public static class RoguePayload {
|
||||
public String note;
|
||||
}
|
||||
|
||||
public static class Envelope {
|
||||
public Object body; // the field default typing has to resolve
|
||||
public Envelope() { }
|
||||
public Envelope(Object b) { body = b; }
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
// Permit ONLY the envelope and our own payload hierarchy. Anything else is
|
||||
// refused at type-resolution time, before any class is instantiated.
|
||||
//
|
||||
// Note the gotcha: with DefaultTyping.NON_FINAL, Jackson writes a type id for
|
||||
// the ROOT object too, so Envelope must be allowlisted as well. Allowlisting
|
||||
// only BasePayload makes even the happy path fail — which is how most people
|
||||
// first meet this API.
|
||||
PolymorphicTypeValidator safeTypeValidator = BasicPolymorphicTypeValidator.builder()
|
||||
.allowIfSubType(Envelope.class)
|
||||
.allowIfSubType(BasePayload.class)
|
||||
.build();
|
||||
|
||||
JsonMapper mapper = JsonMapper.builder()
|
||||
.activateDefaultTyping(safeTypeValidator,
|
||||
DefaultTyping.NON_FINAL,
|
||||
JsonTypeInfo.As.PROPERTY)
|
||||
.build();
|
||||
|
||||
String allowed = mapper.writeValueAsString(new Envelope(new SafePayload("ok")));
|
||||
System.out.println("allowed written : " + allowed);
|
||||
System.out.println("allowed read : "
|
||||
+ ((Envelope) mapper.readValue(allowed, Envelope.class)).body);
|
||||
|
||||
// Negative test: a class outside the allowlist is rejected even though it
|
||||
// exists on the classpath and would deserialise perfectly well otherwise.
|
||||
String rogue = "{\"body\":[\"" + RoguePayload.class.getName() + "\",{\"note\":\"pwn\"}]}";
|
||||
try {
|
||||
mapper.readValue(rogue, Envelope.class);
|
||||
System.out.println("rogue : UNEXPECTEDLY ACCEPTED");
|
||||
} catch (Exception e) {
|
||||
System.out.println("rogue : rejected with " + e.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.ankurm.jackson3.part7security;
|
||||
|
||||
import tools.jackson.core.StreamReadConstraints;
|
||||
import tools.jackson.core.json.JsonFactory;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* BEYOND THE POST — the hardening the security post does not mention.
|
||||
*
|
||||
* Gadget attacks are not the only deserialisation risk. A small payload can also
|
||||
* exhaust the stack or the heap: deeply nested arrays, gigantic numbers, enormous
|
||||
* strings. Jackson 3 ships StreamReadConstraints with defaults for all three, and
|
||||
* they are tunable. Any service accepting external JSON should know what they are.
|
||||
*/
|
||||
public class H04StreamReadConstraints {
|
||||
|
||||
public static void main(String[] args) {
|
||||
StreamReadConstraints defaults = StreamReadConstraints.defaults();
|
||||
System.out.println("--- Jackson 3 defaults ---");
|
||||
System.out.println("max nesting depth : " + defaults.getMaxNestingDepth());
|
||||
System.out.println("max number length : " + defaults.getMaxNumberLength());
|
||||
System.out.println("max string length : " + defaults.getMaxStringLength());
|
||||
System.out.println("max name length : " + defaults.getMaxNameLength());
|
||||
System.out.println("max doc length : " + defaults.getMaxDocumentLength()
|
||||
+ " (-1 = unlimited)");
|
||||
System.out.println();
|
||||
|
||||
JsonMapper plain = JsonMapper.builder().build();
|
||||
String deep = "[".repeat(1200) + "]".repeat(1200);
|
||||
System.out.println("1200-deep nesting, default limits -> " + attempt(plain, deep));
|
||||
|
||||
// Tighten the limits for an endpoint that should never see nested data.
|
||||
JsonFactory strictFactory = JsonFactory.builder()
|
||||
.streamReadConstraints(StreamReadConstraints.builder()
|
||||
.maxNestingDepth(10)
|
||||
.maxStringLength(2_000)
|
||||
.build())
|
||||
.build();
|
||||
JsonMapper strict = JsonMapper.builder(strictFactory).build();
|
||||
|
||||
System.out.println("20-deep nesting, strict limits -> "
|
||||
+ attempt(strict, "[".repeat(20) + "]".repeat(20)));
|
||||
System.out.println("5-deep nesting, strict limits -> "
|
||||
+ attempt(strict, "[".repeat(5) + "]".repeat(5)));
|
||||
System.out.println("3KB string, strict limits -> "
|
||||
+ attempt(strict, "\"" + "x".repeat(3_000) + "\""));
|
||||
}
|
||||
|
||||
private static String attempt(JsonMapper mapper, String json) {
|
||||
try {
|
||||
mapper.readTree(json);
|
||||
return "accepted";
|
||||
} catch (Exception e) {
|
||||
return "rejected (" + e.getClass().getSimpleName() + ")";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.ankurm.jackson3.part7security;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* Post: Jackson Security Best Practices — https://ankurm.com/jackson-security-best-practices/
|
||||
* Section: "Never Deserialise Untrusted JSON into Object.class"
|
||||
*
|
||||
* Worth knowing precisely what readValue(json, Object.class) does on a DEFAULT
|
||||
* Jackson 3 mapper, because the answer is reassuring and often misunderstood:
|
||||
* with no default typing active it produces plain Maps, Lists, Strings and numbers.
|
||||
* The danger only returns when default typing is switched on — as H03 shows.
|
||||
*
|
||||
* The rule still stands. Target a specific type; you get validation for free.
|
||||
*/
|
||||
public class H05NeverDeserialiseIntoObject {
|
||||
|
||||
public record MyRequestDto(String action, int quantity) { }
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
String untrusted = "{\"action\":\"ship\",\"quantity\":3,\"extra\":{\"nested\":[1,2]}}";
|
||||
|
||||
Object loose = mapper.readValue(untrusted, Object.class);
|
||||
System.out.println("as Object : " + loose);
|
||||
System.out.println("runtime type: " + loose.getClass().getName()
|
||||
+ " <- a plain Map, no arbitrary class was instantiated");
|
||||
|
||||
MyRequestDto typed = mapper.readValue(untrusted, MyRequestDto.class);
|
||||
System.out.println("as DTO : " + typed);
|
||||
|
||||
// The real benefit of a specific target type: malformed input fails loudly
|
||||
// instead of flowing onward as an untyped Map.
|
||||
try {
|
||||
mapper.readValue("{\"action\":\"ship\",\"quantity\":\"not-a-number\"}", MyRequestDto.class);
|
||||
System.out.println("bad input : UNEXPECTEDLY ACCEPTED");
|
||||
} catch (Exception e) {
|
||||
System.out.println("bad input : rejected with " + e.getClass().getSimpleName());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user