Serializing Java Beans to XML using XMLEncoder
and XMLDecoder
seems like a pretty neat approach: many classes from many sources can be serialized reliably, just using their public interface. Using this aproach to serialization is even suggested in many places of the API reference. But the XML syntax used for this seems quite powerful. Are there any security mechanisms which will prevent attacks originating from malicious documents? Or should the use of XMLDecoder
on untrusted documents be avoided for security reasons?
The deserialization of XML-serialized beans can cause prety much any operation which the JVM can perform. To give you an ugly examle, consider the following document which will write a certain file without any questions being asked:
<?xml version="1.0" encoding="UTF-8" ?>
<java version="1.4.0" class="java.beans.XMLDecoder">
<object class="java.io.PrintWriter">
<string>/tmp/Hacked.txt</string>
<void method="println">
<string>You have been hacked!</string>
</void>
<void method="close"/>
</object>
</java>
This is roughly the same as a method
PrintWriter deserialize() {
PrintWriter obj = new PrintWriter("/tmp/Hacked.txt");
obj.println("You have been hacked!");
obj.close();
return obj;
}
For this reason, I strongly advise against simply reading data from untrusted sources using XMLDecoder
.
Either validate the document to a well-defined and harmless subset of the XML language, or use your own formats together with technologies such as jaxb. Or perform the deserialization in a tightly controlled environment, with security managers which will disallow any unexpected operation.
NO it absolutely is not safe to use.
The example MvG provide (in the accepted answer) doesn't paint the full picture.
Take a look at the examples I wrote on the Using XMLDecoder to execute server-side Java Code on an Restlet application (i.e. Remote Command Execution) blog post where I show how to:
all from XML files/strings that are parsed by XMLDecoder (and in the example shown in the blog post, via the Restlet's REST API ObjectRepresentation class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With