diff --git a/README.md b/README.md index 4ec1224..728d210 100644 --- a/README.md +++ b/README.md @@ -38,6 +38,7 @@ article; each module's own README has that article's version table, quickstart, | [`completablefuture`](completablefuture/) | CompletableFuture in Java: thenApply vs thenCompose, allOf, Exceptions and Timeouts (and When Virtual Threads Win) | | [`streams`](streams/) | Java Stream API Tutorial with Examples + Collectors Cookbook (laziness, collectors, primitive and parallel streams, Gatherers) | | [`classloaders`](classloaders/) | Java ClassLoaders Explained: Delegation, Custom Loaders, ClassNotFoundException vs NoClassDefFoundError | +| [`process-api`](process-api/) | Running Shell Commands from Java Safely: ProcessBuilder, Process API and Timeouts | ## License diff --git a/pom.xml b/pom.xml index 670efd0..07025a2 100644 --- a/pom.xml +++ b/pom.xml @@ -47,6 +47,7 @@ streams classloaders optional + process-api diff --git a/process-api/README.md b/process-api/README.md new file mode 100644 index 0000000..4cd3c84 --- /dev/null +++ b/process-api/README.md @@ -0,0 +1,36 @@ +# process-api + +Companion code for the ankurm.com post *"Running Shell Commands from Java Safely: ProcessBuilder, +Process API and Timeouts."* Module `process-api` in `java-core-examples`. + +All explanation lives in the post; this module holds the runnable evidence and the captured output. + +## Versions + +| Component | Version | +|---|---| +| JDK | 25.0.5.1+2 (Temurin, LTS) | +| JUnit Jupiter | 5.11.0 | +| OS | Linux (the demos shell out to `sh`, `sleep`, `head`, `tr`, `cat`, `wc`, `ls`, `sort`, `uniq`) | + +## Quickstart + +```bash +export JDK25_HOME=/path/to/jdk-25 +./scripts/run-all.sh # rebuilds, runs the tests, regenerates everything in output/ +``` + +## What is in here + +| File | Shows | Output | +|---|---|---| +| `BasicsDemo` | the smallest correct use; failing command vs missing binary; `exitValue()` too early; no shell | `01` | +| `DeadlockDemo` | the 64 KiB pipe deadlock, the stderr variant, and three fixes | `02` | +| `TimeoutDemo` | `waitFor(timeout)`, `destroy()` vs `destroyForcibly()`, orphaned grandchildren, a grandchild holding the pipe | `03` | +| `EnvironmentDemo` | environment copy, `clear()`, which PATH finds the program, working directory, redirects, stdin | `04` | +| `HandleDemo` | `ProcessHandle`, `Info`, `onExit()`, `startPipeline` | `05` | +| `InjectionDemo` | shell-string injection, option injection, `--`, an allow-list | `06` | +| `ProcessRunner` | the safe runner: concurrent drain, capped capture, closed stdin, deadline, tree kill | used by `02`, `03` | +| `ProcessClaimsTest` | 14 assertions behind the claims above | `07` | + +Child PIDs and timings vary between runs; the behaviour (what hangs, what exits, which exit code) does not. diff --git a/process-api/output/00-environment.txt b/process-api/output/00-environment.txt new file mode 100644 index 0000000..766f21d --- /dev/null +++ b/process-api/output/00-environment.txt @@ -0,0 +1,7 @@ +$ java -version +openjdk version "25.0.5.1" 2026-11-17 LTS +OpenJDK Runtime Environment Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS) +OpenJDK 64-Bit Server VM Temurin-25.0.5.1+2 (build 25.0.5.1+2-LTS, mixed mode, sharing) + +$ uname -sr +Linux 6.18.44-fc-v880 diff --git a/process-api/output/01-basics.txt b/process-api/output/01-basics.txt new file mode 100644 index 0000000..c460114 --- /dev/null +++ b/process-api/output/01-basics.txt @@ -0,0 +1,18 @@ +== 1. the smallest thing that works +stdout = hello from a child process +exit code = 0 + +== 2. a failing command is NOT an exception: it is a non-zero exit code +stderr = ls: cannot access '/definitely/not/here': No such file or directory +exit code = 2 + +== 3. a command that does not exist IS an exception, thrown by start() +IOException: Cannot run program "no-such-binary-xyz": Exec failed, error: 2 (No such file or directory) + +== 4. exitValue() before the process ends throws +IllegalThreadStateException: process hasn't exited +waitFor(200ms) returned false (false = still running, true = exited) +after destroyForcibly(): exit code = 137 (128 + SIGKILL 9 = 137 on Linux) + +== 5. the shell is not involved: no pipes, no globs, no $VARS +stdout = *.txt $HOME a|b diff --git a/process-api/output/02-deadlock.txt b/process-api/output/02-deadlock.txt new file mode 100644 index 0000000..d934533 --- /dev/null +++ b/process-api/output/02-deadlock.txt @@ -0,0 +1,19 @@ +== 1. WRONG: waitFor() first, read afterwards +child exited within 3s? false +child still alive? true +bytes sitting in the pipe: 65536 + +== 2. RIGHT (one stream): read to EOF, then waitFor() +read 200000 bytes, exit code 0 + +== 3. STILL WRONG: read stdout to EOF, but the child also fills stderr +stdout reader finished within 3s? false + +== 4. FIX A: merge stderr into stdout, one stream to drain +read 400000 bytes, exit code 0 + +== 5. FIX B: drain both streams concurrently (what ProcessRunner does) +stdout=200000 stderr=200000 exit=0 timedOut=false + +== 6. FIX C: do not pipe at all. Send output to a file or discard it +waitFor() returned immediately with exit code 0 diff --git a/process-api/output/03-timeouts.txt b/process-api/output/03-timeouts.txt new file mode 100644 index 0000000..9089ee1 --- /dev/null +++ b/process-api/output/03-timeouts.txt @@ -0,0 +1,20 @@ +== 1. waitFor(timeout) returns false; it does NOT stop the process +waitFor(500ms) = false +still alive = true +destroy() then waitFor -> exit code 143 (128 + SIGTERM 15 = 143) + +== 2. a shell command spawns a child; destroying the shell orphans it +descendants of the shell: 1 -> [/usr/bin/sleep] +shell dead, orphan alive = true <- leaked process + +== 3. kill the tree: snapshot descendants first, then kill all +shell alive = false, former child alive = false + +== 4. ProcessRunner with a deadline +timedOut=true exit=-1 stdout=started elapsed<2s=true + +== 5. a background grandchild keeps the pipe open: readAllBytes() waits for IT +sh exited at once, but readAllBytes() took ~4s; got done|late| + +== 6. ProcessRunner is not held hostage by the same command +exit=0 stdout=done| returned in under 2s: true (bounded by the 1s reader grace, not by the 4s grandchild) diff --git a/process-api/output/04-environment.txt b/process-api/output/04-environment.txt new file mode 100644 index 0000000..872f8e7 --- /dev/null +++ b/process-api/output/04-environment.txt @@ -0,0 +1,21 @@ +== 1. the child inherits a COPY of our environment +child sees : GREETING=hello MODE= +our own env: GREETING=null (unchanged) + +== 2. clear() and rebuild: pass only what the child needs +child sees : HOME=[] PATH=[/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin] MODE=[minimal] + +== 3. which PATH finds the program? start() uses OURS; the child's PATH is for the child +start("date") with child PATH=/nonexistent : true (resolved with the parent's PATH) +sh -c 'date +%Y' with child PATH=/nonexistent : sh: 1: date: not found + +== 4. working directory +ls in temp dir: marker.txt +bad directory -> IOException: Cannot run program "ls" (in directory "/no/such/dir"): Exec failed, error: 2 (No such file or directory) + +== 5. redirect to files: no pipe, so nothing to drain +exit 0, file contains: to-stdout | to-stderr | +getInputStream() on a redirected process is a null stream: read() = -1 + +== 6. stdin: close it, or a reader like cat never sees EOF +cat echoed: line one | line two | exit 0 diff --git a/process-api/output/05-handles.txt b/process-api/output/05-handles.txt new file mode 100644 index 0000000..6b8a2a2 --- /dev/null +++ b/process-api/output/05-handles.txt @@ -0,0 +1,21 @@ +== 1. our own process +pid > 0: true, command ends with java: true +has a parent: true + +== 2. onExit() instead of a blocked thread +main thread is free; alive = true +callback: exited with 3 + +== 3. what ProcessHandle.Info reveals about a child +command = /usr/bin/sleep +arguments = 5 +user set = true, startInstant set = true + +== 4. a handle to a finished process +alive after exit: false + +== 5. a real pipeline without a shell: printf | sort | uniq -c + 1 a + 3 b + 1 c +stages: 3 diff --git a/process-api/output/06-injection.txt b/process-api/output/06-injection.txt new file mode 100644 index 0000000..824ff39 --- /dev/null +++ b/process-api/output/06-injection.txt @@ -0,0 +1,25 @@ +== 1. VULNERABLE: build a shell string from user input +$ sh -c wc -c report.txt; cat secret.txt + 18 report.txt + TOP-SECRET [exit 0] + +== 2. SAFE: argument list, no shell. The whole input is one filename +$ wc -c report.txt; cat secret.txt + wc: 'report.txt; cat secret.txt': No such file or directory [exit 1] + +== 3. SAFE but still a trap: option injection. Input '-l' is read as a flag +$ ls -l + total 8 + -rw-r--r-- 1 root root 18 Nov 26 00:48 report.txt + -rw-r--r-- 1 root root 11 Nov 26 00:48 secret.txt [exit 0] +(the caller wanted to list a file called '-l'; ls took it as an option) + +== 4. FIX: '--' ends option parsing, then validate +$ ls -- -l + ls: cannot access '-l': No such file or directory [exit 2] + +== 5. FIX: allow-list the input before it gets anywhere near a command +'report.txt' -> true +'report.txt; cat secret.txt' -> false +'-l' -> false +'../etc/passwd' -> false diff --git a/process-api/output/07-tests.txt b/process-api/output/07-tests.txt new file mode 100644 index 0000000..41eb596 --- /dev/null +++ b/process-api/output/07-tests.txt @@ -0,0 +1,4 @@ +------------------------------------------------------------------------------- +Test set: com.ankurm.process.ProcessClaimsTest +------------------------------------------------------------------------------- +Tests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 16.26 s -- in com.ankurm.process.ProcessClaimsTest diff --git a/process-api/pom.xml b/process-api/pom.xml new file mode 100644 index 0000000..b3ed85b --- /dev/null +++ b/process-api/pom.xml @@ -0,0 +1,43 @@ + + + 4.0.0 + + + com.ankurm + java-core-examples + 1.0 + + + process-api + process-api + ProcessBuilder and the Process API: pipe deadlocks, timeouts, process trees, environment, ProcessHandle and injection. + + + + org.junit.jupiter + junit-jupiter + 5.11.0 + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.13.0 + + 25 + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.5 + + + + diff --git a/process-api/scripts/run-all.sh b/process-api/scripts/run-all.sh new file mode 100755 index 0000000..4ea1cc8 --- /dev/null +++ b/process-api/scripts/run-all.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Regenerates every file in ../output/. Requires JDK25_HOME. Linux/macOS only (uses sh, sleep, head, tr, cat). +set -euo pipefail +[[ -z "${JDK25_HOME:-}" ]] && { echo "JDK25_HOME must be set" >&2; exit 1; } +cd "$(dirname "$0")/.." +OUT=output; mkdir -p "$OUT" +export JAVA_HOME="$JDK25_HOME" +mvn -q -f ../pom.xml -pl process-api -am package +J="$JDK25_HOME/bin/java" +run() { echo "==> $1"; "$J" -cp target/classes "com.ankurm.process.$1" 2>&1 | grep -v "Picked up" > "$OUT/$2"; } +run BasicsDemo 01-basics.txt +run DeadlockDemo 02-deadlock.txt +run TimeoutDemo 03-timeouts.txt +run EnvironmentDemo 04-environment.txt +run HandleDemo 05-handles.txt +run InjectionDemo 06-injection.txt +{ echo '$ java -version'; "$J" -version 2>&1 | grep -v "Picked up"; echo; echo '$ uname -sr'; uname -sr; } > "$OUT/00-environment.txt" +cp target/surefire-reports/com.ankurm.process.ProcessClaimsTest.txt "$OUT/07-tests.txt" +echo Done diff --git a/process-api/src/main/java/com/ankurm/process/BasicsDemo.java b/process-api/src/main/java/com/ankurm/process/BasicsDemo.java new file mode 100644 index 0000000..284fe8a --- /dev/null +++ b/process-api/src/main/java/com/ankurm/process/BasicsDemo.java @@ -0,0 +1,52 @@ +package com.ankurm.process; + +import java.io.IOException; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** The smallest correct use of ProcessBuilder, and the first three things that go wrong. */ +public final class BasicsDemo { + public static void main(String[] args) throws Exception { + System.out.println("== 1. the smallest thing that works"); + Process p = new ProcessBuilder("echo", "hello from a child process").start(); + String line = new String(p.getInputStream().readAllBytes()).strip(); + int exit = p.waitFor(); + System.out.println("stdout = " + line); + System.out.println("exit code = " + exit); + + System.out.println(); + System.out.println("== 2. a failing command is NOT an exception: it is a non-zero exit code"); + Process f = new ProcessBuilder("ls", "/definitely/not/here").start(); + String err = new String(f.getErrorStream().readAllBytes()).strip(); + System.out.println("stderr = " + err); + System.out.println("exit code = " + f.waitFor()); + + System.out.println(); + System.out.println("== 3. a command that does not exist IS an exception, thrown by start()"); + try { + new ProcessBuilder("no-such-binary-xyz").start(); + } catch (IOException e) { + System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage()); + } + + System.out.println(); + System.out.println("== 4. exitValue() before the process ends throws"); + Process sleeper = new ProcessBuilder("sleep", "5").start(); + try { + sleeper.exitValue(); + } catch (IllegalThreadStateException e) { + System.out.println("IllegalThreadStateException: " + e.getMessage()); + } + System.out.println("waitFor(200ms) returned " + sleeper.waitFor(200, TimeUnit.MILLISECONDS) + + " (false = still running, true = exited)"); + sleeper.destroyForcibly().waitFor(); + System.out.println("after destroyForcibly(): exit code = " + sleeper.exitValue() + + " (128 + SIGKILL 9 = 137 on Linux)"); + + System.out.println(); + System.out.println("== 5. the shell is not involved: no pipes, no globs, no $VARS"); + Process g = new ProcessBuilder(List.of("echo", "*.txt", "$HOME", "a|b")).start(); + System.out.println("stdout = " + new String(g.getInputStream().readAllBytes()).strip()); + g.waitFor(); + } +} diff --git a/process-api/src/main/java/com/ankurm/process/DeadlockDemo.java b/process-api/src/main/java/com/ankurm/process/DeadlockDemo.java new file mode 100644 index 0000000..9a4a6ba --- /dev/null +++ b/process-api/src/main/java/com/ankurm/process/DeadlockDemo.java @@ -0,0 +1,69 @@ +package com.ankurm.process; + +import java.io.InputStream; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * The classic ProcessBuilder hang: the child fills an OS pipe buffer (64 KiB on Linux) and blocks in + * write(); the parent is waiting for the child to exit and never reads. Neither can proceed. + * + *

Every demo here has a deadline so the program always finishes. + */ +public final class DeadlockDemo { + + /** Writes 200,000 bytes to the given stream: well past a 64 KiB pipe. */ + private static final String PRODUCE_STDOUT = "head -c 200000 /dev/zero | tr '\\0' x"; + private static final String PRODUCE_STDERR = "head -c 200000 /dev/zero | tr '\\0' e 1>&2"; + private static final String PRODUCE_BOTH = PRODUCE_STDOUT + "; " + PRODUCE_STDERR; + + public static void main(String[] args) throws Exception { + System.out.println("== 1. WRONG: waitFor() first, read afterwards"); + Process p = new ProcessBuilder("sh", "-c", PRODUCE_STDOUT).start(); + boolean done = p.waitFor(3, TimeUnit.SECONDS); + System.out.println("child exited within 3s? " + done); + System.out.println("child still alive? " + p.isAlive()); + // What the child is stuck on: it wrote ~64 KiB and the pipe is full. + int available = p.getInputStream().available(); + System.out.println("bytes sitting in the pipe: " + available); + p.destroyForcibly().waitFor(); + + System.out.println(); + System.out.println("== 2. RIGHT (one stream): read to EOF, then waitFor()"); + Process q = new ProcessBuilder("sh", "-c", PRODUCE_STDOUT).start(); + byte[] all = q.getInputStream().readAllBytes(); + System.out.println("read " + all.length + " bytes, exit code " + q.waitFor()); + + System.out.println(); + System.out.println("== 3. STILL WRONG: read stdout to EOF, but the child also fills stderr"); + Process r = new ProcessBuilder("sh", "-c", PRODUCE_BOTH).start(); + // Reading stdout to EOF blocks forever: the child is stuck writing stderr and never closes stdout. + Thread reader = Thread.ofVirtual().start(() -> { + try { r.getInputStream().readAllBytes(); } catch (Exception ignored) { } + }); + reader.join(Duration.ofSeconds(3)); + System.out.println("stdout reader finished within 3s? " + !reader.isAlive()); + r.destroyForcibly().waitFor(); + + System.out.println(); + System.out.println("== 4. FIX A: merge stderr into stdout, one stream to drain"); + ProcessBuilder merged = new ProcessBuilder("sh", "-c", PRODUCE_BOTH).redirectErrorStream(true); + Process s = merged.start(); + System.out.println("read " + s.getInputStream().readAllBytes().length + " bytes, exit code " + s.waitFor()); + + System.out.println(); + System.out.println("== 5. FIX B: drain both streams concurrently (what ProcessRunner does)"); + ProcessRunner.Result res = ProcessRunner.run(List.of("sh", "-c", PRODUCE_BOTH)); + System.out.println("stdout=" + res.stdout().length() + " stderr=" + res.stderr().length() + + " exit=" + res.exitCode() + " timedOut=" + res.timedOut()); + + System.out.println(); + System.out.println("== 6. FIX C: do not pipe at all. Send output to a file or discard it"); + Process t = new ProcessBuilder("sh", "-c", PRODUCE_BOTH) + .redirectOutput(ProcessBuilder.Redirect.DISCARD) + .redirectError(ProcessBuilder.Redirect.DISCARD) + .start(); + System.out.println("waitFor() returned immediately with exit code " + t.waitFor()); + } +} diff --git a/process-api/src/main/java/com/ankurm/process/EnvironmentDemo.java b/process-api/src/main/java/com/ankurm/process/EnvironmentDemo.java new file mode 100644 index 0000000..c9c9911 --- /dev/null +++ b/process-api/src/main/java/com/ankurm/process/EnvironmentDemo.java @@ -0,0 +1,75 @@ +package com.ankurm.process; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +/** Environment variables, working directory and redirection: the configuration around start(). */ +public final class EnvironmentDemo { + public static void main(String[] args) throws Exception { + System.out.println("== 1. the child inherits a COPY of our environment"); + ProcessBuilder pb = new ProcessBuilder("sh", "-c", "echo GREETING=$GREETING MODE=$MODE"); + pb.environment().put("GREETING", "hello"); + System.out.println("child sees : " + run(pb)); + System.out.println("our own env: GREETING=" + System.getenv("GREETING") + " (unchanged)"); + + System.out.println(); + System.out.println("== 2. clear() and rebuild: pass only what the child needs"); + ProcessBuilder clean = new ProcessBuilder("sh", "-c", "echo HOME=[$HOME] PATH=[$PATH] MODE=[$MODE]"); + clean.environment().clear(); + clean.environment().put("MODE", "minimal"); + System.out.println("child sees : " + run(clean)); + + System.out.println(); + System.out.println("== 3. which PATH finds the program? start() uses OURS; the child's PATH is for the child"); + ProcessBuilder lookup = new ProcessBuilder("date", "+%Y"); + lookup.environment().put("PATH", "/nonexistent"); + System.out.println("start(\"date\") with child PATH=/nonexistent : " + run(lookup).matches("\\d{4}") + + " (resolved with the parent's PATH)"); + ProcessBuilder viaShell = new ProcessBuilder("sh", "-c", "date +%Y"); + viaShell.environment().put("PATH", "/nonexistent"); + System.out.println("sh -c 'date +%Y' with child PATH=/nonexistent : " + run(viaShell)); + + System.out.println(); + System.out.println("== 4. working directory"); + Path dir = Files.createTempDirectory("procdemo"); + Files.writeString(dir.resolve("marker.txt"), "x"); + ProcessBuilder ls = new ProcessBuilder("ls").directory(dir.toFile()); + System.out.println("ls in temp dir: " + run(ls)); + try { + new ProcessBuilder("ls").directory(new File("/no/such/dir")).start(); + } catch (Exception e) { + System.out.println("bad directory -> " + e.getClass().getSimpleName() + ": " + e.getMessage()); + } + + System.out.println(); + System.out.println("== 5. redirect to files: no pipe, so nothing to drain"); + Path outFile = dir.resolve("out.log"); + Process p = new ProcessBuilder("sh", "-c", "echo to-stdout; echo to-stderr 1>&2") + .redirectOutput(outFile.toFile()) + .redirectErrorStream(true) + .start(); + System.out.println("exit " + p.waitFor() + ", file contains: " + + Files.readString(outFile).replace("\n", " | ")); + System.out.println("getInputStream() on a redirected process is a null stream: read() = " + + p.getInputStream().read()); + + System.out.println(); + System.out.println("== 6. stdin: close it, or a reader like cat never sees EOF"); + Process cat = new ProcessBuilder("cat").start(); + try (var w = cat.outputWriter()) { + w.write("line one\nline two\n"); + } // closing the writer closes the child's stdin + System.out.println("cat echoed: " + new String(cat.getInputStream().readAllBytes()).replace("\n", " | ") + + " exit " + cat.waitFor()); + } + + private static String run(ProcessBuilder pb) throws Exception { + pb.redirectErrorStream(true); + Process p = pb.start(); + String s = new String(p.getInputStream().readAllBytes()).strip(); + p.waitFor(); + return s; + } +} diff --git a/process-api/src/main/java/com/ankurm/process/HandleDemo.java b/process-api/src/main/java/com/ankurm/process/HandleDemo.java new file mode 100644 index 0000000..658a01d --- /dev/null +++ b/process-api/src/main/java/com/ankurm/process/HandleDemo.java @@ -0,0 +1,48 @@ +package com.ankurm.process; + +import java.util.List; +import java.util.concurrent.CompletableFuture; + +/** ProcessHandle: pid, info, onExit(), pipelines, and looking at processes we did not start. */ +public final class HandleDemo { + public static void main(String[] args) throws Exception { + System.out.println("== 1. our own process"); + ProcessHandle me = ProcessHandle.current(); + System.out.println("pid > 0: " + (me.pid() > 0) + ", command ends with java: " + + me.info().command().orElse("?").endsWith("java")); + System.out.println("has a parent: " + me.parent().isPresent()); + + System.out.println(); + System.out.println("== 2. onExit() instead of a blocked thread"); + Process p = new ProcessBuilder("sh", "-c", "sleep 1; exit 3").start(); + CompletableFuture done = p.onExit().thenAccept(proc -> + System.out.println("callback: exited with " + proc.exitValue())); + System.out.println("main thread is free; alive = " + p.isAlive()); + done.join(); + + System.out.println(); + System.out.println("== 3. what ProcessHandle.Info reveals about a child"); + Process c = new ProcessBuilder("sleep", "5").start(); + ProcessHandle.Info info = c.info(); + System.out.println("command = " + info.command().orElse("?")); + System.out.println("arguments = " + info.arguments().map(a -> String.join(" ", a)).orElse("?")); + System.out.println("user set = " + info.user().isPresent() + ", startInstant set = " + + info.startInstant().isPresent()); + c.destroyForcibly().waitFor(); + + System.out.println(); + System.out.println("== 4. a handle to a finished process"); + System.out.println("alive after exit: " + c.toHandle().isAlive()); + + System.out.println(); + System.out.println("== 5. a real pipeline without a shell: printf | sort | uniq -c"); + List procs = ProcessBuilder.startPipeline(List.of( + new ProcessBuilder("printf", "b\\na\\nb\\nc\\nb\\n"), + new ProcessBuilder("sort"), + new ProcessBuilder("uniq", "-c"))); + Process last = procs.get(procs.size() - 1); + System.out.print(new String(last.getInputStream().readAllBytes())); + for (Process x : procs) x.waitFor(); + System.out.println("stages: " + procs.size()); + } +} diff --git a/process-api/src/main/java/com/ankurm/process/InjectionDemo.java b/process-api/src/main/java/com/ankurm/process/InjectionDemo.java new file mode 100644 index 0000000..beb85ca --- /dev/null +++ b/process-api/src/main/java/com/ankurm/process/InjectionDemo.java @@ -0,0 +1,50 @@ +package com.ankurm.process; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +/** Command injection through a shell string, option injection through an argument list, and the fixes. */ +public final class InjectionDemo { + public static void main(String[] args) throws Exception { + Path dir = Files.createTempDirectory("inject"); + Files.writeString(dir.resolve("report.txt"), "quarterly numbers\n"); + Files.writeString(dir.resolve("secret.txt"), "TOP-SECRET\n"); + String hostile = "report.txt; cat secret.txt"; + + System.out.println("== 1. VULNERABLE: build a shell string from user input"); + run(dir, List.of("sh", "-c", "wc -c " + hostile)); + + System.out.println(); + System.out.println("== 2. SAFE: argument list, no shell. The whole input is one filename"); + run(dir, List.of("wc", "-c", hostile)); + + System.out.println(); + System.out.println("== 3. SAFE but still a trap: option injection. Input '-l' is read as a flag"); + run(dir, List.of("ls", "-l")); + System.out.println("(the caller wanted to list a file called '-l'; ls took it as an option)"); + + System.out.println(); + System.out.println("== 4. FIX: '--' ends option parsing, then validate"); + run(dir, List.of("ls", "--", "-l")); + + System.out.println(); + System.out.println("== 5. FIX: allow-list the input before it gets anywhere near a command"); + for (String candidate : List.of("report.txt", hostile, "-l", "../etc/passwd")) { + System.out.println(String.format("%-28s -> %s", "'" + candidate + "'", safeName(candidate))); + } + } + + /** Conservative allow-list: a plain file name, no leading dash, no path separators. */ + static boolean safeName(String s) { + return s.matches("[A-Za-z0-9][A-Za-z0-9._]{0,63}"); + } + + private static void run(Path dir, List cmd) throws Exception { + ProcessBuilder pb = new ProcessBuilder(cmd).directory(dir.toFile()).redirectErrorStream(true); + Process p = pb.start(); + String out = new String(p.getInputStream().readAllBytes()).strip().replace("\n", "\n "); + System.out.println("$ " + String.join(" ", cmd.subList(0, Math.min(cmd.size(), 3))) + (cmd.size() > 3 ? " ..." : "")); + System.out.println(" " + out + " [exit " + p.waitFor() + "]"); + } +} diff --git a/process-api/src/main/java/com/ankurm/process/ProcessRunner.java b/process-api/src/main/java/com/ankurm/process/ProcessRunner.java new file mode 100644 index 0000000..03c34f0 --- /dev/null +++ b/process-api/src/main/java/com/ankurm/process/ProcessRunner.java @@ -0,0 +1,136 @@ +package com.ankurm.process; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * A small, safe "run a command and give me the result" helper. + * + *

What it does that a bare {@code new ProcessBuilder(...).start()} does not: + *

+ */ +public final class ProcessRunner { + + /** Outcome of one run. {@code exitCode} is -1 when the process was killed on timeout. */ + public record Result(int exitCode, String stdout, String stderr, + boolean timedOut, boolean truncated, Duration elapsed) { + public boolean ok() { return !timedOut && exitCode == 0; } + } + + /** Immutable run settings. */ + public record Options(Duration timeout, long maxCaptureBytes, Map extraEnv) { + public static Options defaults() { return new Options(Duration.ofSeconds(10), 1 << 20, Map.of()); } + public Options withTimeout(Duration d) { return new Options(d, maxCaptureBytes, extraEnv); } + public Options withMaxCapture(long n) { return new Options(timeout, n, extraEnv); } + } + + /** How long to wait for the pipe readers to reach EOF after the child has exited. */ + static final Duration READER_GRACE = Duration.ofSeconds(1); + + private ProcessRunner() { } + + private static void joinUntil(Thread t, long deadlineNanos) throws InterruptedException { + long left = deadlineNanos - System.nanoTime(); + if (left > 0) t.join(Duration.ofNanos(left)); + } + + public static Result run(List command) throws IOException, InterruptedException { + return run(command, Options.defaults()); + } + + public static Result run(List command, Options opt) throws IOException, InterruptedException { + long t0 = System.nanoTime(); + ProcessBuilder pb = new ProcessBuilder(command); // argument list: no shell, no injection + pb.environment().putAll(opt.extraEnv()); + Process p = pb.start(); + p.getOutputStream().close(); // stdin: immediate EOF + + Capture out = new Capture(p.getInputStream(), opt.maxCaptureBytes()); + Capture err = new Capture(p.getErrorStream(), opt.maxCaptureBytes()); + Thread to = Thread.ofVirtual().name("drain-out-" + p.pid()).start(out); + Thread te = Thread.ofVirtual().name("drain-err-" + p.pid()).start(err); + + boolean finished = p.waitFor(opt.timeout()); + boolean timedOut = !finished; + if (timedOut) { + killTree(p); + } + // Readers normally end at EOF the moment the child exits. If a grandchild inherited the pipes, + // EOF only comes when IT exits, so give the readers one shared grace period, then close the + // streams (best effort: on Linux this does not always interrupt a read already in progress) and + // stop waiting. An abandoned reader stays blocked, and the pipe stays open, until the + // grandchild exits. + long graceEnd = System.nanoTime() + READER_GRACE.toNanos(); + joinUntil(to, graceEnd); + joinUntil(te, graceEnd); + if (to.isAlive() || te.isAlive()) { + closeQuietly(p.getInputStream()); + closeQuietly(p.getErrorStream()); + to.join(Duration.ofMillis(200)); + te.join(Duration.ofMillis(200)); + } + int exit = timedOut ? -1 : p.exitValue(); + return new Result(exit, out.text(), err.text(), timedOut, + out.truncated || err.truncated, Duration.ofNanos(System.nanoTime() - t0)); + } + + /** + * Kills {@code p} and every descendant. Descendants must be snapshotted before the parent + * dies: once it is gone its children are re-parented to init and {@code descendants()} no longer + * finds them. + */ + public static void killTree(Process p) throws InterruptedException { + List tree = new ArrayList<>(); + p.descendants().forEach(tree::add); + p.destroyForcibly(); + tree.forEach(ProcessHandle::destroyForcibly); + p.waitFor(5, TimeUnit.SECONDS); + } + + private static void closeQuietly(InputStream in) { + try { in.close(); } catch (IOException ignored) { } + } + + /** Reads a stream to EOF, keeping at most {@code max} bytes and discarding (not blocking on) the rest. */ + private static final class Capture implements Runnable { + private final InputStream in; + private final long max; + private final ByteArrayOutputStream buf = new ByteArrayOutputStream(); + volatile boolean truncated; + + Capture(InputStream in, long max) { this.in = in; this.max = max; } + + @Override public void run() { + byte[] chunk = new byte[8192]; + try { + int n; + while ((n = in.read(chunk)) != -1) { + synchronized (buf) { + long room = max - buf.size(); + if (room > 0) buf.write(chunk, 0, (int) Math.min(room, n)); + if (n > room) truncated = true; + } + } + } catch (IOException ignored) { + // stream closed by killTree/closeQuietly: stop reading + } + } + + String text() { + synchronized (buf) { return buf.toString(StandardCharsets.UTF_8); } + } + } +} diff --git a/process-api/src/main/java/com/ankurm/process/TimeoutDemo.java b/process-api/src/main/java/com/ankurm/process/TimeoutDemo.java new file mode 100644 index 0000000..a32858c --- /dev/null +++ b/process-api/src/main/java/com/ankurm/process/TimeoutDemo.java @@ -0,0 +1,65 @@ +package com.ankurm.process; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** Timeouts, and why killing the direct child is not enough. */ +public final class TimeoutDemo { + public static void main(String[] args) throws Exception { + System.out.println("== 1. waitFor(timeout) returns false; it does NOT stop the process"); + Process p = new ProcessBuilder("sleep", "30").start(); + System.out.println("waitFor(500ms) = " + p.waitFor(500, TimeUnit.MILLISECONDS)); + System.out.println("still alive = " + p.isAlive()); + p.destroy(); // SIGTERM + System.out.println("destroy() then waitFor -> exit code " + p.waitFor() + " (128 + SIGTERM 15 = 143)"); + + System.out.println(); + System.out.println("== 2. a shell command spawns a child; destroying the shell orphans it"); + Process sh = new ProcessBuilder("sh", "-c", "sleep 40 & wait").start(); + Thread.sleep(300); + List kids = sh.descendants().toList(); + System.out.println("descendants of the shell: " + kids.size() + " -> " + + kids.stream().map(h -> h.info().command().orElse("?")).toList()); + ProcessHandle orphan = kids.get(0); + sh.destroyForcibly().waitFor(); + Thread.sleep(200); + System.out.println("shell dead, orphan alive = " + orphan.isAlive() + " <- leaked process"); + orphan.destroyForcibly(); + orphan.onExit().join(); + + System.out.println(); + System.out.println("== 3. kill the tree: snapshot descendants first, then kill all"); + Process sh2 = new ProcessBuilder("sh", "-c", "sleep 40 & wait").start(); + Thread.sleep(300); + ProcessHandle child = sh2.descendants().findFirst().orElseThrow(); + ProcessRunner.killTree(sh2); + child.onExit().join(); + System.out.println("shell alive = " + sh2.isAlive() + ", former child alive = " + child.isAlive()); + + System.out.println(); + System.out.println("== 4. ProcessRunner with a deadline"); + ProcessRunner.Result r = ProcessRunner.run(List.of("sh", "-c", "echo started; sleep 40 & wait"), + ProcessRunner.Options.defaults().withTimeout(Duration.ofSeconds(1))); + System.out.println("timedOut=" + r.timedOut() + " exit=" + r.exitCode() + " stdout=" + r.stdout().strip() + + " elapsed<2s=" + (r.elapsed().toMillis() < 2000)); + + System.out.println(); + System.out.println("== 5. a background grandchild keeps the pipe open: readAllBytes() waits for IT"); + long t0 = System.nanoTime(); + Process bg = new ProcessBuilder("sh", "-c", "(sleep 4; echo late) & echo done").start(); + byte[] out = bg.getInputStream().readAllBytes(); // blocks until the grandchild closes the pipe + long ms = (System.nanoTime() - t0) / 1_000_000; + System.out.println("sh exited at once, but readAllBytes() took ~" + (ms / 1000) + "s; got " + + new String(out).replace("\n", "|")); + bg.waitFor(); + + System.out.println(); + System.out.println("== 6. ProcessRunner is not held hostage by the same command"); + ProcessRunner.Result r2 = ProcessRunner.run(List.of("sh", "-c", "(sleep 4; echo late) & echo done"), + ProcessRunner.Options.defaults()); + System.out.println("exit=" + r2.exitCode() + " stdout=" + r2.stdout().replace("\n", "|") + + " returned in under 2s: " + (r2.elapsed().toMillis() < 2000) + + " (bounded by the 1s reader grace, not by the 4s grandchild)"); + } +} diff --git a/process-api/src/test/java/com/ankurm/process/ProcessClaimsTest.java b/process-api/src/test/java/com/ankurm/process/ProcessClaimsTest.java new file mode 100644 index 0000000..e7c55f9 --- /dev/null +++ b/process-api/src/test/java/com/ankurm/process/ProcessClaimsTest.java @@ -0,0 +1,222 @@ +package com.ankurm.process; + +import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.time.Duration; +import java.util.List; +import java.util.concurrent.TimeUnit; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; + +/** One assertion per claim the post makes. Unix-only: it needs sh, sleep, head, tr, cat, wc. */ +class ProcessClaimsTest { + + private static final String PRODUCE_STDOUT = "head -c 200000 /dev/zero | tr '\\0' x"; + private static final String PRODUCE_BOTH = PRODUCE_STDOUT + "; head -c 200000 /dev/zero | tr '\\0' e 1>&2"; + + @BeforeAll + static void unixOnly() { + assumeTrue(Files.isExecutable(Path.of("/bin/sh")), "needs a Unix shell"); + } + + @Test + void failingCommandIsAnExitCodeAndMissingBinaryIsAnException() throws Exception { + Process f = new ProcessBuilder("ls", "/definitely/not/here").start(); + f.getErrorStream().readAllBytes(); + assertEquals(2, f.waitFor()); + IOException e = assertThrows(IOException.class, () -> new ProcessBuilder("no-such-binary-xyz").start()); + assertTrue(e.getMessage().contains("error: 2") || e.getMessage().contains("error=2"), e.getMessage()); + } + + @Test + void exitValueBeforeExitThrows() throws Exception { + Process p = new ProcessBuilder("sleep", "5").start(); + try { + assertThrows(IllegalThreadStateException.class, p::exitValue); + assertFalse(p.waitFor(100, TimeUnit.MILLISECONDS)); + } finally { + p.destroyForcibly().waitFor(); + } + assertEquals(137, p.exitValue()); + } + + @Test + void shellIsNotInvolved() throws Exception { + Process g = new ProcessBuilder("echo", "*.txt", "$HOME", "a|b").start(); + assertEquals("*.txt $HOME a|b", new String(g.getInputStream().readAllBytes()).strip()); + g.waitFor(); + } + + @Test + void unreadPipeBlocksTheChildAtThePipeBufferSize() throws Exception { + Process p = new ProcessBuilder("sh", "-c", PRODUCE_STDOUT).start(); + try { + assertFalse(p.waitFor(2, TimeUnit.SECONDS), "child must be stuck in write()"); + assertTrue(p.isAlive()); + int inPipe = p.getInputStream().available(); + assertTrue(inPipe > 0 && inPipe < 200_000, "only a pipe-buffer's worth arrived: " + inPipe); + } finally { + p.destroyForcibly().waitFor(); + } + } + + @Test + void readingOnlyStdoutStillDeadlocksWhenStderrFills() throws Exception { + Process r = new ProcessBuilder("sh", "-c", PRODUCE_BOTH).start(); + Thread reader = Thread.ofVirtual().start(() -> { + try { r.getInputStream().readAllBytes(); } catch (Exception ignored) { } + }); + try { + reader.join(Duration.ofSeconds(2)); + assertTrue(reader.isAlive(), "stdout never reaches EOF while stderr is full"); + } finally { + r.destroyForcibly().waitFor(); + } + } + + @Test + void mergedStreamsAndConcurrentDrainBothFinish() throws Exception { + Process s = new ProcessBuilder("sh", "-c", PRODUCE_BOTH).redirectErrorStream(true).start(); + assertEquals(400_000, s.getInputStream().readAllBytes().length); + assertEquals(0, s.waitFor()); + + ProcessRunner.Result res = ProcessRunner.run(List.of("sh", "-c", PRODUCE_BOTH)); + assertEquals(200_000, res.stdout().length()); + assertEquals(200_000, res.stderr().length()); + assertTrue(res.ok()); + } + + @Test + void captureCapTruncatesButNeverBlocksTheChild() throws Exception { + ProcessRunner.Result res = ProcessRunner.run(List.of("sh", "-c", PRODUCE_STDOUT), + ProcessRunner.Options.defaults().withMaxCapture(1000)); + assertEquals(1000, res.stdout().length()); + assertTrue(res.truncated()); + assertEquals(0, res.exitCode()); + } + + @Test + void destroyingTheShellOrphansItsChildButKillTreeDoesNot() throws Exception { + Process sh = new ProcessBuilder("sh", "-c", "sleep 40 & wait").start(); + Thread.sleep(300); + ProcessHandle orphan = sh.descendants().findFirst().orElseThrow(); + sh.destroyForcibly().waitFor(); + Thread.sleep(200); + assertEquals(0, sh.descendants().count(), "descendants() is empty once the parent is dead"); + assertTrue(orphan.isAlive(), "the orphan survives its parent"); + orphan.destroyForcibly(); + orphan.onExit().join(); + + Process sh2 = new ProcessBuilder("sh", "-c", "sleep 40 & wait").start(); + Thread.sleep(300); + ProcessHandle child = sh2.descendants().findFirst().orElseThrow(); + ProcessRunner.killTree(sh2); + child.onExit().join(); + assertFalse(child.isAlive()); + } + + @Test + void runnerTimeoutKillsTheWholeTree() throws Exception { + ProcessRunner.Result r = ProcessRunner.run(List.of("sh", "-c", "sleep 40 & echo $!; wait"), + ProcessRunner.Options.defaults().withTimeout(Duration.ofSeconds(1))); + assertTrue(r.timedOut()); + assertEquals(-1, r.exitCode()); + long pid = Long.parseLong(r.stdout().strip()); + ProcessHandle gc = ProcessHandle.of(pid).orElse(null); + if (gc != null) { + gc.onExit().get(5, TimeUnit.SECONDS); // a killed non-child is noticed by polling, so allow a moment + assertFalse(gc.isAlive(), "grandchild must be dead"); + } + assertTrue(r.elapsed().toMillis() < 3000, "elapsed " + r.elapsed()); + } + + @Test + void aBackgroundGrandchildHoldsAPlainReadHostageButNotTheRunner() throws Exception { + // warm up: the very first spawn in a JVM is slow enough for the exit-time drain to hide the effect + new ProcessBuilder("true").start().waitFor(); + long t0 = System.nanoTime(); + Process bg = new ProcessBuilder("sh", "-c", "(sleep 3; echo late) & echo done").start(); + byte[] out = bg.getInputStream().readAllBytes(); + long plainMs = (System.nanoTime() - t0) / 1_000_000; + bg.waitFor(); + assertTrue(plainMs >= 2500, "plain read waited for the grandchild: " + plainMs + " ms"); + assertEquals("done\nlate\n", new String(out)); + + ProcessRunner.Result r = ProcessRunner.run(List.of("sh", "-c", "(sleep 3; echo late) & echo done")); + assertTrue(r.elapsed().toMillis() < 2000, "runner elapsed " + r.elapsed()); + assertEquals("done\n", r.stdout()); + } + + @Test + void environmentIsACopyAndProgramLookupUsesTheParentsPath() throws Exception { + ProcessBuilder pb = new ProcessBuilder("sh", "-c", "echo $GREETING"); + pb.environment().put("GREETING", "hello"); + Process p = pb.start(); + assertEquals("hello", new String(p.getInputStream().readAllBytes()).strip()); + p.waitFor(); + assertNull(System.getenv("GREETING")); + + ProcessBuilder viaShell = new ProcessBuilder("sh", "-c", "date +%Y").redirectErrorStream(true); + viaShell.environment().put("PATH", "/nonexistent"); + Process q = viaShell.start(); + assertTrue(new String(q.getInputStream().readAllBytes()).contains("not found")); + q.waitFor(); + + ProcessBuilder direct = new ProcessBuilder("date", "+%Y"); + direct.environment().put("PATH", "/nonexistent"); + Process d = direct.start(); + assertTrue(new String(d.getInputStream().readAllBytes()).strip().matches("\\d{4}")); + d.waitFor(); + } + + @Test + void stdinMustBeClosedForCatToFinish() throws Exception { + Process cat = new ProcessBuilder("cat").start(); + assertFalse(cat.waitFor(500, TimeUnit.MILLISECONDS), "cat waits for EOF on stdin"); + cat.getOutputStream().close(); + assertTrue(cat.waitFor(2, TimeUnit.SECONDS)); + + ProcessRunner.Result r = ProcessRunner.run(List.of("cat")); + assertTrue(r.ok(), "the runner closes stdin up front"); + } + + @Test + void shellStringInjectsButArgumentListDoesNot() throws Exception { + Path dir = Files.createTempDirectory("inject"); + Files.writeString(dir.resolve("report.txt"), "quarterly numbers\n"); + Files.writeString(dir.resolve("secret.txt"), "TOP-SECRET\n"); + String hostile = "report.txt; cat secret.txt"; + + String shell = out(dir, List.of("sh", "-c", "wc -c " + hostile)); + assertTrue(shell.contains("TOP-SECRET")); + String list = out(dir, List.of("wc", "-c", hostile)); + assertFalse(list.contains("TOP-SECRET")); + + assertTrue(out(dir, List.of("ls", "-l")).contains("secret.txt"), "'-l' was taken as an option"); + assertTrue(out(dir, List.of("ls", "--", "-l")).contains("cannot access")); + assertTrue(InjectionDemo.safeName("report.txt")); + assertFalse(InjectionDemo.safeName(hostile)); + assertFalse(InjectionDemo.safeName("-l")); + assertFalse(InjectionDemo.safeName("../etc/passwd")); + } + + @Test + void pipelineWithoutAShell() throws Exception { + List ps = ProcessBuilder.startPipeline(List.of( + new ProcessBuilder("printf", "b\\na\\nb\\n"), new ProcessBuilder("sort"), new ProcessBuilder("uniq", "-c"))); + String out = new String(ps.get(2).getInputStream().readAllBytes()); + assertEquals(3, ps.size()); + assertEquals(" 1 a\n 2 b\n", out); + } + + private static String out(Path dir, List cmd) throws Exception { + Process p = new ProcessBuilder(cmd).directory(dir.toFile()).redirectErrorStream(true).start(); + String s = new String(p.getInputStream().readAllBytes()); + p.waitFor(); + return s; + } +}