Skip to content

Commit

Permalink
Add ObjectInputFilter example
Browse files Browse the repository at this point in the history
  • Loading branch information
egon-okerman-sonarsource committed Jan 18, 2024
1 parent 5a8cb45 commit 9a7e474
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions rules/S5135/java/how-to-fix-it/java-se.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,52 @@ public class RequestProcessor {
Object input = objectIS.readObject();
}
}
----

In Java 9 and later, it is also possible to use an `ObjectInputFilter` to limit deserialization to certain classes:

// Unfortunately, we cannot link two compliant examples to one non-compliant one, so this example does not have a diff view.
[source,java]
----
public class RequestProcessor {
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
ServletInputStream servletIS = request.getInputStream();
ObjectInputStream objectIS = new ObjectInputStream(servletIS);
ObjectInputFilter filter = ObjectInputFilter.Config.createFilter(
"com.example.AllowedClass1;com.example.AllowedClass2;!*"
);
objectIS.setObjectInputFilter(filter);
Object input = objectIS.readObject();
}
}
----

Lambdas can also be used to filter classes dynamically:

[source,java]
----
public class RequestProcessor {
List<String> approvedClasses = Arrays.asList(
AllowedClass1.class.getName(),
AllowedClass2.class.getName()
);
protected void doGet(HttpServletRequest request, HttpServletResponse response) {
ServletInputStream servletIS = request.getInputStream();
ObjectInputStream objectIS = new ObjectInputStream(servletIS);
objectIS.setObjectInputFilter(info -> {
if (this.approvedClasses.contains(info.serialClass().getName())) {
return ObjectInputFilter.Status.ALLOWED;
}
return ObjectInputFilter.Status.REJECTED;
});
Object input = objectIS.readObject();
}
}
----

=== How does this work?
Expand Down

0 comments on commit 9a7e474

Please sign in to comment.