Guidance on Deserializing Objects Safely

Patient Tools

Read, save, and share this guide

Use these quick tools to make this medical article easier to read, print, save, or share with a family member.

Article Summary

Serialization is the process of turning some object into a data format that can be restored later. People often serialize objects in order to save them for storage, or to send as part of communications. Deserialization is the reverse of that process, taking data structured in some format, and rebuilding it into an object. Today, the most popular data format for serializing data is JSON. Before that,...

Key Takeaways

  • This article explains Guidance on Deserializing Objects Safely in simple medical language.
  • This article explains Language-Agnostic Methods for Deserializing Safely in simple medical language.
Educational health guideWritten for patient understanding and clinical awareness.
Reviewed content workflowUse writer and reviewer profiles for stronger trust.
Emergency safety firstUrgent warning signs are highlighted below.

Seek urgent medical care if you notice

These warning signs are general safety guidance. Local emergency numbers and clinical judgment should always come first.

  • Severe symptoms, breathing difficulty, fainting, confusion, or rapidly worsening illness.
  • New weakness, severe pain, high fever, or symptoms after a serious injury.
  • Any symptom that feels urgent, unusual, or unsafe for the patient.
1

Emergency now

Use emergency care for severe, sudden, rapidly worsening, or life-threatening symptoms.

2

See a doctor

Book a professional medical evaluation if symptoms persist, worsen, recur often, affect daily activities, or occur in a high-risk patient.

3

Learn safely

Use this article to understand possible causes, tests, treatment options, prevention, and questions to ask your clinician.

Serialization is the process of turning some object into a data format that can be restored later. People often serialize objects in order to save them for storage, or to send as part of communications.

Deserialization is the reverse of that process, taking data structured in some format, and rebuilding it into an object. Today, the most popular data format for serializing data is JSON. Before that, it was XML.

However, many programming languages have native ways to serialize objects. These native formats usually offer more features than JSON or XML, including customizability of the serialization process.

Unfortunately, the features of these native deserialization mechanisms can sometimes be repurposed for malicious effect when operating on untrusted data. Attacks against deserializers have been found to allow denial-of-service, access control, or remote code execution (RCE) attacks.

Guidance on Deserializing Objects Safely

The following language-specific guidance attempts to enumerate safe methodologies for deserializing data that can’t be trusted.

PHP

WhiteBox Review

Check the use of unserialize() function and review how the external parameters are accepted. Use a safe, standard data interchange format such as JSON (via json_decode() and json_encode()) if you need to pass serialized data to the user.

Python

BlackBox Review

If the traffic data contains the symbol dot . at the end, it’s very likely that the data was sent in serialization.

WhiteBox Review

The following API in Python will be vulnerable to serialization attack. Search code for the pattern below.

  1. The uses of pickle/c_pickle/_pickle with load/loads:
import pickle
data = """ cos.system(S'dir')tR. """
pickle.loads(data)
  1. Uses of PyYAML with load:
import yaml
document = "!!python/object/apply:os.system ['ipconfig']"
print(yaml.load(document))
  1. Uses of jsonpickle with encode or store methods.

Java

The following techniques are all good for preventing attacks against deserialization against Java’s Serializable format.

Implementation advices:

  • In your code, override the ObjectInputStream#resolveClass() method to prevent arbitrary classes from being deserialized. This safe behavior can be wrapped in a library like SerialKiller.
  • Use a safe replacement for the generic readObject() method as seen here. Note that this addresses “billion laughs” type attacks by checking input length and number of objects deserialized.

WhiteBox Review

Be aware of the following Java API uses for potential serialization vulnerability.

1. XMLdecoder with external user defined parameters

2. XStream with fromXML method (xstream version <= v1.4.6 is vulnerable to the serialization issue)

3. ObjectInputStream with readObject

4. Uses of readObjectreadObjectNoDatareadResolve or readExternal

5. ObjectInputStream.readUnshared

6. Serializable

BlackBox Review

If the captured traffic data includes the following patterns, it may suggest that the data was sent in Java serialization streams:

  • AC ED 00 05 in Hex
  • rO0 in Base64
  • Content-type header of an HTTP response set to application/x-java-serialized-object

Prevent Data Leakage and Trusted Field Clobbering

If there are data members of an object that should never be controlled by end users during deserialization or exposed to users during serialization, they should be declared as the transient keyword (section Protecting Sensitive Information).

For a class that defined as Serializable, the sensitive information variable should be declared as private transient.

For example, the class myAccount, the variables ‘profit’ and ‘margin’ were declared as transient to prevent them from being serialized.

public class myAccount implements Serializable
{
    private transient double profit; // declared transient

    private transient double margin; // declared transient
    ....

Prevent Deserialization of Domain Objects

Some of your application objects may be forced to implement Serializable due to their hierarchy. To guarantee that your application objects can’t be deserialized, a readObject() method should be declared (with a final modifier) which always throws an exception:

private final void readObject(ObjectInputStream in) throws java.io.IOException {
    throw new java.io.IOException("Cannot be deserialized");
}

Harden Your Own java.io.ObjectInputStream

The java.io.ObjectInputStream class is used to deserialize objects. It’s possible to harden its behavior by subclassing it. This is the best solution if:

  • you can change the code that does the deserialization;
  • you know what classes you expect to deserialize.

The general idea is to override ObjectInputStream.html#resolveClass() in order to restrict which classes are allowed to be deserialized.

Because this call happens before a readObject() is called, you can be sure that no deserialization activity will occur unless the type is one that you allow.

A simple example is shown here, where the LookAheadObjectInputStream class is guaranteed to not deserialize any other type besides the Bicycle class:

public class LookAheadObjectInputStream extends ObjectInputStream {

    public LookAheadObjectInputStream(InputStream inputStream) throws IOException {
        super(inputStream);
    }

    /**
    * Only deserialize instances of our expected Bicycle class
    */
    @Override
    protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
        if (!desc.getName().equals(Bicycle.class.getName())) {
            throw new InvalidClassException("Unauthorized deserialization attempt", desc.getName());
        }
        return super.resolveClass(desc);
    }
}

More complete implementations of this approach have been proposed by various community members:

  • NibbleSec – a library that allows creating lists of classes that are allowed to be deserialized
  • IBM – the seminal protection, written years before the most devastating exploitation scenarios were envisioned.
  • Apache Commons IO classes

Harden All java.io.ObjectInputStream Usage with an Agent

As mentioned above, the java.io.ObjectInputStream class is used to deserialize objects. It’s possible to harden its behavior by subclassing it. However, if you don’t own the code or can’t wait for a patch, using an agent to weave in hardening to java.io.ObjectInputStream is the best solution.

Globally changing ObjectInputStream is only safe for block-listing known malicious types, because it’s not possible to know for all applications what the expected classes to be deserialized are. Fortunately, there are very few classes needed in the blocklist to be safe from all the known attack vectors, today.

It’s inevitable that more “gadget” classes will be discovered that can be abused. However, there is an incredible amount of vulnerable software exposed today, in need of a fix. In some cases, “fixing” the vulnerability may involve re-architecting messaging systems and breaking backwards compatibility as developers move towards not accepting serialized objects.

To enable these agents, simply add a new JVM parameter:

-javaagent:name-of-agent.jar

Agents taking this approach have been released by various community members:

A similar, but less scalable approach would be to manually patch and bootstrap your JVM’s ObjectInputStream. Guidance on this approach is available here.

Other Deserialization Libraries and Formats

While the advice above is focused on Java’s Serializable format, there are a number of other libraries that use other formats for deserialization. Many of these libraries may have similar security issues if not configured correctly. This section lists some of these libraries and recommended configuration options to avoid security issues when deserializing untrusted data:

Can be used safely with default configuration:

The following libraries can be used safely with default configuration:

Requires configuration before can be used safely:

The following libraries require configuration options to be set before they can be used safely:

  • fastjson v1.2.68+ (JSON) – cannot be used safely unless the safemode option is turned on, which disables deserialization of any class (see documentation). Previous versions are not safe.
  • json-io (JSON) – cannot be used safely since the use of @type property in JSON allows deserialization of any class. Can only be used safely in following situations:
  • Kryo < v5.0.0 (custom format) – cannot be used safely unless class registration is turned on, which disables deserialization of any class (see documentation and this issue)
    • NOTE: other wrappers exist around Kryo such as Chill, which may also have class registration not required by default regardless of the underlying version of Kryo being used
  • SnakeYAML (YAML) – cannot be used safely unless the org.yaml.snakeyaml.constructor.SafeConstructor class is used, which disables deserialization of any class (see docs)

Cannot be used safely:

The following libraries are either no longer maintained or cannot be used safely with untrusted input:

.Net CSharp

WhiteBox Review

Search the source code for the following terms:

  1. TypeNameHandling
  2. JavaScriptTypeResolver

Look for any serializers where the type is set by a user controlled variable.

BlackBox Review

Search for the following base64 encoded content that starts with:

AAEAAAD/////

Search for content with the following text:

  1. TypeObject
  2. $type:

General Precautions

Microsoft has stated that the BinaryFormatter type is dangerous and cannot be secured. As such, it should not be used. Full details are in the BinaryFormatter security guide.

Don’t allow the datastream to define the type of object that the stream will be deserialized to. You can prevent this by for example using the DataContractSerializer or XmlSerializer if at all possible.

Where JSON.Net is being used make sure the TypeNameHandling is only set to None.

TypeNameHandling = TypeNameHandling.None

If JavaScriptSerializer is to be used then do not use it with a JavaScriptTypeResolver.

If you must deserialise data streams that define their own type, then restrict the types that are allowed to be deserialized. One should be aware that this is still risky as many native .Net types potentially dangerous in themselves. e.g.

System.IO.FileInfo

FileInfo objects that reference files actually on the server can when deserialized, change the properties of those files e.g. to read-only, creating a potential denial of service attack.

Even if you have limited the types that can be deserialised remember that some types have properties that are risky. System.ComponentModel.DataAnnotations.ValidationException, for example has a property Value of type Object. if this type is the type allowed for deserialization then an attacker can set the Value property to any object type they choose.

Attackers should be prevented from steering the type that will be instantiated. If this is possible then even DataContractSerializer or XmlSerializer can be subverted e.g.

// Action below is dangerous if the attacker can change the data in the database
var typename = GetTransactionTypeFromDatabase();

var serializer = new DataContractJsonSerializer(Type.GetType(typename));

var obj = serializer.ReadObject(ms);

Execution can occur within certain .Net types during deserialization. Creating a control such as the one shown below is ineffective.

var suspectObject = myBinaryFormatter.Deserialize(untrustedData);

//Check below is too late! Execution may have already occurred.
if (suspectObject is SomeDangerousObjectType)
{
    //generate warnings and dispose of suspectObject
}

For JSON.Net it is possible to create a safer form of allow-list control using a custom SerializationBinder.

Try to keep up-to-date on known .Net insecure deserialization gadgets and pay special attention where such types can be created by your deserialization processes. A deserializer can only instantiate types that it knows about.

Try to keep any code that might create potential gadgets separate from any code that has internet connectivity. As an example System.Windows.Data.ObjectDataProvider used in WPF applications is a known gadget that allows arbitrary method invocation. It would be risky to have this a reference to this assembly in a REST service project that deserializes untrusted data.

Known .NET RCE Gadgets

  • System.Configuration.Install.AssemblyInstaller
  • System.Activities.Presentation.WorkflowDesigner
  • System.Windows.ResourceDictionary
  • System.Windows.Data.ObjectDataProvider
  • System.Windows.Forms.BindingSource
  • Microsoft.Exchange.Management.SystemManager.WinForms.ExchangeSettingsProvider
  • System.Data.DataViewManager, System.Xml.XmlDocument/XmlDataDocument
  • System.Management.Automation.PSObject

Language-Agnostic Methods for Deserializing Safely

Using Alternative Data Formats

A great reduction of risk is achieved by avoiding native (de)serialization formats. By switching to a pure data format like JSON or XML, you lessen the chance of custom deserialization logic being repurposed towards malicious ends.

Many applications rely on a data-transfer object pattern that involves creating a separate domain of objects for the explicit purpose data transfer. Of course, it’s still possible that the application will make security mistakes after a pure data object is parsed.

Only Deserialize Signed Data

If the application knows before deserialization which messages will need to be processed, they could sign them as part of the serialization process. The application could then to choose not to deserialize any message which didn’t have an authenticated signature.

Patient safety assistant

Check your symptom safely

Hi, I am RX Symptom Navigator. I can help you understand what to read next and what warning signs need care.
Warning: Do not use this in emergencies, pregnancy, severe illness, or as a substitute for a doctor. For children or teens, use with a parent/guardian and clinician.
A rural-friendly guide: warning signs, when to see a doctor, related articles, tests to discuss, and OTC safety education.
1 Symptom 2 Severity 3 Safe guidance
First safety question

Is there chest pain, breathing trouble, fainting, confusion, severe bleeding, stroke-like weakness, severe injury, or pregnancy danger sign?

Choose quickly

Browse by body area
Start here: Write or select a symptom. The guide will show warning signs, doctor guidance, diagnostic tests to discuss, OTC safety education, and related RX articles.

Important: This tool is educational only. It cannot diagnose, treat, or replace a doctor. OTC information is not a prescription. In an emergency, contact local emergency services or go to the nearest hospital.

Doctor visit helper

Prepare before seeing a doctor

A simple rural-patient checklist to help you explain symptoms clearly, ask better questions, and avoid unsafe self-treatment.

Safety note: This is not a prescription or diagnosis. For severe symptoms, pregnancy danger signs, children with serious illness, chest pain, breathing difficulty, stroke-like weakness, or major injury, seek urgent care.

Which doctor may help?

Start with a registered doctor or the nearest qualified health center.

What to tell the doctor

  • Write when the problem started and how it changed.
  • Bring old prescriptions, investigation reports, and current medicines.
  • Write allergies, pregnancy status, diabetes, kidney/liver disease, and major past illnesses.
  • Bring one family member if the patient is weak, elderly, confused, or a child.

Questions to ask

  • What is the most likely cause of my symptoms?
  • Which danger signs mean I should go to hospital quickly?
  • Which tests are necessary now, and which can wait?
  • How should I take medicines safely and what side effects should I watch for?
  • When should I come for follow-up?

Tests to discuss

  • Vital signs: temperature, pulse, blood pressure, oxygen saturation
  • Basic physical examination by a clinician
  • CBC, urine test, blood sugar, or imaging only when clinically needed

Avoid these mistakes

  • Do not use antibiotics, steroid tablets/injections, or strong painkillers without proper medical advice.
  • Do not hide pregnancy, kidney disease, ulcer, allergy, or blood thinner use.
  • Do not delay emergency care when danger signs are present.

Medicine safety and first-aid guide

This section is for patient education only. It does not replace a doctor, pharmacist, or emergency care.

Safe first steps

  • Avoid heavy lifting, sudden bending, and prolonged bed rest.
  • Use comfortable posture and gentle movement as tolerated.
  • Discuss physiotherapy, X-ray, or MRI only when clinically needed.

OTC medicine safety

  • For mild back pain, pain-relief medicine may be discussed with a doctor or pharmacist.
  • Avoid repeated painkiller use if you have kidney disease, stomach ulcer, uncontrolled blood pressure, or are taking blood thinners.

Avoid these mistakes

  • Do not start antibiotics without a proper medical decision.
  • Do not use steroid tablets or injections casually for quick relief.
  • Do not delay emergency care because of home remedies.

Get urgent help if

  • Back pain with leg weakness, numbness around private area, loss of urine/stool control, fever, cancer history, or major injury needs urgent care.
Medicine names, dose, and timing must be decided by a qualified clinician or pharmacist after checking age, pregnancy, allergy, other diseases, and current medicines.

For rural patients and family caregivers

Patient health record and symptom diary

Write your symptoms, medicines already taken, test results, and questions before visiting a doctor. This note stays on your device unless you print or copy it.

Doctor to discuss: Doctor / qualified healthcare provider
Tests to discuss with doctor
  • Basic vital signs: temperature, pulse, blood pressure, oxygen level if needed
  • Relevant blood, urine, imaging, or specialist tests only after clinical assessment
Questions to ask
  • What is the most likely cause of my symptoms?
  • Which warning signs mean I should go to emergency care?
  • Which tests are really needed now?
  • Which medicines are safe for my age, pregnancy status, allergy, kidney/liver/stomach condition, and current medicines?

Emergency warning signs such as chest pain, severe breathing difficulty, sudden weakness, confusion, severe dehydration, major injury, or loss of bladder/bowel control need urgent medical care. Do not wait for online information.

Safe pathway to proper treatment

Back pain care roadmap

Use this simple roadmap to understand the next safe steps. It is educational and does not replace examination by a doctor.

Go to emergency care if you notice:
  • New leg weakness, numbness around private area, or loss of bladder/bowel control
  • Back pain after major injury, fever, unexplained weight loss, cancer history, or severe night pain
Doctor / service to discuss: Orthopedic/spine specialist, physical medicine doctor, physiotherapist under guidance, or qualified clinician.
  1. Step 1

    Check danger signs first

    If danger signs are present, seek emergency care and do not wait for online information.

  2. Step 2

    Record the symptom story

    Write when symptoms started, severity, medicines already taken, allergies, pregnancy status, and test results.

  3. Step 3

    Visit a qualified clinician

    A doctor, nurse, or qualified healthcare provider can examine you and decide which tests or treatment are needed.

  4. Step 4

    Do only useful tests

    Discuss neurological examination first. X-ray or MRI may be needed only when red flags, injury, nerve weakness, or persistent severe symptoms are present.

  5. Step 5

    Follow up and return early if worse

    If symptoms worsen, new warning signs appear, or treatment is not helping, return for review quickly.

Rural patient practical tips
  • Take a written symptom diary and all previous prescriptions/test reports.
  • Do not hide medicines already taken, even herbal or over-the-counter medicines.
  • Ask which warning signs mean urgent referral to hospital.
  • Avoid forceful massage or bone-setting when there is weakness, injury, fever, or nerve symptoms.

This roadmap is for education. A real diagnosis and treatment plan requires history, examination, and clinical judgment.

RX Patient Help

Ask a health question safely

Write your symptom story. A health professional or site editor can review it before any answer is prepared. This box is not for emergency care.

Emergency first: Severe chest pain, breathing trouble, unconsciousness, stroke signs, severe injury, heavy bleeding, or rapidly worsening symptoms need urgent local medical care now.

Frequently Asked Questions

Is this article a replacement for a doctor?

No. It is educational content only. Patients should consult a qualified clinician for diagnosis and treatment.

When should I seek urgent care?

Seek urgent care for severe symptoms, rapidly worsening condition, breathing difficulty, severe pain, neurological changes, or any emergency warning sign.

References

Add references, clinical guidelines, textbooks, journal articles, or trusted medical sources here. You can edit this area from the RX Article Professional Blocks panel.