Skip to content
shellhacks.dev
Security

Call Commands by Absolute Path to Harden a Shell Script

Stop a planted program from being run by a script: set PATH to system directories at the top and resolve tools with command -v, or call them by absolute path.

1 min read
Summarize in AI

A script calls tar, and a directory early in PATH holds a program with the same name.

Shell
mkdir evil
printf '#!/bin/sh\necho "evil tar ran"\n' > evil/tar
chmod +x evil/tar
cat > unsafe.sh <<'EOF'
#!/bin/bash
tar --version | head -n 1
EOF
cat > safe.sh <<'EOF'
#!/bin/bash
PATH=/usr/sbin:/usr/bin:/sbin:/bin
tar=$(command -v tar) || { echo "tar is not installed" >&2; exit 1; }
"$tar" --version | head -n 1
EOF
PATH=$PWD/evil:$PATH bash unsafe.sh
PATH=$PWD/evil:$PATH bash safe.sh
Text
evil tar ran
tar (GNU tar) 1.34

The shell runs the first match along PATH. The unsafe script ran the fake tar placed in the first directory and printed evil tar ran, while the safe one replaces PATH with the system directories before it does anything else, resolves the command with command -v and reported tar (GNU tar) 1.34. Failing early when command -v finds nothing gives a clear error instead of a surprise later. See command in the specification.

A fixed PATH hides tools in /usr/local/bin or a home directory, so add those you need and nothing writable by other users. An empty entry or a dot in PATH has the same effect as a planted program. Scripts run with sudo or from cron should not trust the caller's PATH either.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.