T09 · Insecure Skill Coding Practices
- Location
scripts/script.sh:132- Finding
Arbitrary Command Execution Through GNU sed Script Injection
- Content
View full analysis
)"; 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 `key` and `val` command-line arguments are interpolated directly into a GNU sed program: ```bash sed -i "s|^${key}=.*|${key}=${val}|" "$cfg" ``` Shell quoting prevents an immediate shell expansion of metacharacters, but it does not make untrusted content safe as sed syntax. An attacker can supply the `|` delimiter, newline characters, backreferences, regular-expression syntax, or additional sed commands. In particular, GNU sed supports the `e` command, which executes a shell command. A multiline value can terminate the intended substitution and inject a separate `e` instruction. The vulnerable branch is reached when the selected key already exists in `config.txt`. The key is also embedded in the regular expressions used by `grep` and sed without validation or escaping. This permits unintended matching and configuration-file corruption in addition to command execution. ### Attack Path 1. The attacker invokes the configuration command with a normal key and value so that an existing configuration record is created: ```bash scripts/script.sh config target initial ...[truncated 1161 chars]- Remediation
View remediation
&2 return 1 } ``` - Reject newline, carriage-return, and NUL-like control content in configuration values unless such content is explicitly required. - Replace the dynamic sed operation with a safe configuration writer that treats keys and values as data rather than executable syntax. - Prefer a structured format such as JSON and update it with a dedicated parser such as `jq`. - If a plain key-value file must be retained, rewrite it using a parser that performs exact string comparisons and safely encodes values. - Write updates to a securely created temporary file in the same directory, verify success, set restrictive permissions, and atomically rename it over the original file. - Add regression tests containing sed delimiters, backslashes, newlines, regular-expression characters, and strings resembling GNU sed commands. ]]>
