T09 · Insecure Skill Coding Practices
- Location
scripts/script.sh:139- Finding
Arbitrary Command Execution Through GNU sed Expression 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 inserted directly into a GNU sed program without escaping or validation: ```bash sed -i "s|^${key}=.*|${key}=${val}|" "$cfg" ``` Because these values may contain sed delimiters, newlines, regular-expression operators, and command flags, an attacker can alter the structure of the generated sed script. GNU sed supports the `e` substitution flag, which executes the resulting pattern space through a shell. A malicious multiline value can terminate the intended substitution, add the `e` flag, and comment out or neutralize the remaining generated syntax. Command substitution embedded in the replacement text is then evaluated by the shell invoked by GNU sed. The lookup operations are also affected by regular-expression injection because `key` is interpolated into `grep` patterns without being treated as a fixed string. ### Attack Path 1. The attacker invokes the configuration command with a benign key and value to ensure that the key exists in `config.txt`. 2. The attacker invokes the command again for that ...[truncated 1198 chars]- Remediation
View remediation
&2 return 1 fi ``` 3. Define and enforce an allowlist of supported configuration keys rather than accepting arbitrary names. 4. Do not permit embedded control characters or newlines in values unless the storage format explicitly supports and safely encodes them. 5. If sed must be retained, escape pattern and replacement metacharacters separately. This is less robust than avoiding dynamic sed expressions entirely. 6. Write updates to a securely created temporary file in the same directory and atomically rename it over the original file. 7. Use fixed-string matching where regular expressions are not required, such as `grep -F`, while ensuring complete key/value boundary checks. ]]>
