Guard rm when unset variable expands to filesystem root path

This product is not supported for your selected Datadog site. ().

Metadata

ID: bash-security/guard-rm-rf-variable-paths

Language: Bash

Severity: Error

Category: Security

CWE: 73

Description

A pattern like rm -rf "$DIR/"* deletes files under $DIR. If $DIR is empty, the quoted part becomes nothing and the glob can expand from the filesystem root, with catastrophic effect.

Use a form that fails when the variable is unset or empty, for example rm -rf "${DIR:?}/"*, or assign and validate the path before running rm.

Non-Compliant Code Examples

#!/bin/bash
rm -r -f "$STEAMROOT/"*
rm -rf "$STEAMROOT/"*
rm "$STEAMROOT/"*
rm -rf "${build}/"*

Compliant Code Examples

#!/bin/bash
rm -rf "${STEAMROOT:?}/"*
rm -rf /tmp/safe
rm -rf "$HOME/dir"
rm "$HOME/dir"
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security