T09 · Insecure Skill Coding Practices
- Location
scripts/script.sh:145- Finding
Arbitrary Command Execution Through Sed Expression Injection
- Content
View full analysis
/dev/null; then sed -i "s|^${key}=.*|${key}=${val}|" "$cfg" else echo "${key}=${val}" >> "$cfg" fi ``` ### Technical Analysis The `config` command embeds the user-controlled `key` and `val` arguments directly into a GNU `sed` program. Neither value is escaped for use as a regular expression, replacement string, or sed command. An attacker can place the `|` delimiter in `val` to terminate the replacement and append GNU sed's `e` flag. The `e` flag executes the substituted line through a shell. Although the replacement starts with `${key}=`, shell command substitution inside the resulting assignment is still evaluated. For example, a value resembling the following produces a sed expression with the `e` execution flag: ```text $(touch /tmp/mining-pwned)|e ``` For a key named `target`, the resulting expression is equivalent to: ```bash sed -i 's|^target=.*|target=$(touch /tmp/mining-pwned)|e' config.txt ``` When a matching line exists, GNU sed executes the replacement through `/bin/sh`, and the command substitution invokes `touch`. The unescaped `key` is also interpreted as regular-expression and sed syntax, expanding the injection surface. ### Attack Path 1. The attacker or an Agent acting on attacker-controlled input creates a configuration key: ```bash scripts/script.sh config target initial ``` 2. This creates a matching `target=initial` record in `config.txt`. 3. The attacker updates that key with a malicious value containing a sed delimiter and the GNU sed `e` flag: ```bash scripts/script.sh config target '$(touch /tmp/mining-pwned)|e' ``` 4. The generated sed program matches the existing record and executes the substituted value through a shell ...[truncated 723 chars]- Remediation
View remediation
&2 return 1 } ``` - Rewrite the configuration using a parser that treats keys and values strictly as data. Pass values separately rather than embedding them into executable syntax. - Write updates to a securely created temporary file in the same directory, verify success, and atomically rename the file. - If sed must be retained, escape every regular-expression and replacement metacharacter and explicitly reject delimiters, newlines, and control characters. Avoid GNU sed's `e` functionality entirely. - Add regression tests using values containing `|`, `&`, backslashes, newlines, `$()`, backticks, and sed flags. ]]>
