Skip to content
shellhacks.dev
Security

Reject a leading dash in user input

Reject a value that starts with a dash before passing it on, using case $x in -*). It is the fallback for tools that do not accept a double dash.

1 min read
Summarize in AI

A function takes a file name from its caller, and a value such as -rf must not reach the program that gets it.

Shell
safe_name() {
  case $1 in
    -*) echo "refused: $1 starts with a dash" >&2; return 1 ;;
    '') echo "refused: empty" >&2; return 1 ;;
  esac
  printf 'ok: %s\n' "$1"
}
safe_name report.txt
safe_name -rf
safe_name ""
safe_name ./-rf
Text
ok: report.txt
refused: -rf starts with a dash
refused: empty
ok: ./-rf

The case pattern -* matches any value that begins with a hyphen, so the function refuses it before the value reaches a command. The same check is spelled [[ $1 == -* ]] in Bash, and the case form works in any POSIX shell, as defined in the shell command language. The fourth call shows the escape hatch: a relative path with ./ in front is accepted, because it cannot be an option.

Rejecting is a policy, so the caller loses the ability to use a file that really starts with a dash. Prefer -- where the tool supports it and keep this check for the tools that do not. A check on the first character does nothing about other dangers in a name, like a newline or .. components.

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.