Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to properly close and release new ObjectInputStream() and objectInputStream.readObject()

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading