Current Location: Home> Latest Articles> serialize and unserialize security: How to prevent object injection attacks?

serialize and unserialize security: How to prevent object injection attacks?

gitbox 2025-05-19

As a widely used server-side programming language, PHP occupies an important position in web development. As more and more PHP applications are exposed to the Internet, security issues are gradually becoming the focus of developers. In PHP, serialize() and unserialize() functions are widely used to handle the serialization and deserialization of objects and arrays. However, these functions can also become potential vulnerabilities for attackers to conduct "object injection attacks". If not prevented, an attacker can change the behavior of the application through carefully constructed malicious data, and even lead to serious security issues such as remote code execution (RCE).

This article will analyze the security issues of serialize() and unserialize() functions in PHP, and provide effective measures to prevent object injection attacks.

Overview of serialize and unserialize functions in PHP

serialize() and unserialize() are two important functions in PHP for object and array serialization and deserialization.

  • serialize() : converts PHP variables (including objects, arrays, etc.) into strings that can be stored or transferred. For example, you can convert an object or array into a string and store it in a database.

  • unserialize() : It is to reconvert a serialized string to PHP's original data type (such as an object or an array).

 $data = ['name' => 'John', 'age' => 30];
$serializedData = serialize($data);
echo $serializedData;  // Output:a:2:{s:4:"name";s:4:"John";s:3:"age";i:30;}

The above code serializes an array $data into a string. If you store it in the database, you can later restore it to the original array via unserialize() .

The principle of object injection attack

Object Injection attack refers to the attacker constructing special serialized data, so that the PHP unserialize() function executes malicious code or changes the behavior of the application when deserializing the data. This type of attack usually occurs when PHP applications do not fully verify the input data.

For example, suppose an attacker constructs the following malicious data:

 $maliciousData = 'O:8:"UserClass":1:{s:4:"name";s:4:"evil";}';
unserialize($maliciousData);

Among them, UserClass is a class in the application. The attacker creates a malicious object through the serialized data and passes it to the unserialize() function without verification, thereby triggering the object's constructor and may lead to security vulnerabilities.

How to prevent object injection attacks?

In order to prevent object injection attacks, developers can take the following effective measures:

1. Disable automatic loading of untrusted classes

During the deserialization process, the unserialize() function will attempt to load the class if the data contains a class name. If the class exists in the application without proper security measures, malicious objects may be created and executed. Therefore, the classes that are allowed to be loaded during deserialization can be restricted by unserialize() 's allowed_classes parameter.

 $data = 'O:8:"UserClass":1:{s:4:"name";s:4:"evil";}';
$unserializedData = unserialize($data, ['allowed_classes' => ['UserClass']]);

If the class name is not explicitly listed, PHP will not allow deserialization of data containing unknown class names.

2. Filter and verify input data

Strictly verify and filter incoming serialized data to ensure that it does not contain any bad content. Before accepting data, you can use regular expressions or other methods to check whether the structure of a serialized string is legal.

 if (preg_match('/^[O|a|s|i|d|b|f|N|r|C|l|n]/', $inputData)) {
    $unserializedData = unserialize($inputData);
} else {
    die('Invalid serialized data');
}

3. Use JSON instead of serialization

If there are no special requirements, it is recommended to use json_encode() and json_decode() instead of serialize() and unserialize() . json_encode() and json_decode() are not easily exploited for object injection attacks, because they can only handle simple data types (such as arrays, objects, strings, numbers, etc.) and will not involve complex classes and objects.

 $data = json_encode($dataArray);
$decodedData = json_decode($data, true);

4. Use PHP's configuration files to disable dangerous functions

In the php.ini configuration file, security can be enhanced by disabling specific functions to avoid the developers' accidental use of these functions. To prevent attackers from causing security vulnerabilities through unserialize() , they can disable the unserialize() function or limit it to a trusted range.

 disable_functions = "unserialize"

5. Use the latest version of PHP and security patches

The PHP community regularly releases updates and security patches to fix potential security vulnerabilities. Developers should always use the latest version of PHP and update the system in a timely manner to ensure security.

Practical protection: security best practices when processing sensitive data

In addition to directly protecting serialize() and unserialize() functions, developers also need to strengthen overall security management of sensitive data. Here are some security best practices:

  1. Encrypted sensitive data : For sensitive data stored or transmitted, encrypted using strong encryption algorithms, such as AES encryption, to ensure that even if the attacker obtains the data, it cannot be easily cracked.

  2. Input Verification : Strictly verify all user input, especially data received through URLs, forms, or APIs. Existing libraries can be used to help prevent common attacks such as SQL injection, XSS, and CSRF.

  3. Minimize object exposure : Try to avoid exposing sensitive or complex objects directly to the client. The data that needs to be serialized should contain only the necessary information.

Summarize

The serialize() and unserialize() functions in PHP provide developers with convenient data storage and transmission mechanisms, but using them without restrictions will pose serious security risks. Through reasonable configuration, input verification, use of alternatives and timely update of PHP versions, object injection attacks can be effectively prevented.

The most important thing is: Never trust user input! Reasonable security strategies and protective measures can effectively improve the security of applications and reduce potential risks.