Skip to content

Lab 02 — Processes, /proc and Signals

After this lab you will be able to point at any running process on a Linux machine or an Android device and read its complete identity out of /proc — who it runs as, what it has open, what namespace it lives in, whether anything is debugging it — and you will have watched the TracerPid field change from 0 to a debugger's PID with your own eyes, because that single line of a single generated file is the most-checked anti-debugging signal in mobile security.

Chapter: 02 — Linux Basics Difficulty: Intermediate Estimated time: 3 to 4 hours Prerequisite lab: Lab 01 — Filesystem, permissions and the Android layout Also assumes: 01 — Computer Science Basics, whose Lab 02 covers /proc/<pid>/maps in depth. This lab deliberately does not repeat that; it covers everything else under /proc/<pid>/.


Objective

Lab 01 dealt with files at rest. This lab deals with programs in motion, and with the one interface Linux gives you for looking at them.

There is a reason this material is worth several hours. Almost everything a hardened Android app does to resist analysis is a read of a file under /proc, and almost everything you do to analyse it is a read of the same files. Root detection reads /proc/self/mounts. Debugger detection reads /proc/self/status. Frida detection reads /proc/self/maps and /proc/net/tcp. Emulator detection reads /proc/cpuinfo. When you understand what those files are and what normal looks like in each of them, the entire anti-analysis genre becomes legible at once.

By the end you will have:

  • Listed processes and explained every column of ps on both a laptop and a phone.
  • Read /proc/<pid>/status line by line and explained the fields that matter.
  • Decoded the four numbers on the Uid: line and said which one permission checks use.
  • Read the NUL-separated cmdline and environ files correctly, and explained why cat mangles them.
  • Followed exe, cwd, root and fd/ — the four magic symlinks — and explained what each proves.
  • Listed a process's threads through task/, its limits through limits, and its namespaces through ns/.
  • Sent every signal that matters and observed the result.
  • Used kill -3 against an Android app to obtain a complete Java thread dump for free.
  • Attached a debugger and watched TracerPid go from 0 to a PID and back to 0.
  • Written, in your own words, the three ways an app detects a debugger and the three ways each is defeated.

Definition — Process An executing instance of a program: a private virtual address space, one or more threads, a set of credentials (real, effective, saved-set and filesystem UIDs and GIDs plus supplementary groups), an open file descriptor table, a signal disposition table, a working directory, a root directory, a set of namespaces, and a resource-limit set. The kernel holds all of that in one structure per task. /proc/<pid>/ is a window onto it.

Definition — /proc A pseudo-filesystem: a filesystem whose contents are generated by the kernel at the instant you read them, backed by no storage at all. cat /proc/uptime calls a kernel function that formats the current uptime into your buffer. This is why every file in /proc reports size 0, why you cannot patch one ahead of time, and why /proc/self resolves differently for every reader.


Prerequisites

Requirement Why Check
Linux, WSL 2, or a Linux VM /proc does not exist on Windows or macOS ls /proc/self/
gdb or strace installed on the host Part F needs something that calls ptrace which gdb strace
An Android device or emulator with USB debugging Parts C, E, F adb devices
Root on the device, or a debuggable app, or an emulator with adb root /proc/<pid>/maps, fd, environ need the owning UID See Setup
Lab 01 completed You will be reading modes and ownership constantly —

Install what is missing on the host:

# host / WSL — Debian or Ubuntu
sudo apt update && sudo apt install -y gdb strace procps

Warning ptrace is how debuggers work, and attaching to a process you do not own requires privilege. Attach only to processes you started yourself, on machines and devices you own or are explicitly authorised to test. Attaching to an app with anti-debug protection may crash it — that is not a tool failure, it is the finding.


Setup

1. A long-lived process to inspect on the host

# host / WSL
sleep 3600 &
SLEEP_PID=$!
echo "sleep is PID $SLEEP_PID"
ls -d /proc/$SLEEP_PID
[1] 48213
sleep is PID 48213
/proc/48213

& puts the job in the background; $! holds the PID of the most recent background job. Keep that number, you will use it constantly. If you close the terminal, redo this step.

2. Confirm device access and pick a target app

# host
adb devices -l
adb shell id
adb shell 'ps -A | head -5'

For an app target, the easiest options in order of preference:

# host — option A: emulator with a non-Play system image
adb root
adb shell id                    # should now say uid=0(root)

# host — option B: your own debuggable build
adb shell run-as com.example.app id

# host — option C: any app, for the parts that only need public /proc entries
adb shell pidof com.android.settings

3. Scratch space on the device

# adb shell
mkdir -p /data/local/tmp/lab02
cd /data/local/tmp/lab02

Steps

Part A — ps: what is running, and as whom

A1. List processes on the host.

# host / WSL
ps
ps aux | head -10
ps -eo pid,ppid,uid,user,stat,pri,ni,rss,vsz,wchan,comm --sort=-rss | head -15

The bare ps shows only your own terminal's processes, which is why it looks uselessly short. ps aux (BSD syntax) and ps -ef (System V syntax) both mean "everything"; the two syntaxes coexist for historical reasons and both are accepted.

A2. Every column, and why you care.

Column Meaning Why it matters
PID Process ID, assigned by the kernel The key to everything: /proc/<pid>, kill, frida -p
PPID Parent's PID On Android almost every app's parent is zygote64. A process whose parent is not zygote did not start the normal way
UID / USER Owning user On Android this is the sandbox. App UIDs are 10000–19999
STAT / S State letter, sometimes with modifiers See A3
PRI / NI Scheduling priority and nice value Android uses cgroups more than nice; rarely interesting
RSS Resident set size, in KB — physical memory in use Overcounts shared pages
VSZ Virtual size, in KB — address space reserved Always far larger than RSS; reserving address space is nearly free
WCHAN Kernel function the process is blocked in Tells you what it is waiting for, not just that it waits
COMM / CMD Command name or full command line On Android the command name is the process name, usually the package

A3. Process states. The letter is not decoration.

Letter State What it means When you see it
R Running or runnable On a CPU, or queued for one Busy work
S Interruptible sleep Waiting for something, can be woken by a signal The normal state of almost everything
D Uninterruptible sleep Waiting on I/O; cannot be killed, not even with SIGKILL A hung storage or driver operation
T Stopped Suspended by SIGSTOP, or by Ctrl+Z Job control
t Tracing stop Stopped because a tracer is attached A debugger, Frida in attach mode, or an anti-debug self-trace
Z Zombie Exited, but the parent has not collected the exit status A parent that never calls wait()
I Idle kernel thread Kernel worker with nothing to do Only kernel threads

The t state and the TracerPid field of Part F are the same fact seen through two windows.

A4. On the device.

# adb shell
ps -A -o PID,PPID,USER,S,RSS,VSZ,NAME | head -30
ps -A | grep -i zygote
ps -A | wc -l
  PID  PPID USER     S     RSS      VSZ NAME
    1     0 root     S    6612  10932352 init
  483     1 root     S   14208  11324928 zygote64
 2145   483 u0_a231  S  187364  15234048 com.example.app
 3012   483 u0_a245  S   94112  14893056 com.other.app

A5. Prove the zygote relationship.

# adb shell
ZYGOTE=$(pidof zygote64); echo "zygote64 = $ZYGOTE"
APP=$(pidof com.android.settings); echo "app = $APP"
grep -E '^(Name|PPid)' /proc/$APP/status

The app's PPid equals zygote's PID. Every ordinary Android app process is a fork of the same already-warmed parent, which is why app startup takes milliseconds rather than seconds and why every app's framework libraries sit at identical addresses. The specialisation step where the fork becomes "your app" — new UID, new SELinux context, capability drop, seccomp install, umask — is covered in 09 — Android App Internals.

Pentester's Note A process on an Android device whose PPid is 1 (init) rather than zygote's PID is either a native daemon declared in an .rc file, or something that was started by other means — a shell command, an injected process, frida-server. Enumerating processes by parent is a fast triage step on a device you did not set up.


Part B — /proc/<pid>/status, line by line

This is the file. Learn it properly and half of Android anti-analysis becomes obvious.

B1. Read the whole thing.

# host / WSL
cat /proc/$SLEEP_PID/status
Name:   sleep
Umask:  0022
State:  S (sleeping)
Tgid:   48213
Ngid:   0
Pid:    48213
PPid:   47990
TracerPid:  0
Uid:    1000    1000    1000    1000
Gid:    1000    1000    1000    1000
FDSize: 256
Groups: 4 24 27 30 46 1000
NStgid: 48213
NSpid:  48213
NSpgid: 48213
NSsid:  47990
VmPeak:     5476 kB
VmSize:     5476 kB
VmRSS:       764 kB
Threads:    1
SigQ:   0/62793
SigPnd: 0000000000000000
ShdPnd: 0000000000000000
SigBlk: 0000000000000000
SigIgn: 0000000000000000
SigCgt: 0000000000000000
CapInh: 0000000000000000
CapPrm: 0000000000000000
CapEff: 0000000000000000
CapBnd: 000001ffffffffff
NoNewPrivs: 0
Seccomp:    0
Speculation_Store_Bypass:   thread vulnerable
Cpus_allowed_list:  0-15
voluntary_ctxt_switches:    1
nonvoluntary_ctxt_switches: 0

B2. The fields that matter, and why.

Field Meaning Security relevance
Name Executable name, truncated to 15 characters Trivially spoofable with prctl(PR_SET_NAME). Malware and injected agents rename themselves. Never trust it alone
Umask The process's current file-creation mask Confirms Zygote's default; a process with umask 0000 will create world-writable files
State Scheduler state with its letter t (tracing stop) means something is attached right now
Tgid Thread group ID — the number userspace calls "the PID" Equals Pid for the main thread
Pid The kernel task ID. For a thread this differs from Tgid This is what gettid() returns
PPid Parent 1 means the parent died and init adopted it
TracerPid PID of the process ptrace-attached to this one, or 0 The single most-checked anti-debugging field in mobile security. Part F
Uid Four numbers: real, effective, saved-set, filesystem Permission checks use the filesystem UID, which normally tracks the effective UID
Gid The same four, for groups
Groups Supplementary group IDs On Android, 3003 here means the app holds the INTERNET permission
FDSize Allocated slots in the descriptor table (not the number open) A large value hints at a descriptor leak
Threads Threads in this group An idle Android app has dozens
SigBlk / SigIgn / SigCgt Hex bitmasks of blocked, ignored and caught signals SigCgt tells you which signals the process installed handlers for — including whether it handles SIGSEGV itself, which packers and crash reporters do
CapPrm / CapEff / CapBnd Capability bitmasks: permitted, effective, bounding How much of root's power this process actually has. An app process should be all zeros
NoNewPrivs 1 means the process can never gain privileges via setuid Set on Android app processes
Seccomp 0 disabled, 1 strict, 2 filter installed Android sets 2 on app processes
NSpid The PID as seen inside its PID namespace If this differs from Pid, the process is in a nested PID namespace
voluntary_ctxt_switches Times it gave up the CPU willingly A process that is spinning shows a huge nonvoluntary count

B3. Decode the Uid: line. Four numbers, and the order never changes:

Uid:    1000    1000    1000    1000
        │       │       │       └── filesystem UID (fsuid)  ← file permission checks use THIS
        │       │       └────────── saved set-user-ID       ← what you can switch back to
        │       └────────────────── effective UID (euid)    ← most other permission checks
        └────────────────────────── real UID (ruid)         ← who launched it

They are all equal in the ordinary case. They diverge when a setuid binary runs:

# host / WSL — watch a setuid binary's credentials while it is running.
# `passwd` waits for input, so it stays alive long enough to inspect.
passwd &
PW=$!
sleep 1
grep -E '^(Name|Uid|Gid)' /proc/$PW/status
kill $PW
Name:   passwd
Uid:    1000    0   0   0
Gid:    1000    1000    1000    1000

The real UID is still you (1000). The effective, saved and filesystem UIDs are 0. That is the setuid bit from Lab 01, observed in a live process. On Android the same divergence appears while run-as is transitioning, and any unexpected divergence in an app process is worth investigating.

B4. Read an app's identity on the device.

# adb shell
PID=$(pidof com.android.settings)
grep -E '^(Name|State|Tgid|PPid|TracerPid|Uid|Gid|Groups|Threads|Seccomp|NoNewPrivs|CapEff)' /proc/$PID/status
Name:   ndroid.settings
State:  S (sleeping)
Tgid:   2145
PPid:   483
TracerPid:  0
Uid:    1000    1000    1000    1000
Gid:    1000    1000    1000    1000
Groups: 1001 1002 1003 1004 3002 3003 ...
Threads:    42
CapEff: 0000000000000000
NoNewPrivs: 1
Seccomp:    2

Note Name is truncated to 15 characters — com.android.settings becomes ndroid.settings because the front is cut, not the back. This trips people up when grepping.

Map the UID back to a package:

# adb shell
cmd package list packages --uid 10231
# or, on older builds
pm list packages -U | grep 10231

B5. Compare two apps. Pick one with the INTERNET permission and one without (a simple offline utility, or one you build yourself), and diff their Groups lines. GID 3003 is the only difference that matters. There is no framework check involved in an app's ability to open a socket — it is a Linux group membership, checked by the kernel.


Part C — cmdline, environ, and the NUL problem

C1. The confusing output.

# host / WSL
cat /proc/$SLEEP_PID/cmdline; echo
sleep3600

Where did the space go? There never was one. The kernel stores the original argv array as a sequence of NUL-terminated strings laid end to end, and a terminal draws a NUL as nothing at all. This is lossless — an argument containing a space stays one argument — but unreadable.

C2. Read it properly.

# host / WSL — one argument per line
tr '\0' '\n' < /proc/$SLEEP_PID/cmdline

# host / WSL — spaces, if you prefer
tr '\0' ' ' < /proc/$SLEEP_PID/cmdline; echo

# host / WSL — see the actual bytes and prove the separator is 0x00
xxd /proc/$SLEEP_PID/cmdline
sleep
3600

sleep 3600

00000000: 736c 6565 7000 3336 3030 00              sleep.3600.

There it is: 73 6c 65 65 70 is sleep, then 00, then 33 36 30 30 is 3600, then 00.

C3. The same applies to environ.

# host / WSL — variable names only; values often contain secrets
tr '\0' '\n' < /proc/$SLEEP_PID/environ | cut -d= -f1

# host / WSL — a specific variable
tr '\0' '\n' < /proc/$SLEEP_PID/environ | grep '^PATH='
# adb shell — an app's environment, if you have the UID or root
PID=$(pidof com.android.settings)
tr '\0' '\n' < /proc/$PID/environ
PATH=/product/bin:/apex/com.android.runtime/bin:/system/bin:/system_ext/bin
ANDROID_BOOTLOGO=1
ANDROID_ROOT=/system
ANDROID_ASSETS=/system/app
ANDROID_DATA=/data
ANDROID_STORAGE=/storage
ANDROID_ART_ROOT=/apex/com.android.art
ANDROID_I18N_ROOT=/apex/com.android.i18n
ANDROID_TZDATA_ROOT=/apex/com.android.tzdata
EXTERNAL_STORAGE=/sdcard
DOWNLOAD_CACHE=/data/cache
BOOTCLASSPATH=/apex/com.android.art/javalib/core-oj.jar:...

An Android app's environment is short and dull because it is inherited from Zygote. That is precisely what makes anomalies loud: an app process carrying LD_PRELOAD, an unusual LD_LIBRARY_PATH, or a wrap.<package> artefact has been tampered with, and this is one place that shows up.

Pentester's Note grep may refuse these files with Binary file matches because they contain bytes below 0x20. Use grep -a to force text mode, or pipe through tr first. The idiom worth memorising: tr '\0' '\n' < /proc/<pid>/environ | grep -i -E 'token|key|secret|password'. It costs nothing and occasionally finds something a developer put in an environment variable on a debug build.

C4. The spoofing angle. A process can rewrite its own argv[0] region in memory, and cmdline renders whatever is there. Combined with prctl(PR_SET_NAME) changing comm, a process's advertised identity is entirely under its own control. What is not under its control is /proc/<pid>/exe, which is a kernel-maintained link to the actual executable inode — that is the next part.


D1. exe, cwd, root and fd/.

# host / WSL
ls -l /proc/$SLEEP_PID/exe
ls -l /proc/$SLEEP_PID/cwd
ls -l /proc/$SLEEP_PID/root
ls -l /proc/$SLEEP_PID/fd
lrwxrwxrwx 1 harsh harsh 0 Aug  5 13:10 /proc/48213/exe -> /usr/bin/sleep
lrwxrwxrwx 1 harsh harsh 0 Aug  5 13:10 /proc/48213/cwd -> /home/harsh/lab01
lrwxrwxrwx 1 harsh harsh 0 Aug  5 13:10 /proc/48213/root -> /
total 0
lrwx------ 1 harsh harsh 64 Aug  5 13:10 0 -> /dev/pts/1
lrwx------ 1 harsh harsh 64 Aug  5 13:10 1 -> /dev/pts/1
lrwx------ 1 harsh harsh 64 Aug  5 13:10 2 -> /dev/pts/1
Link Points at What it proves
exe The executable file, by inode The real program, not the name it advertises. Still resolves after the file is deleted, with a (deleted) suffix
cwd The current working directory Where relative paths resolve from. Useful when a process is writing files "somewhere"
root The process's root directory Normally /. If it is anything else, the process has been chrooted or is in a container
fd/N The object descriptor N refers to Every open file, socket, pipe and device

D2. The deleted-file trick. This is worth doing once because it explains a whole forensic technique.

# host / WSL
cd ~/lab01 2>/dev/null || mkdir -p ~/lab01 && cd ~/lab01
echo "this will be deleted" > secret.txt
tail -f secret.txt &
TAIL=$!
sleep 1
rm secret.txt
ls secret.txt                       # gone
ls -l /proc/$TAIL/fd | grep secret  # still there
cat /proc/$TAIL/fd/3                # and still readable
kill $TAIL
ls: cannot access 'secret.txt': No such file or directory
lr-x------ 1 harsh harsh 64 Aug  5 13:15 3 -> /home/harsh/lab01/secret.txt (deleted)
this will be deleted

The name was removed and the link count reached zero, but a process still held the inode open, so the data survived. Copying /proc/<pid>/fd/N recovers it. Apps that write a temporary file, unlink it immediately, and keep using the descriptor are relying on exactly this — and it means the data is still extractable from a live process even though nothing on the filesystem shows it.

D3. Descriptors on an Android app.

# adb shell — needs the app's UID or root
PID=$(pidof com.android.settings)
ls -l /proc/$PID/fd | head -30
ls -l /proc/$PID/fd | wc -l
lrwx------ 1 system system 64 2025-08-05 13:20 0 -> /dev/null
lrwx------ 1 system system 64 2025-08-05 13:20 4 -> anon_inode:[eventpoll]
lrwx------ 1 system system 64 2025-08-05 13:20 5 -> /dev/binder
lrwx------ 1 system system 64 2025-08-05 13:20 8 -> socket:[184213]
lr-x------ 1 system system 64 2025-08-05 13:20 12 -> /system/priv-app/Settings/Settings.apk
lrwx------ 1 system system 64 2025-08-05 13:20 19 -> /data/data/com.android.settings/databases/x.db
Target What it is Why you care
/dev/binder, /dev/hwbinder The Binder IPC driver Every framework call goes through it. Every app has one — see 24 — IPC
socket:[N] A socket; N is its inode Cross-reference against /proc/net/tcp to find the peer — Lab 03
pipe:[N] A pipe Often the app's own logging, or a Runtime.exec() child
anon_inode:[eventpoll], [eventfd] Event objects The Looper's message queue
*.db, *.db-wal Open SQLite databases Files worth pulling and reading
shared_prefs/*.xml Preferences Frequently holds tokens
/memfd:..., /dev/ashmem Shared memory Data crossing a process boundary
base.apk The app's own APK, held open for resources Normal
Anything unexpected The finding

D4. The rest of the directory, in one pass.

# host / WSL
ls /proc/$SLEEP_PID/
Entry Contains Read it when
status Human-readable identity and state Always first
stat The same data as 52 space-separated fields, machine-readable Scripting, and field 3 is the state letter
statm Memory in pages, seven numbers Quick memory arithmetic
cmdline argv, NUL-separated Identifying what actually ran
environ Environment, NUL-separated Hunting for leaked config and injection artefacts
exe, cwd, root Magic symlinks Establishing ground truth about identity
fd/, fdinfo/ Open descriptors, and their offsets and flags Finding open databases, sockets, leaked descriptors
maps, smaps, smaps_rollup Memory regions Covered in chapter 01 Lab 02
mem The process's memory, readable with ptrace privilege Dumping decrypted content
task/<tid>/ One directory per thread, each with its own status, stat, comm Finding which thread is doing something
limits Soft and hard resource limits Descriptor exhaustion, core dump settings
mounts, mountinfo, mountstats The mount table as this process sees it Namespace detection — Lab 03
ns/ Namespace identity links Comparing two processes' namespaces — Lab 03
cgroup cgroup membership Android's foreground/background scheduling
oom_score, oom_score_adj Kill priority under memory pressure Android's LMK behaviour
sched, schedstat, wchan Scheduler statistics and blocking point Diagnosing a hang
attr/current The SELinux context Which domain this process runs in
personality Execution domain flags Rarely, when ASLR is disabled per-process
net/ Network tables for this process's network namespace Lab 03

D5. Try the useful ones.

# host / WSL
cat /proc/$SLEEP_PID/limits
cat /proc/$SLEEP_PID/wchan; echo
cat /proc/$SLEEP_PID/oom_score
ls /proc/$SLEEP_PID/task/
# adb shell — the Android-specific ones
PID=$(pidof com.android.settings)
cat /proc/$PID/attr/current; echo
cat /proc/$PID/oom_score_adj
cat /proc/$PID/cgroup
ls /proc/$PID/task/ | wc -l
for t in /proc/$PID/task/*/comm; do echo "$(basename $(dirname $t)) $(cat $t)"; done | head -20
u:r:system_app:s0
-800
0::/uid_1000/pid_2145
42
2145 ndroid.settings
2151 Jit thread pool
2152 HeapTaskDaemon
2153 ReferenceQueueD
2154 FinalizerDaemon
2158 Binder:2145_1
2159 Binder:2145_2

Thread names are informative. Binder:<pid>_N threads handle incoming IPC; Jit thread pool and HeapTaskDaemon are ART's. A thread with an unexpected name — gmain, gum-js-loop, pool-frida — is a strong signal that something has been injected.

D6. Run the chapter's process report script and compare its output to what you found by hand.

# host / WSL
sh ../../01-Computer-Science-Basics/scripts/inspect-process.sh $SLEEP_PID

That script (from chapter 01) covers identity, memory, maps and descriptors. This chapter's ../scripts/first-shell.sh covers the environment-orientation side. Reading both sources afterwards is worth as much as running them.


Part E — Signals

E1. What a signal is.

Definition — Signal An asynchronous notification delivered to a process, identified by a small integer. Each signal has a default action — terminate, terminate and dump core, stop, continue, or ignore — and for most signals a process may install a handler function instead. Delivery interrupts whatever the process was doing.

The command to send one is called kill because terminating was the first use anyone had for it. The name stuck; most signals do not terminate anything.

E2. The table you need.

# Name Default action Catchable Why it matters here
1 SIGHUP Terminate Yes Terminal closed; daemons often reload config on it
2 SIGINT Terminate Yes Ctrl+C
3 SIGQUIT Terminate + core Yes ART installs a handler: dumps every Java thread stack. E5
4 SIGILL Terminate + core Yes Illegal instruction — sometimes a failed hook
5 SIGTRAP Terminate + core Yes The debugger's signal. Breakpoints raise it
6 SIGABRT Terminate + core Yes abort(), a failed assertion, or a detected heap corruption
8 SIGFPE Terminate + core Yes Arithmetic error, including integer divide by zero
9 SIGKILL Terminate No Uncatchable, unblockable, unignorable. The kernel does it
11 SIGSEGV Terminate + core Yes Invalid memory access. On Android, produces a tombstone
13 SIGPIPE Terminate Yes Wrote to a pipe with no reader
15 SIGTERM Terminate Yes The polite request. What kill <pid> sends by default
17 SIGCHLD Ignore Yes A child changed state
18 SIGCONT Continue Yes Resume a stopped process
19 SIGSTOP Stop No Uncatchable. Freezes the process
20 SIGTSTP Stop Yes Ctrl+Z
31 SIGSYS Terminate + core Yes A seccomp filter blocked a syscall

The two uncatchable signals, SIGKILL and SIGSTOP, are uncatchable on purpose: the system needs a way to stop a process that has decided not to cooperate.

E3. Send some.

# host / WSL
sleep 600 &
P=$!
grep '^State' /proc/$P/status

kill -STOP $P
grep '^State' /proc/$P/status          # expect: T (stopped)

kill -CONT $P
grep '^State' /proc/$P/status          # expect: S (sleeping)

kill -TERM $P
sleep 1
ls -d /proc/$P 2>&1                    # expect: No such file or directory
State:  S (sleeping)
State:  T (stopped)
State:  S (sleeping)
ls: cannot access '/proc/48301': No such file or directory

E4. Watch a handler ignore a signal, then watch SIGKILL not care.

# host / WSL — a shell that catches SIGTERM and refuses to die
cat > ~/lab01/stubborn.sh <<'EOF'
#!/bin/sh
trap 'echo "caught SIGTERM, ignoring"' TERM
echo "stubborn pid $$"
while true; do sleep 1; done
EOF
chmod 755 ~/lab01/stubborn.sh
~/lab01/stubborn.sh &
S=$!
sleep 1
kill -TERM $S ; sleep 1                # prints the message, keeps running
ps -o pid,stat,comm -p $S
kill -KILL $S ; sleep 1                # no handler can save it
ps -o pid,stat,comm -p $S
stubborn pid 48355
caught SIGTERM, ignoring
    PID STAT COMMAND
  48355 S    stubborn.sh
    PID STAT COMMAND

That is why kill -9 is the last resort and not the first: SIGTERM lets a process flush its buffers and clean up, and SIGKILL does not.

E5. kill -3 against an Android app — the free thread dump.

This is one of the highest-value zero-cost actions in mobile testing. It does not stop the app.

# adb shell
PID=$(pidof com.android.settings)
kill -3 $PID

Then read the result. ART writes the dump to logcat and, on most builds, to a trace file:

# host
adb logcat -d | grep -B2 -A 100 "Cmd line: com.android.settings" | head -80
# adb shell — the file form
ls -l /data/anr/
-rw-rw---- 1 system system 184320 2025-08-05 13:40 /data/anr/anr_2025-08-05-13-40-11-123
# host — pull and read it (needs root or system access to /data/anr)
adb shell "su -c 'cat /data/anr/anr_2025-08-05-13-40-11-123'" > dump.txt
head -60 dump.txt

A dump looks like this, abridged:

----- pid 2145 at 2025-08-05 13:40:11 -----
Cmd line: com.android.settings

DALVIK THREADS (42):
"main" prio=5 tid=1 Native
  | group="main" sCount=1 ucsCount=0 flags=1 obj=0x72d8c1e8 self=0xb400007...
  | sysTid=2145 nice=-10 cgrp=top-app sched=0/0 handle=0x7a1e4c14f8
  | state=S schedstat=( 291847362 41283746 1204 ) utm=18 stm=10 core=3 HZ=100
  | stack=0x7fd1a20000-0x7fd1a22000 stackSize=8188KB
  native: #00 pc 00000000000a1234  /apex/com.android.runtime/lib64/bionic/libc.so (__epoll_pwait+8)
  at android.os.MessageQueue.nativePollOnce(Native method)
  at android.os.MessageQueue.next(MessageQueue.java:335)
  at android.os.Looper.loopOnce(Looper.java:161)
  at com.android.settings.SettingsActivity.onResume(SettingsActivity.java:412)
  ...

Pentester's Note Read what that gives you against an obfuscated app. A static tool showed you classes called a, b and c. kill -3 shows you the call stacks actually executing right now, with line numbers, for every one of the app's threads — including the thread that is sitting inside the root check, the certificate validation, or the crypto routine, at the moment you triggered it. It costs one command, requires no instrumentation, and cannot be detected by looking for TracerPid. Trigger the app's interesting code path, then immediately kill -3 and read the top frames.

E6. Signals and crashes. When a native crash happens, Android's debuggerd catches the fatal signal and writes a tombstone.

# adb shell (root)
ls -l /data/tombstones/ | tail -5

A tombstone records the signal (SIGSEGV), the si_code distinguishing "no mapping" from "permission denied", the faulting address, the full register set, and the memory map at the time. If the faulting address is something like 0x4141414141, you sent a string of A characters and the crash address is attacker-controlled — which is the difference between "it crashed" and a report worth money. The si_code values are covered in chapter 01's FAQ.


Part F — TracerPid: watch it change

This is the centrepiece of the lab. Do it slowly and do it twice.

F1. What ptrace is.

Definition — ptrace A system call that lets one process (the tracer) observe and control another (the tracee): read and write its memory and registers, intercept its system calls, and stop it at breakpoints. Every debugger uses it. So does strace. So does Frida when it attaches to a running process. A process may have at most one tracer at a time.

That last sentence is the whole game. Because there is exactly one tracer slot, an app can occupy its own slot by calling ptrace(PTRACE_TRACEME) on itself, or by forking a child that traces the parent, and no debugger can then attach.

F2. Baseline — nothing attached. Open two terminals. In terminal 1:

# host / WSL — terminal 1
sleep 900 &
echo "TARGET PID = $!"
TARGET PID = 48412

In terminal 2, replace 48412 with your number everywhere below:

# host / WSL — terminal 2
grep TracerPid /proc/48412/status
grep '^State' /proc/48412/status
TracerPid:  0
State:  S (sleeping)

Zero means nothing is tracing it. Write that down.

F3. Watch the field live. In terminal 2, start a watcher that reprints the value every half second:

# host / WSL — terminal 2. Ctrl+C to stop it later.
while true; do
  printf '%s  %s  %s\n' "$(date +%T)" \
    "$(grep TracerPid /proc/48412/status)" \
    "$(grep '^State' /proc/48412/status)"
  sleep 0.5
done
13:50:01  TracerPid:    0  State:   S (sleeping)
13:50:01  TracerPid:    0  State:   S (sleeping)

F4. Attach a debugger from a third terminal.

# host / WSL — terminal 3
gdb -p 48412

Watch terminal 2. The moment gdb attaches:

13:50:14  TracerPid:    0      State:   S (sleeping)
13:50:15  TracerPid:    48430  State:   t (tracing stop)
13:50:15  TracerPid:    48430  State:   t (tracing stop)

TracerPid is now gdb's own PID, and the state changed from S to t. Confirm what 48430 is:

# host / WSL — terminal 2, in another shell or after Ctrl+C
cat /proc/48430/comm
ls -l /proc/48430/exe
gdb
lrwxrwxrwx 1 harsh harsh 0 Aug  5 13:50 /proc/48430/exe -> /usr/bin/gdb

Now detach in terminal 3:

(gdb) detach
(gdb) quit

Terminal 2 immediately shows:

13:50:41  TracerPid:    0  State:   S (sleeping)

You have just watched the entire mechanism of Android anti-debugging, in about forty seconds. An app that reads its own /proc/self/status every second and looks at that one line will see exactly what your watcher saw.

F5. The same with strace.

# host / WSL — terminal 3
strace -p 48412

Terminal 2 shows TracerPid become strace's PID. strace is a debugger by any technical definition; it just prints syscalls instead of offering a prompt. This is why strace on an app with anti-debug protection makes the app die — you have set the field it is watching.

F6. Prove there is only one tracer slot. With gdb still attached in terminal 3, try strace in a fourth terminal:

# host / WSL — terminal 4, while gdb is attached
strace -p 48412
strace: attach: ptrace(PTRACE_SEIZE, 48412): Operation not permitted

Denied — the slot is taken. Now flip it around: this is exactly the self-defence technique. A process that traces itself cannot be traced by you.

# host / WSL — a program that occupies its own tracer slot
cat > ~/lab01/selftrace.c <<'EOF'
#include <stdio.h>
#include <unistd.h>
#include <sys/ptrace.h>
int main(void) {
    if (ptrace(PTRACE_TRACEME, 0, 0, 0) == -1) {
        printf("already being traced -- refusing to run\n");
        return 1;
    }
    printf("pid %d running, tracer slot occupied by my parent\n", getpid());
    for (;;) sleep(1);
}
EOF
gcc -o ~/lab01/selftrace ~/lab01/selftrace.c
~/lab01/selftrace &
sleep 1

PTRACE_TRACEME makes the process's parent its tracer. Any later attach attempt fails, and if the program is started under a debugger, the ptrace call itself fails and the program can refuse to run. Both halves of that are used in real Android apps, implemented in native code so they cannot be patched from Java.

F7. Do it on Android.

# adb shell — terminal 1, watch an app
PID=$(pidof com.example.app)
while true; do grep TracerPid /proc/$PID/status; sleep 1; done
# host — terminal 2, attach with Frida in attach mode
frida -U -p <PID>

The watcher shows TracerPid become frida-server's PID. Now do it the other way:

# host — spawn instead of attach
frida -U -f com.example.app

In spawn mode Frida starts the process suspended and releases ptrace before the app's own code runs, so a TracerPid check performed later sees 0. That is the first and simplest bypass, and it is available to you because you now understand exactly what the check reads.

F8. Write the summary yourself. Before reading the solution, fill in this table from what you observed:

Detection What it reads Why it works How it is defeated
TracerPid in /proc/self/status
Process state t in /proc/self/stat field 3
ptrace(PTRACE_TRACEME) returning -1

Part G — Clean up

# host / WSL
kill $SLEEP_PID 2>/dev/null
jobs -p | xargs -r kill 2>/dev/null
rm -rf ~/lab01/stubborn.sh ~/lab01/selftrace ~/lab01/selftrace.c
# adb shell
rm -rf /data/local/tmp/lab02

Hints

Hint 1 — `cat /proc//status` says permission denied on the device `/proc//status` is world-readable for basic fields, but `maps`, `fd`, `environ` and `mem` need the owning UID or root. Since Android 9 the visibility of other processes is further restricted. Use one of: `adb root` on a non-Play emulator image; `run-as ` for a debuggable app; or `su -c` on a rooted device. Check which you have with `id` and `getenforce`.
Hint 2 — `gdb -p` says "ptrace: Operation not permitted" on my own process Most desktop distributions set `kernel.yama.ptrace_scope` to 1, which allows tracing only direct descendants. Check with `cat /proc/sys/kernel/yama/ptrace_scope`. For this lab, either run gdb with `sudo`, or temporarily lower it with `sudo sysctl kernel.yama.ptrace_scope=0` and set it back to `1` afterwards. Do not leave it at 0.
Hint 3 — `kill -3` produced nothing in logcat Three possibilities. You sent it to the wrong PID — an app can have several processes, so check `ps -A | grep `. Or you are not permitted to signal that process; `kill` needs matching UID or root. Or the dump went to a file rather than logcat: look in `/data/anr/`, which needs root or system to read. Also try `adb logcat -d -b main -b system | grep -i "DALVIK THREADS"`.
Hint 4 — `TracerPid` never changes when I attach You are almost certainly watching a different PID from the one you attached to. If the target is an Android app, confirm with `pidof ` immediately before and after — an app that crashes and restarts gets a new PID. Also check that your attach actually succeeded: gdb prints an error and returns to its prompt if it did not.
Hint 5 — `tr '\0' '\n'` does nothing on Android Toybox's `tr` accepts the escape, but some older builds do not. Alternatives that always work: `xxd /proc//cmdline` to see the raw bytes, or `cat -v` on some builds, or pull the file to your host with `adb exec-out cat /proc//cmdline > cmdline.bin` and process it there.
Hint 6 — the app dies the instant I attach That *is* your result. The app has anti-debugging and it is working. Do not conclude the tool is broken. Switch to spawn mode (`frida -U -f `), which releases `ptrace` before the app's code runs, and note the behaviour in your report — an app that refuses to run under a debugger is a resilience control you should describe, and its exact detection method is worth identifying.

Solution

The /proc/<pid>/status fields, ranked by how often you will read them

Rank Field Why
1 TracerPid Anti-debugging, both directions
2 Uid / Gid Which sandbox this process is in
3 Groups Which coarse permissions it holds — 3003 is INTERNET
4 State t means traced, D means stuck in I/O, Z means the parent leaked it
5 PPid Was it forked from zygote, or from something else
6 Seccomp 2 on every normal Android app process
7 CapEff Should be all zeros for an app; anything else is privileged
8 Threads Baseline for spotting injected threads
9 SigCgt Which signals it handles — a SIGSEGV handler means a crash reporter or a packer
10 Name Last, because it is spoofable

Part F8 answers

Detection What it reads Why it works How it is defeated
TracerPid in /proc/self/status A generated line naming the attached tracer The kernel populates it truthfully; there is no file to pre-patch Spawn rather than attach, so ptrace is released before the app's code runs; or hook openat/read/strstr in libc so the read returns 0; or use a non-ptrace injector such as a Zygisk module
Process state t in /proc/self/stat field 3 The same fact through a different file State is t (tracing stop) while stopped by a tracer The same hooks, applied to stat as well — this is why patching only status fails
ptrace(PTRACE_TRACEME) returning -1 Whether the tracer slot is already taken Only one tracer per process Hook ptrace itself in libc and return 0; or start the app cleanly and inject afterwards through a path that does not use ptrace

The general lesson is the one worth carrying forward: all three read the same underlying kernel fact through different interfaces. Defeating one and not the others is why a "bypass script found on the internet" works against one app and fails against the next.

Why the /proc model makes anti-debugging both easy and defeatable

Easy, because the check is three lines of C: open a file, scan for a string, compare a number. It needs no permissions, no framework API, and no library beyond libc, and it can be compiled into a native library where Java-level patching cannot reach it.

Defeatable, because those three lines are open, read and a comparison — all of which are ordinary function calls in a shared library that a hooking framework can intercept. There is no privileged path, no attestation, and no way for the app to know whether the bytes it received actually came from the kernel.

Which is why the honest conclusion, stated in the chapter README and worth repeating: on-device anti-debugging is friction and telemetry, never a security boundary. The decision that matters belongs on a server, informed by hardware-backed attestation the client cannot forge.

The complete kill -3 workflow, as you would use it on an engagement

# 1. host — find the process
adb shell ps -A | grep com.example.app

# 2. adb shell — drive the app to the interesting state through its UI, then immediately:
kill -3 $(pidof com.example.app)

# 3. host — capture the dump
adb logcat -d > dump.txt
# or, with root:
adb shell "su -c 'ls -t /data/anr/ | head -1'"   # whole pipeline runs as root

# 4. host — find the app's own frames among the framework noise
grep -n 'com\.example\.' dump.txt | head -40

# 5. host — the threads that are NOT idle in the Looper are the ones doing work
grep -A3 '^"' dump.txt | grep -v nativePollOnce | head -60

The fifth step is the trick: nearly every thread in an idle Android app is parked in nativePollOnce. Filtering those out leaves the handful actually executing, and on an obfuscated build those are the frames worth reversing.


Success Criteria

# Criterion Proof
1 You can explain PID, PPID, UID, STAT, RSS, VSZ and WCHAN without notes Verbal
2 You confirmed an Android app's PPid equals zygote64's PID Two numbers
3 You explained the four numbers on the Uid: line and named the one used for file checks One sentence
4 You observed a setuid binary's real and effective UIDs differing in a live process status extract
5 You identified GID 3003 in an app's Groups and stated what it grants One sentence
6 You read cmdline correctly and showed the NUL bytes in a hex dump xxd output
7 You dumped an app's environment as NAME=value lines Transcript
8 You recovered the contents of a deleted file through /proc/<pid>/fd/ Transcript
9 You listed an app's descriptors and identified /dev/binder, a socket and a database ls -l output
10 You listed an app's threads and named three of them task/*/comm output
11 You stopped, continued and terminated a process with three different signals Three State readings
12 You demonstrated a handler catching SIGTERM and SIGKILL ignoring the handler Transcript
13 You obtained a Java thread dump from a running Android app with kill -3 The first 20 lines
14 You watched TracerPid change from 0 to a debugger's PID and back to 0 Three consecutive watcher lines
15 You confirmed the tracer PID belonged to the debugger you started /proc/<tracer>/exe
16 You demonstrated that a second tracer is refused The Operation not permitted line
17 You filled in the F8 table before reading the solution Your table
18 You cleaned up every background process you started jobs showing none

Going Further

  1. Decode /proc/<pid>/stat by hand. It is 52 space-separated fields with no labels. Field 3 is the state, field 4 the PPID, fields 14 and 15 are user and system CPU time in clock ticks, field 23 is vsize. Use man 5 proc and write a one-line awk that prints a labelled subset. This is what monitoring tools actually parse, because status is expensive to generate.

  2. Compare SigCgt across apps. Convert the hex bitmask to a set of signal numbers — bit 0 is signal 1 — and identify which apps install a SIGSEGV handler. Those are crash reporters, packers, or anti-tamper code, and knowing which before you start saves an afternoon.

  3. Find every process whose PPid is not zygote. Write a loop over /proc/[0-9]* that prints name and PPid, and identify the native daemons. Cross-reference them against the service declarations in init.rc from AOSP. That list is the native attack surface of the device.

  4. Watch a process's descriptor count grow. Run while true; do ls /proc/<pid>/fd | wc -l; sleep 1; done against an app while you use it heavily. A count that grows monotonically and never falls is a descriptor leak, and eventually an availability bug — check limits for the ceiling.

  5. Trace syscalls and correlate with /proc. Run strace -f -e trace=openat,read against a process while it performs a root check, and watch it open /proc/self/status. You will see the exact read that the whole of Part F is about, as a syscall.

  6. Build the watcher into a script. Rewrite the Part F watcher to poll TracerPid, the process state, the thread count and the descriptor count together, and print a line only when something changes. That is a genuinely useful tool during an engagement and it is thirty lines of shell.


Why this matters for Android security

/proc is the shared ground between you and the app. Every anti-analysis technique in the mobile world reads a file you have now read yourself. Root detection reads /proc/self/mounts. Debugger detection reads /proc/self/status. Frida detection reads /proc/self/maps and /proc/net/tcp. Emulator detection reads /proc/cpuinfo and /sys. You cannot defeat a check you do not understand, and you cannot understand it until you know what normal looks like in the file it reads.

TracerPid is the highest-value single line in mobile security. It is checked by an enormous fraction of hardened apps, it is trivially readable, and the three standard bypasses each correspond to a different point in the chain you just traced. When you get to 53 — Frida, the difference between frida -U -p <pid> and frida -U -f <package> will not be a piece of trivia to memorise; it will be an obvious consequence of what you watched happen in Part F.

kill -3 is free intelligence. Against an obfuscated release build where static analysis gives you class names like a.b.c, a thread dump gives you the actual call stacks executing at the moment you triggered the interesting behaviour, with line numbers. It requires no instrumentation, sets no TracerPid, and takes one command. It is the first thing to try and one of the last things people learn.

Identity is what the sandbox is made of. The Uid, Gid, Groups, CapEff and Seccomp lines of status are, collectively, the enforcement state of the Android app sandbox for that process. 21 — App Sandbox explains how those values get set during Zygote specialisation; this lab is where you learn to read them off a live process and notice when one is wrong.

Descriptors leak, and /proc/<pid>/fd finds it. A privileged process that hands a descriptor to a less privileged one has bypassed every path-based permission check, because the kernel checked permissions once at open() and never again. It is a cheap thing to look for and it is occasionally a critical finding.

Next: Lab 03 — IPC, sockets and mount namespaces, which takes two processes that now have identities and makes them talk to each other — then shows how a process can be given an entirely different, entirely genuine view of the filesystem.