Skip to content
shellhacks.dev
Security

Use double dash before user input

Put -- before a variable that holds a file name, so a value such as -rf or -v is read as an operand and not as an option. It closes option injection.

1 min read
Summarize in AI

A script passes a name from a user or a directory listing to ls or rm, and a file called -A turns into an option.

Shell
touch ./-A ./normal.txt
f=-A
ls "$f"
echo ---
ls -- "$f"
rm -- "$f"
echo ---
ls
Text
-A
main.sh
normal.txt
---
-A
---
main.sh
normal.txt

Quoting stops word splitting but not option parsing, so ls "-A" is still the -A option and lists every entry instead of the one file. The -- argument marks the end of options in the POSIX utility conventions, and everything after it is an operand. The second listing shows only the file, and rm -- then removes it, which a bare rm -A could not do since it is not an option of rm.

Not every program honors --, and some, like echo, print it. For those, prefix relative paths with ./ so the name cannot begin with a dash. A glob like * is safe in a directory listing only when the expansion starts with ./*.

Share

More snippets

Security

Avoid predictable temp names

Never build a temp file name from $$ or a fixed string. An attacker who guesses it can plant a symlink, and mktemp picks an unused random name with mode 600.

1 min read
Security

Avoid eval on input

Never pass input to eval. Run a command held in an array as "${cmd[@]}", or escape a value with printf %q when eval cannot be avoided.

1 min read
Security

Validate input with a whitelist

Validate input against a list of allowed values with a case statement. A grep check with ^ and $ can be fooled by a value that holds a newline.

1 min read

Get new posts by email

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

Unsubscribe in one click. No spam, ever.