DEV Community

Aurum Revenue
Aurum Revenue

Posted on

An argv list fixed the injection. A deadline fixed the hang.

An argv list fixed the injection. A deadline fixed the hang.

For months the advice I gave was the same: stop building shell strings, pass a list. If a value came from a user, it stayed data. subprocess.run(["echo", text]) and the parentheses, backticks and $(...) inside text never reach a shell, because there is no shell to reach.

That part works. I shipped a small library, shellguard, that refuses shell=True and bare-string commands so nobody on my team can drift back into the old habit. It is 144 tests deep now, and the attack suite covers the usual metacharacters.

But a clean injection story still leaves one failure on the table.

A command can be perfectly safe and still never come back.

I had a wrapper around a CLI that occasionally blocked waiting on input nobody was going to give it. The argv list was fine. No shell involved. The process just sat there, holding a worker slot, until something upstream gave up and killed the whole job. At the time I treated it as an infrastructure problem. It was not. It was a missing argument.

Injection is about what a command parses. A hang is about how long it runs. Passing a list answers the first question and says nothing about the second. I had been so focused on the first that I forgot the other half of running something you do not control.

So I made the deadline a first-class argument instead of an afterthought.

What it looks like

The library raises a typed Timeout when a command blows its budget, so a caller can catch that one case instead of a bare subprocess.TimeoutExpired:

import shellguard as sg

try:
    sg.run(["python", "-c", "import time; time.sleep(5)"], timeout=0.3)
except sg.Timeout as exc:
    print(exc)
Enter fullscreen mode Exit fullscreen mode

Real output from that call on my machine:

command exceeded 0.3s: ['python', '-c']
Enter fullscreen mode Exit fullscreen mode

That is the whole point. The value I cared about — the command exceeded its budget — is now an exception I can name, log, and handle. It does not get swallowed into a generic failure or, worse, never surface at all.

The two halves, side by side

The injection guard and the deadline solve different problems, and I finally keep them next to each other:

import shellguard as sg

# Half one: untrusted text stays data, never shell syntax.
r = sg.run(["echo", "$(touch pwned)"])
print(r.stdout)          # literal string, no file created

# Half two: untrusted runtime is bounded.
sg.run(["slow-tool"], timeout=2.0)  # raises sg.Timeout after 2s
Enter fullscreen mode Exit fullscreen mode

I ran the first line here too. The output is the literal string, with the $(...) intact and no file written:

$(touch pwned)
Enter fullscreen mode Exit fullscreen mode

And the library still refuses the dangerous modes outright rather than quietly allowing them:

sg.run(["echo hi"], shell=True)   # -> SafetyError
Enter fullscreen mode Exit fullscreen mode

Which prints, on a real run:

shell=True is refused: a shell parses untrusted text. Pass an argv list to run() instead.
Enter fullscreen mode Exit fullscreen mode

Three lines of defense, three different jobs: keep text as data, refuse the shell path, and bound the time. I used to ship the first two and call it done.

A deadline is not a substitute for thinking

To be honest about the limits: a timeout is a guardrail, not a fix-all. subprocess kills the child when the budget is up, but it does not guarantee a graceful shutdown, and it does not undo side effects the command already committed. If your tool writes a file before it blocks, that file is still there. Set the number from something you can defend — a measured p99, a user-facing SLA — not a round figure you guessed at 2 in the morning.

It also does not replace input validation. An argv list stops shell injection, not argument injection: a value like -l handed to ls is still parsed as a flag by the program you called. Separate concern, separate fix (-- where the tool supports it). The deadline is about time, full stop.

Why I am writing this down

I keep seeing the same pattern in code review: someone has done the security part properly — argv lists, no shell — and then left the process free to run forever. The injection story is well told. The hang story is not. Both come from the same habit of treating an external command as something that returns promptly.

If you are carrying an f-string-built shell command around, the source for this is MIT and free. If your team wants the offline commercial license and the audit trail, it is a one-time EUR 49: https://buy.stripe.com/00weVg5HQawocP77lS4ko0S

Either way, give the command a deadline. The process you do not control will eventually thank you, or at least stop holding your worker hostage.

Top comments (1)

Collapse
 
acemeridian profile image
Ace Meridian •

The deadline half is right, but timeout= alone left two gaps when I tried it with plain subprocess.run (Python 3.14.4, Linux, two runs, same numbers):

prompt, inherited stdin         1.00s  TimeoutExpired(stdout=b'continue? ')
prompt, stdin=DEVNULL           0.11s  rc=1 stdout='continue? '
sh done in ms, bg child         1.02s  TimeoutExpired(stdout=b'started\n')  orphans=1
timeout=1, bg child             1.02s  TimeoutExpired(stdout=b'started\n')  orphans=1
group kill, bg child            1.02s  TimeoutExpired(stdout=b'started\n')  orphans=0
Enter fullscreen mode Exit fullscreen mode
  1. For your "CLI blocked waiting on input" case, the timeout turns a hang into a 1 s failure, but the cause is still stdin. The child inherits the worker's stdin, and if that is an open pipe nobody writes to, input() waits forever. With stdin=subprocess.DEVNULL the same CLI gets EOF and exits in 0.11 s with rc=1. That's a real error you can read, instead of a timeout you have to guess about. I'd make DEVNULL the default in a wrapper like shellguard, and let callers opt in to passing input.

  2. A deadline doesn't stop the work. sh -c "sleep 4 & echo started" exits in milliseconds with rc 0, but run() still raises TimeoutExpired, because the background child holds the stdout pipe open and communicate() waits for EOF. And after a timeout, run() kills only the direct child, so the background sleep keeps running as an orphan (1 left in both runs). Starting the child with start_new_session=True and calling os.killpg(p.pid, SIGKILL) on timeout brought that to 0.

So "kill the child when the budget is up" in your limits section really means "kill one PID", which is a smaller promise than it sounds like for tools that fork.

Does sg.run pass stdin through by default, and does it kill the process group or just the child?