T09 · Insecure Skill Coding Practices
- Location
scripts/script.sh:136- Finding
Arbitrary Command Execution Through GNU sed Configuration Injection
- Content
View full analysis
Vulnerability Details
File Location:
scripts/script.sh, lines 136-150
Vulnerability Type: Shell command execution through an attacker-controlledsedprogram
Risk Level: HighVulnerable Code
bash cmd_config() { local key="${1:-}" val="${2:-}" local cfg="$DATA_DIR/config.txt" if [ -z "$key" ]; then echo "=== Config ===" if [ -f "$cfg" ]; then while IFS="=" read -r k v; do echo " $k=$v"; done < "$cfg" else echo " (empty — use config <key> <value>)"; fi elif [ -z "$val" ]; then grep "^${key}=" "$cfg" 2>/dev/null | cut -d= -f2- || echo "(not set)" else if [ -f "$cfg" ] && grep -q "^${key}=" "$cfg" 2>/dev/null; then sed -i "s|^${key}=.*|${key}=${val}|" "$cfg" else echo "${key}=${val}" >> "$cfg" fi echo "Set: $key=$val" fi }Technical Analysis
The configuration key and value are interpolated directly into a GNU
sedexpression. Neither value is escaped for the regular-expression, replacement-string, or command-delimiter contexts.On GNU
sed, an attacker can terminate the replacement expression with the|delimiter and append theeflag. Theeflag executes the resulting replacement text as a shell command. Because the generated replacement starts withkey=, a value beginning with a semicolon can terminate that assignment and introduce a second command.The same unsafe interpolation also permits regular-expression injection, replacement metacharacter injection, and unintended modification of configuration records.
Attack Path
- Create a configuration entry so that the vulnerable update branch is reached:
bash scripts/script.sh config foo safe- Update the existing key with a crafted value:
bash scripts/script.sh config foo ';touch /tmp/turbine-pwned|e'- The script constructs an expression equivalent to:
bash sed -i 's|^foo=.*|foo ...[truncated 906 chars]- Remediation
View remediation
Remediation Suggestions
- Do not construct a
sedprogram by interpolating untrusted keys or values. - Restrict configuration keys to a strict allowlist, such as:
bash [[ "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]] || { echo "Invalid configuration key" >&2 return 1 }- Replace the record using a safe temporary-file workflow in which the value is handled as data rather than executable syntax.
- Prefer a structured configuration format and serializer, such as JSON manipulated with
jq. - Create temporary files with
mktempinside the protected data directory, verify every operation, and atomically rename the completed file. - Add regression tests using values containing
|,;,&, backslashes, newlines, andsedflags. - If
sedmust be retained, escape all regular-expression and replacement metacharacters and reject line breaks. Escaping alone is less robust than replacing the implementation.
- Do not construct a
