Validating Paths and User-Supplied Filenames
A script that accepts a file name or a path from someone else, as a command-line argument, a form field passed in by a web handler, a line in a configuration file or the name of an uploaded file, is letting that person choose which file the script opens, creates or deletes. Path validation is the step that decides, before any file is touched, whether the supplied value names a file the script is actually allowed to use.
Without validation, a script that means to read "a document from the docs folder" will happily read ../../etc/shadow, follow a symbolic link to another user's files, or write over .bashrc. This class of bug is called path traversal (or directory traversal), and it is one of the most common security problems in any program that handles file names, shell scripts included. Lesson 160 showed a first version of the containment check; this lesson explains each part of path validation in detail and builds a complete tool around it.
Understanding the Concept
A file name supplied by a user can go wrong in two separate ways.
- The text itself is unsafe. It may contain
/or..that climb out of the intended folder, start with-and be read as an option, start with.and reach hidden files such as.envor.git/config, contain newlines or other control characters that break logs and later processing, be empty, or be far too long. - The text looks fine, but the location it reaches is wrong. A harmless-looking name such as
guides/escape.txtcan be a symbolic link that points somewhere else entirely. Only the file system knows where a path really leads, so the text alone can never prove that a path is safe.
Good validation therefore has two layers:
- Text rules (an allowlist of characters and shapes) reject obviously unsafe input early and give clear error messages.
- Resolution and containment turn the path into its real, absolute location with
realpathand confirm that this location lies inside an allowed base folder.
Each layer catches problems the other misses, so careful scripts use both.
Why Simple Joining Is Dangerous
The most natural way to use a supplied name is to append it to a base folder:
BASE=/srv/t161/docs
cat -- "$BASE/$1"
The base folder in this lesson's examples is /srv/t161/docs. It holds readme.txt and guides/install.txt, and also a symbolic link guides/escape.txt that points to /srv/t161/other/secret.txt, a file outside the base folder:
bash naive.sh readme.txt
bash naive.sh ../other/secret.txt
bash naive.sh guides/escape.txt
hello
top secret
top secret
The first call does what was intended. The second climbs out of the base folder with ... The third never mentions .. at all; it just names a symbolic link inside the folder, and the kernel follows it. Quoting the variable and using -- (lesson 155) protect against word splitting and option injection, but they do nothing about where the path leads.
Why removing "../" does not work
A common first attempt is to delete every ../ from the input:
p='....//....//other/secret.txt'
echo "${p//..\//}"
../../other/secret.txt
Removing ../ from ....// leaves ../ behind, so the cleaned value is more dangerous than before. Rewriting input until it "looks safe" is fragile. Instead, reject input that does not match the allowed shape, and check where accepted input really leads.
Validating a Single File Name
When the script needs only a file name, with no folders (for example, the name under which to store an upload), the safest approach is a short allowlist: say exactly what a valid name looks like and reject everything else.
export LC_ALL=C
valid_name() {
local n=$1
[[ -n $n ]] || { echo "empty name"; return 1; }
[[ $n != .* ]] || { echo "starts with a dot"; return 1; }
[[ $n != -* ]] || { echo "starts with a hyphen"; return 1; }
[[ $n =~ ^[A-Za-z0-9._-]+$ ]] || { echo "invalid characters"; return 1; }
(( ${#n} <= 100 )) || { echo "longer than 100 characters"; return 1; }
}
Each rule has a clear purpose:
| Rule | What it blocks |
|---|---|
-n $n | an empty value, which would turn $BASE/$n into the folder itself |
no leading . | ., .., and hidden files such as .bashrc and .env |
no leading - | names that commands would read as options, such as -rf |
^[A-Za-z0-9._-]+$ | /, spaces, quotes, *, $, newlines and every other character not listed |
| length limit | names longer than the file system allows (usually 255 bytes) or than you want to store |
Testing the function against a list of names:
long=$(printf 'a%.0s' {1..120})
for n in report.txt ../etc/passwd a/b '' .. .hidden -rf 'my file.txt' $'bad\nname' café.txt 'x.txt ' "$long"; do
shown=$(printf '%q' "$n"); (( ${#shown} > 20 )) && shown="${shown:0:12}...(${#n})"
if msg=$(valid_name "$n"); then printf 'OK %s\n' "$shown"; else printf 'REJECT %-20s %s\n' "$shown" "$msg"; fi
done
OK report.txt
REJECT ../etc/passwd starts with a dot
REJECT a/b invalid characters
REJECT '' empty name
REJECT .. starts with a dot
REJECT .hidden starts with a dot
REJECT -rf starts with a hyphen
REJECT my\ file.txt invalid characters
REJECT $'bad\nname' invalid characters
REJECT $'caf\303\251.txt' invalid characters
REJECT x.txt\ invalid characters
REJECT aaaaaaaaaaaa...(120) longer than 100 characters
printf %q shows every rejected value unambiguously: the trailing space in x.txt appears as x.txt\ , and the newline as $'bad\nname'.
Why LC_ALL=C matters
Bracket ranges such as [A-Za-z] and the length ${#n} depend on the locale. In a UTF-8 locale, Bash counts characters, so café has length 4; in the C locale it counts bytes and the same word has length 5, because é takes two bytes. With some locales and C library versions, ranges like [a-z] also match accented letters, and [[:alpha:]] matches é in C.UTF-8. Setting LC_ALL=C makes the rules work on plain bytes, so the allowlist means exactly what it says on every system, and the length limit counts bytes, which is what the file system's 255-byte name limit (getconf NAME_MAX prints 255 on common Linux file systems) is measured in.
If your users need names with non-ASCII letters, allow them deliberately and test the result in the locale your script runs in. A restrictive allowlist with a clear error message is usually the better choice for names that a script generates or stores.
Validating a Relative Path
When users may name files in subfolders, such as guides/install.txt, apply the text rules to each component of the path. Splitting on / with read -a gives an array of components without any globbing:
check_rel() {
local p=$1 part
local -a parts
[[ $p != /* ]] || { echo "absolute path"; return 1; }
IFS=/ read -r -a parts <<< "$p"
for part in "${parts[@]}"; do
[[ -n $part ]] || { echo "empty component"; return 1; }
[[ $part != .* ]] || { echo "component starts with a dot"; return 1; }
[[ $part =~ ^[A-Za-z0-9_][A-Za-z0-9._-]*$ ]] || { echo "invalid component"; return 1; }
done
}
- An absolute path such as
/etc/passwdis rejected outright. - Because no component may start with a dot,
..and.can never appear, and neither can hidden folders like.git. - An empty component catches
a//band a trailing/. Rejecting these is stricter than the file system requires, but it keeps every accepted path in one simple, canonical form. - The pattern
^[A-Za-z0-9_][A-Za-z0-9._-]*$combines the "no leading dot or hyphen" rule and the character allowlist in one regular expression: the first character must be a letter, digit or underscore.
IFS=/ read changes IFS only for that one read command. The check for control characters (shown in the complete example) runs first, so the here string cannot contain a newline that would cut the value short.
Resolving the Real Location with realpath
Text rules cannot see symbolic links, so the second layer asks the file system where a path really leads. realpath (GNU coreutils) prints the canonical absolute path: it removes . and .. components and follows every symbolic link.
| Option | Behavior |
|---|---|
realpath -e | every component must exist; fails otherwise |
realpath -m | nothing needs to exist; resolves as far as possible |
| (no option) | all but the last component must exist |
realpath -s | does not follow symbolic links (only cleans up . and ..) |
Run from /srv/t161:
path -e -m -s -m
docs/guides/install.txt /srv/t161/docs/guides/install.txt (same for all three)
docs/guides/../readme.txt /srv/t161/docs/readme.txt (same for all three)
docs/guides/../../other/secret.txt /srv/t161/other/secret.txt (same for all three)
docs/guides/escape.txt /srv/t161/other/secret.txt /srv/t161/other/secret.txt /srv/t161/docs/guides/escape.txt
docs/outside/secret.txt /srv/t161/other/secret.txt /srv/t161/other/secret.txt /srv/t161/docs/outside/secret.txt
docs/missing.txt No such file or directory /srv/t161/docs/missing.txt /srv/t161/docs/missing.txt
(docs/outside is a symbolic link to the folder /srv/t161/other.)
The important rows are the two symbolic links. With -e or -m, realpath shows that both lead to /srv/t161/other/secret.txt. With -s, the links are not followed and the paths still look as if they were inside docs. Never use -s for a security check. Use -e when the file must already exist (reading, deleting) and -m when it may not exist yet (creating), keeping in mind that with -m the missing parts are not checked at all.
Checking Containment
After resolving, compare the result with the resolved base folder:
base=$(realpath -e /srv/t161/docs)
for rel in guides/install.txt guides/../readme.txt guides/escape.txt ../docs-old/draft.txt; do
t=$(realpath -m -- "$base/$rel")
if [[ $t == "$base"/* ]]; then echo "inside : $rel -> ${t#"$base"/}"; else echo "outside: $rel -> $t"; fi
done
inside : guides/install.txt -> guides/install.txt
inside : guides/../readme.txt -> readme.txt
outside: guides/escape.txt -> /srv/t161/other/secret.txt
outside: ../docs-old/draft.txt -> /srv/t161/docs-old/draft.txt
Three details make this comparison correct:
- Resolve the base folder too. If
/srv/t161/docswere itself reached through a symbolic link, the resolved target would never start with the unresolved base text, and every check would fail (or, worse, a hand-written variant might pass the wrong paths). - Quote the base inside the pattern. In
[[ $t == "$base"/* ]], the quotes make the base folder a literal string, so characters such as*or[in a folder name are not treated as pattern characters. - Include the slash. Without it, a sibling folder whose name merely starts with the same text passes the check:
base=/srv/t161/docs
for p in /srv/t161/docs/readme.txt /srv/t161/docs-old/draft.txt /srv/t161/docs; do
[[ $p == "$base"* ]] && a=pass || a=fail
[[ $p == "$base"/* ]] && b=pass || b=fail
printf '%-30s "$base"*: %s "$base"/*: %s\n' "$p" "$a" "$b"
done
/srv/t161/docs/readme.txt "$base"*: pass "$base"/*: pass
/srv/t161/docs-old/draft.txt "$base"*: pass "$base"/*: fail
/srv/t161/docs "$base"*: pass "$base"/*: fail
The "$base"/* form also rejects the base folder itself, which matters for commands that would act on the whole folder. realpath --relative-base=DIR offers a related check: it prints a path relative to DIR only when the path is inside DIR and prints it unchanged (absolute) otherwise.
Checking What Kind of File It Is
A path that is inside the base folder can still be the wrong type of file. Before using it, test for what the operation needs (lessons 71 and 72):
[[ -f $target ]]for a regular file to read. This rejects folders, devices such as/dev/zeroand named pipes, which could make a reader block forever or read without end.[[ -d $target && ! -L $path ]]for a folder you are about to write into. Testing-Lon the unresolved path catches a folder that has been replaced by a symbolic link.- A size limit (
stat -c %s) before reading a file into memory or sending it somewhere.
Time of Check and Time of Use
Every check above looks at the file system at one moment, and the script then uses the path a moment later. If another user can change the folders in between, for example by replacing a checked file with a symbolic link, the check no longer describes what is used. This gap is called a TOCTOU (time-of-check to time-of-use) race.
Shell scripts cannot close this gap completely, but they can make it small and harmless:
- Keep the base folder writable only by the account that runs the script, so nobody else can plant links in it (see lesson 159).
- Create new files in a way that fails if the name already exists, instead of checking first and writing second. Bash's
set -C(noclobber) opens new files exclusively, andlnof a hard link fails if the target exists; both refuse a symbolic link planted under the target name. - Use the resolved path for the operation, not the original text, so the same location that was checked is the one that is used.
A Complete Example: A Document Store
docs.sh gives other programs, for example a small web handler, safe access to one base folder. get prints a document named by a relative path, put stores standard input under a new name in an inbox subfolder, and list lists the readable documents.
#!/usr/bin/env bash
# docs.sh: read and store documents inside one base folder
# usage: docs.sh get RELPATH print a document from the base folder
# docs.sh put NAME store standard input as inbox/NAME
# docs.sh list list readable documents
set -euo pipefail
export LC_ALL=C
readonly BASE=${DOCS_BASE:-/srv/t161/docs}
readonly MAX_BYTES=1048576 # 1 MiB limit for get and put
tmp='' # upload temp file, removed on exit
trap '[[ -n $tmp ]] && rm -f -- "$tmp"' EXIT
die() { printf '%s: %s\n' "${0##*/}" "$1" >&2; exit 2; }
base_real=$(realpath -e -- "$BASE") || die "base folder missing: $BASE"
# check_text VALUE: rules that apply to every user-supplied path or name
check_text() {
[[ -n $1 ]] || die 'empty path or name'
(( ${#1} <= 255 )) || die 'path or name longer than 255 bytes'
[[ $1 != *[[:cntrl:]]* ]] || die "control characters are not allowed: ${1@Q}"
}
# check_rel RELPATH: a relative path made of safe components
check_rel() {
local p=$1 part
local -a parts
check_text "$p"
[[ $p != /* ]] || die "absolute paths are not allowed: ${p@Q}"
IFS=/ read -r -a parts <<< "$p"
for part in "${parts[@]}"; do
[[ -n $part ]] || die "empty path component: ${p@Q}"
[[ $part != .* ]] || die "components must not start with a dot: ${p@Q}"
[[ $part =~ ^[A-Za-z0-9_][A-Za-z0-9._-]*$ ]] \
|| die "invalid characters in ${part@Q}"
done
}
# check_name NAME: a single file name, no folders
check_name() {
check_text "$1"
[[ $1 =~ ^[A-Za-z0-9_][A-Za-z0-9._-]*$ ]] \
|| die "invalid name ${1@Q}: use letters, digits, '.', '_' and '-', not starting with '.' or '-'"
(( ${#1} <= 100 )) || die 'name longer than 100 characters'
}
cmd_get() {
local rel=$1 target size
check_rel "$rel"
target=$(realpath -e -- "$base_real/$rel" 2>/dev/null) || die "no such document: ${rel@Q}"
[[ $target == "$base_real"/* ]] || die "refusing ${rel@Q}: resolves outside the base folder"
[[ -f $target ]] || die "not a regular file: ${rel@Q}"
size=$(stat -c %s -- "$target")
(( size <= MAX_BYTES )) || die "document too large: $size bytes"
cat -- "$target"
}
cmd_put() {
local name=$1 inbox size
check_name "$name"
inbox=$base_real/inbox
mkdir -p -- "$inbox"
[[ ! -L $inbox && -d $inbox ]] || die 'inbox is not a plain folder'
tmp=$(mktemp -- "$inbox/.upload.XXXXXX")
head -c "$((MAX_BYTES + 1))" > "$tmp"
size=$(stat -c %s -- "$tmp")
(( size <= MAX_BYTES )) || die "input larger than $MAX_BYTES bytes"
chmod 640 -- "$tmp"
# ln fails if the name already exists, so nothing is ever overwritten
ln -- "$tmp" "$inbox/$name" 2>/dev/null || die "already exists: inbox/$name"
printf 'stored inbox/%s (%d bytes)\n' "$name" "$size"
}
cmd_list() {
find "$base_real" -type f ! -path '*/.*' -printf '%P\n' | sort
}
(( $# >= 1 )) || die 'usage: docs.sh get RELPATH | put NAME | list'
case $1 in
get) (( $# == 2 )) || die 'usage: docs.sh get RELPATH'; cmd_get "$2" ;;
put) (( $# == 2 )) || die 'usage: docs.sh put NAME'; cmd_put "$2" ;;
list) (( $# == 1 )) || die 'usage: docs.sh list'; cmd_list ;;
*) die "unknown command: ${1@Q}" ;;
esac
How It Works
- One base folder.
BASEis resolved once withrealpath -eintobase_real, and every check compares against that resolved value. An environment variable can point the script at a test folder. - Shared text rules.
check_textrejects empty values, values longer than 255 bytes (withLC_ALL=C,${#1}counts bytes) and any control character.[[:cntrl:]]matches newline, tab, carriage return, the escape character and the other non-printing bytes. - Path rules for
get.check_relrejects absolute paths, empty components, components starting with a dot and components with characters outside the allowlist. Thenrealpath -eresolves the path, the containment test requires it to be strictly inside the base folder,-frequires a regular file and a size check limits what is printed. - Name rules for
put.check_nameallows only a single name, soputcan never write outsideinbox. The script also confirms thatinboxis a real folder and not a symbolic link. - No overwriting. Input goes into a hidden temporary file created by
mktempinsideinbox.head -creads at most one byte more than the limit, so an oversized upload is detected without reading it all.lnthen creates the final name as a hard link to the temporary file.lnfails if anything, including a planted symbolic link, already has that name, so existing files are never replaced. The EXIT trap removes the temporary name in every case. - Hidden files stay hidden.
listskips any path containing a component that starts with a dot, which also hides the temporary upload files, andfindwithout-Ldoes not follow symbolic links, soescape.txtis not listed.
The first version of this script declared tmp as a local variable inside cmd_put and set the trap there. The trap runs when the script exits, after cmd_put has returned and its local variables are gone, so every successful upload failed with tmp: unbound variable under set -u and left its temporary file behind. Declaring tmp at the top of the script fixed both problems. Variables used by an EXIT trap must still exist when the script ends.
Running the Complete Example
Reading documents, including every attempt to leave the base folder:
for a in 'guides/install.txt' 'readme.txt' '../other/secret.txt' 'guides/../../other/secret.txt' \
'/etc/passwd' 'guides/escape.txt' 'outside/secret.txt' '.env' '.git/config' \
'guides//install.txt' 'guides' 'missing.txt' '-n' "$(printf 'readme.txt\nx')" ''; do
printf '$ docs.sh get %q\n' "$a"; docs.sh get "$a"; echo "status $?"
done
$ docs.sh get guides/install.txt
Install steps
status 0
$ docs.sh get readme.txt
hello
status 0
$ docs.sh get ../other/secret.txt
docs.sh: components must not start with a dot: '../other/secret.txt'
status 2
$ docs.sh get guides/../../other/secret.txt
docs.sh: components must not start with a dot: 'guides/../../other/secret.txt'
status 2
$ docs.sh get /etc/passwd
docs.sh: absolute paths are not allowed: '/etc/passwd'
status 2
$ docs.sh get guides/escape.txt
docs.sh: refusing 'guides/escape.txt': resolves outside the base folder
status 2
$ docs.sh get outside/secret.txt
docs.sh: refusing 'outside/secret.txt': resolves outside the base folder
status 2
$ docs.sh get .env
docs.sh: components must not start with a dot: '.env'
status 2
$ docs.sh get .git/config
docs.sh: components must not start with a dot: '.git/config'
status 2
$ docs.sh get guides//install.txt
docs.sh: empty path component: 'guides//install.txt'
status 2
$ docs.sh get guides
docs.sh: not a regular file: 'guides'
status 2
$ docs.sh get missing.txt
docs.sh: no such document: 'missing.txt'
status 2
$ docs.sh get -n
docs.sh: invalid characters in '-n'
status 2
$ docs.sh get $'readme.txt\nx'
docs.sh: control characters are not allowed: $'readme.txt\nx'
status 2
$ docs.sh get ''
docs.sh: empty path or name
status 2
The .. paths, the absolute path and the hidden files were stopped by the text rules. The two symbolic links passed the text rules, because their names are ordinary, and were stopped by the containment check after realpath revealed where they lead. That is why both layers are needed.
Storing uploads:
echo "data for notes.txt" | docs.sh put notes.txt; echo "status $?"
echo "data for notes.txt" | docs.sh put notes.txt; echo "status $?"
echo "data for report-2026_11.md" | docs.sh put report-2026_11.md; echo "status $?"
head -c 2000000 /dev/zero | docs.sh put big.bin; echo "status $?"
ls -la docs/inbox
stored inbox/notes.txt (19 bytes)
status 0
docs.sh: already exists: inbox/notes.txt
status 2
stored inbox/report-2026_11.md (27 bytes)
status 0
docs.sh: input larger than 1048576 bytes
status 2
total 16
drwxr-xr-x 2 root root 4096 Nov 24 10:53 .
drwxr-xr-x 5 root root 4096 Nov 24 10:53 ..
-rw-r----- 1 root root 19 Nov 24 10:53 notes.txt
-rw-r----- 1 root root 27 Nov 24 10:53 report-2026_11.md
The second upload with the same name was refused instead of replacing the first, the oversized upload was refused, and no temporary files were left behind. Names such as ../evil.sh, .bashrc, -rf, a b.txt and sub/x.txt were all refused with the "invalid name" message.
Finally, an attacker who can replace the inbox folder with a symbolic link to another folder does not get a file written there, and listing shows only regular, non-hidden files inside the base folder:
echo x | docs.sh put planted.txt; echo "status $?" # inbox is now a symlink to ../other
docs.sh list
docs.sh: inbox is not a plain folder
status 2
guides/install.txt
inbox/notes.txt
inbox/report-2026_11.md
readme.txt
(The list output above was taken after the real inbox folder was restored.)