Part6 SW SEC Insecure Deserialization

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 36

SOFTWARE

SECURITY
INSECURE DESERIALIZATION
Outline
• Introduction into Serialization
• What is Serialization for?
• Serialization for storing and transmitting data objects
• What is deSerialization?
• Insecure deSerialization
• Deserialization vulnerability
• Programming language support serialization
• Examples:
• Deserialization vulnerability in Java
• Deserialization vulnerability in Python
• Deserialization vulnerability in PHP
• Exploiting PHP deserialization
Introduction into Serialization

• Serialization is the mechanism in which the state of an object is converted to a


byte stream (byte stream can be stored in or written into a file) so that the byte
stream can be reverted back into the copy of the object (Object in its original state
can not be stored in a file).
• Byte stream can include information about object’s type and types of data stored in
the object.
Introduction into Serialization

• A stream is simply a sequence of data elements.


• Data in the form of streams is generated from a source and consumed at a
destination.
• Different data streams in the computer systems are:
Introduction into Serialization

1. Byte Stream – It is a low level I/O operation (read/write binary data) and does not
have any encoding scheme.
byte[] data = { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100 };
Introduction into Serialization

2. Data Stream – Data Stream allows to read-write primitive data types and used
to perform binary I/O operations on primitive data types.
• I/O operations can be performed for byte, char, boolean, short, int, long, float,
double and strings efficiently and conveniently.

try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.bin"))) {

{ dos.writeInt(42); // Write an integer


dos.writeDouble(3.14); // Write a double
dos.writeBoolean(true); // Write a boolean
dos.writeUTF("Hello"); // Write a UTF-encoded string

}
}
Introduction into Serialization

3. Character Stream – The character stream can easily translate to and from local
character set unlike byte stream.
• It has a proper encoding scheme such as UNICODE; and is composed of streams
of characters. In Java, UNICODE system is followed to store characters as
character stream.
Introduction into Serialization

4. Object Stream – Object stream can covert the state of an object into a byte stream so that
it can be stored into a database, file or transported to any location (Serialization) and used at
a later point of time for retrieving the stored values and restoring the old state of the object
(deSerialization).
• The process of serialization is instance independent which means an object can be
serialized on one platform and deserialized on a different platform. To make an object
serializable we use java.io.Serializable interface.
So you want to save your data ...
Common problem:
You have built a large, c o m p l e x o b j e c t
• Spam/Normal statistics tables
• Game state
• Database of student records
• etc ...

• Want to store on disk and retrieve later


• Or: want to send over network to another Java process

• In general: want your objects to be persistent-­outlive the


current Java process
Serialization for storing and transmitting
data objects
• Serialization is the process of turning some object into a data format
that can be restored later.
• Data stream can be stored on disk or database or transmitted over the
network

• People often serialize objects in order to save them to storage, or to


send as part of communications.
What is deSerialization?

• Deserialization is the reverse of that process taking data structured from some format, and rebuilding it
into an object.

1. disassemble serialize; prepare


for transport
at the sale point
2. Assemble  deSerialize
at the destination
Insecure deSerialization

• Serialization can be manipulated to perform tasks that were not the


original intent of the developer.
• The user will be able to detect insecure deserialization vulnerabilities
• The user will be able to exploit insecure deserialization vulnerabilities

High quality screw Replaced by Low quality screw


Serialize and deSerialize
Deserialization vulnerability

• Native Serialization
• Many programming languages support native serialization.

• Native serialization refers to the built-in capability of programming languages to


serialize objects into a format that can be easily stored or transmitted and then
deserialize them back into their original form.
• Eg., in Java, native serialization is achieved through java.io.Serializable interface to allow
objects to be serialized.
• in Python, native serialization is facilitated using pickle module to allow objects to be
serialized and deserialized.
Deserialization vulnerability

• Native Serialization
• Many programming languages support native serialization.
• Native formats offer more features than JSON or XML.
• Features include customizability of the serialization process.
• Unfortunately, features of these native deserialization mechanisms
can be repurposed for (modified to serve) malicious effect when
operating on untrusted data.
Deserialization vulnerability

• Native Serialization

• THUS:
• If deSerialization is not properly implemented or secured, it can be
exploited by attackers to carry out various types of attacks such as DoS
and remote code execution.

• The risk increases when untrusted user input is deserialized.

 That means the vulnerability happens during deSerialization.


Serialization in Java
Deserialization vulnerability in Java

• Java provides serialization where object represented as sequence of bytes,


serialization process is JVM independent, which means an object can be
serialized in a platform and de-serialized on different platforms.
• Java implements serialization using class interface Java.io.Serializable, to serialize
an object to implement classes ObjectInputStream and ObjectOutputStream
those classes contains several methods to write/read objects.

ObjectOutputStream ObjectInputStream
writeObject: The method writeObject is readObject: Read an object from the
used to write an object to the stream ObjectInputStream.
import java.io.*;
public class Main {
In this example, public static void main(String[] args) {
try {
// Serialize the object
the Employee class implements the FileOutputStream fileOut = new FileOutputStream("employee.ser");
Serializable interface, allowing its ObjectOutputStream out = new ObjectOutputStream(fileOut);
instances to be serialized and Employee emp = new Employee("John Doe", "123456");
deserialized using out.writeObject(emp);
out.close();
ObjectOutputStream and fileOut.close();
ObjectInputStream. System.out.println("Serialized data is saved in employee.ser");
// Deserialize the object
FileInputStream fileIn = new FileInputStream("employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
The ssn field is marked as transient Employee deserializedEmp = (Employee) in.readObject();
to prevent it from being serialized. in.close();
fileIn.close();
However, an attacker can modify the System.out.println("Deserialized Employee: " + deserializedEmp.toString());
}
serialized data to include a malicious }
payload so that can lead to a }
deserialization vulnerability. class Employee implements Serializable {
private transient String ssn; // Transient field
}
Serialization in Python
Deserialization vulnerability in
Python •The pickle module is used for serialization and
deserialization.
import pickle •An Employee class is defined with name and ssn
attributes.
class Employee:
def __init__(self, name, ssn): •The serialize_employee() function creates an Employee
self.name = name object, serializes it using pickle.dumps(), and writes it to
self.ssn = ssn
a file. The pickle will dump items.
# Serialize the object
def serialize_employee(): •The deserialize_employee() function reads the serialized
employee = Employee("John Doe", "123-45-6789") data from file, deserializes it using pickle.loads(), and
serialized_employee = pickle.dumps(employee) prints the deserialized Employee object.
with open("employee.pickle", "wb") as file:
file.write(serialized_employee)
print("Serialized data is saved in employee.pickle") •Running this code as-is is safe. However, if an attacker
gains access to the serialized data and manipulates it
# Deserialize the object before deserialization, they could execute inserted
def deserialize_employee(): code.
with open("employee.pickle", "rb") as file:
serialized_employee = file.read()
deserialized_employee = pickle.loads(serialized_employee) •It is possible to construct malicious pickle data which will
print("Deserialized Employee: Name =", execute arbitrary code during unpickling. Never unpickle
deserialized_employee.name, ", SSN =", data that could have come from an untrusted source.
deserialized_employee.ssn)
Serialization in PHP
Deserialization vulnerability in •The serialize() function is used to serialize the
PHP Employee object and store it in a file named
<?php
class Employee { employee.txt.
public $name;
public $ssn; •The unserialize() function is used to deserialize
public function __construct($name, $ssn) { the data from the file and recreate the Employee
$this->name = $name; object.
$this->ssn = $ssn;
} •Running this code is safe. However, if an
} attacker gains access to serialized data and
// Serialize the object manipulates it before deserialization, they could
function serialize_employee() { execute code.
$employee = new Employee("John Doe", "123-45-6789");
$serialized_employee = serialize($employee); serialize() object i/p
file_put_contents("employee.txt", $serialized_employee);
echo "Serialized data is saved in employee.txt";
employee.txt file  o/p
}
employee.txt file  i/p
// Deserialize the object serialize() object o/p
function deserialize_employee() {
$serialized_employee = file_get_contents("employee.txt");
$deserialized_employee = unserialize($serialized_employee);
echo "Deserialized Employee: Name = " . $deserialized_employee->name . ", SSN = " . $deserialized_employee-
>ssn;
}

serialize_employee();
deserialize_employee();
?>
Exploiting PHP deserialization
• When a serialized object is controlled, properties of the created object will be
controlled.
• Attacker might be able to hijack the flow of the application by controlling the
values passed into automatically executed methods like __wakeup() or __destruct().
Exploiting PHP deserialization
Components of the serialized string:

O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:9:"not admin";}
Component Description
O Indicates the object type (in this case, Object)
4 Length of the class name (User)
"User" Class name
2 Number of properties
{...} Encapsulates the properties of the object
s:8:"username"; Property: username
s:6:"vickie"; Value assigned to username: Vickie
s:6:"status"; Property: status
s:9:"not admin"; Value assigned to status: not admin
Exploiting PHP deserialization
• This is called a PHP object injection.
• PHP object injection can lead to 1) variable manipulation, 2) code execution, 3) SQL
injection, 4) path traversal, or 5) DoS.

1. Controlling variable values


• One possible way to exploit a PHP object injection vulnerability is variable
manipulation. For example, you can mess with the values encoded in the serialized
string.
O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:9:"not admin";}
• In this serialize string, you can try to change the value of “status” to “admin”, and see if
the application grants you admin privileges.
O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:5:"admin";}
Exploiting PHP deserialization
2. Code execution

• Serialized string 
O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:9:"not admin";}

• Modified serialized string with injected PHP code 


O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:28:"not admin";system('rm -rf /');}

• This is a modified serialized string contains injected PHP code within "status"
variable, after value "not admin", that is an additional PHP code enclosed within
single quotes: system('rm -rf /');.
Exploiting PHP deserialization
2. Code execution

• Modified serialized string with injected PHP code 


O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:28:"not admin";system('rm -rf /');}

• This PHP code attempts to execute the command rm -rf /.


• This command recursively deletes all files and directories starting from the root directory
("/") of the server’s file system.
• An attacker can exploit PHP object injection to execute commands on server to cause
severe damage such as to attempt to erase entire OS
Exploiting PHP deserialization
2. Code execution
O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:28:"not admin";system('rm -rf /');}

• system: this is a PHP function used to execute shell commands.

• 'rm -rf /’: this is the shell command being executed. It consists of the following parts:
• rm: denotes for remove.
• -rf:
• -r : “recursive” ie. delete directories and their contents recursively,
• -f : “force” ie. - non-existent files and never prompt for confirmation.
• /: the starting point from which the command will recursively delete all files and
directories.
Exploiting PHP deserialization
3. SQL injection

• Serialized string 
O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:9:"not admin";}

• Modified serialized string with injected SQL code 

O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:18:"not admin'; DROP TABLE users;";}

Note: a single quote ' closes the original SQL string.


Exploiting PHP deserialization
3. SQL injection

O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:18:"not admin'; DROP TABLE


users;";}

• In the modified serialized string, “status” variable has been tampered with to include
additional SQL code.
• After “not admin” value , there is a semicolon followed by SQL command DROP TABLE
users;
to attempt to delete “users” table from database.
This SQL injection can allow an attacker to insert malicious SQL code into an input field
to manipulate database or execute unauthorized operations.
Exploiting PHP deserialization
4. Path traversal (i.e., passing across)
• Serialized string 
O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:9:"not admin";}

• Modified serialized string with injected path traversal 


O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:29:"not ../../../../../etc/passwd";}

• Attacker manipulates the serialized string by injecting a path traversal payload into
“status”.
Exploiting PHP deserialization
4. Path traversal (i.e., passing across)
• Attacker manipulates the serialized string
O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:29:"not
../../../../../etc/passwd";} by injecting a path traversal payload into
“status”.
• Payload = “../../../../../etc/passwd”.
• Payload attempts to navigate
upwards in directory structure
(using “../”) to reach desired root(s)
to access “/etc/passwd” file.
• “/etc/passwd” is a targeted file in
Unix; it stores user account
information.
• If an attacker successfully injected
this payload and accessed
“/etc/passwd” file, sensitive
information about user accounts on
server could be retrieved.
https://www.hackingarticles.in/comprehensive-guide-on-path-traversal/
Exploiting PHP deserialization
5. DoS
• Serialized string 
O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:9:"not admin";}
• Modified serialized string with injected malicious payload 
O:4:"User":2:{s:8:"username";s:6:"vickie";s:6:"status";s:100000:"not admin";}

• Attacker exploits the PHP object injection vulnerability by injecting a large value into
“status” of the serialized object.
• This injected value (payload) is larger than necessary or expected  application will allocate a
large amount of memory.
• As a result, application becomes unable to handle legitimate user requests.
• That leads to DoS situation where the application may become slow or unresponsive.
Preventing exploiting PHP
deserialization
PHP object injection security countermeasure security countermeasure 2 How to
1 prevent
Variable Input validation Data integrity checks: use digital signatures or exploiting
manipulation checksums to make sure that data has not been tampered. PHP insecure
deserialization
Code execution Input validation Code whitelisting: only accept input that matches
predefined patterns or formats & reject anything else. 
SQL injection Parameterized queries Least privilege principle: 1) grant minimal database
privileges to application users; 2) ensure that application
accounts have only the necessary permissions.
Path traversal Input validation Validate file paths: ensure that deserialized file paths are
within the intended scope and do not allow access to
sensitive system files.

DoS Input validation Limit payload size: set limits on the size of serialized
objects or fields within the serialized data; to prevent
attackers from injecting large payloads.

You might also like