I would like to close and release new ObjectInputStream() while safely use objectInputStream.readObject().
Looking at this piece of code:
public Map<?, ?> getMap(String encoded) {
try {
var objectInputStream = new ObjectInputStream(new ByteArrayInputStream(Base64.getDecoder().decode(encoded)));
return (Map<?, ?>) objectInputStream.readObject();
} catch (IOException | ClassNotFoundException | IllegalArgumentException e) {
return Map.of();
}
}
The above is being flagged with multiple static analysis tools. The issue reported is:
defines and initializes the ObjectInputStream object. This object
encapsulates a limited computing resource, such as open file streams,
database connections, or network streams. This resource is not
properly closed and released in all situations.
with
gets user input from element readObject. This element’s value flows
through the code without being properly sanitized or validated, and is
eventually used in writing an audit log. This may enable Stored Log
Forging.
How to properly use new ObjectInputStream() and objectInputStream.readObject()?
>Solution :
Just one rule for all streams to correctly release all resources is try-with-resources:
try (InputStream in = new ObjectInputStream()) {
// TODO
}
public Map<?, ?> getMap(String encoded) {
try (InputStream in = new ObjectInputStream(
new ByteArrayInputStream(Base64.getDecoder().decode(encoded))) {
return (Map<?, ?>) objectInputStream.readObject();
} catch (Exception e) {
return Map.of();
}
}