Do not inject data into shell code strings (sh -c)

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

Metadata

ID: bash-security/dont-inject-data-into-shell-code-strings

Language: Bash

Severity: Error

Category: Security

CWE: 78

Description

The script argument to sh -c is run by a new shell. If that argument is double-quoted and contains parameter expansion ($var, ${var}), the outer shell substitutes values into the string before the inner shell parses it, which can turn filenames or other input into command injection (CWE-78).

Prefer passing data as operands after the script (e.g. sh -c 'cmd "$1"' _ "$path") or a single-quoted script so the outer shell does not expand into the -c text.

Non-Compliant Code Examples

#!/bin/bash
sh -c "rm $file"
/bin/sh -c "touch ${path}"
sh -c "install $pkg in /opt"
bash -c "run $cmd"
/usr/bin/zsh -c "cp ${src} dest"

Compliant Code Examples

#!/bin/bash
sh -c 'echo hello'
sh -c "echo hello"
sh -c 'rm -- "$1"' _ "$filepath"
sh -c "$(curl -fsSL https://example.com/install.sh)"
sh -c "wc $(cat list.txt)"
sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
bash -c 'echo $1' _ "$safe"
zsh -c "echo ok"
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