T09 · Insecure Skill Coding Practices
- Location
scripts/script.sh:136- Finding
Arbitrary Command Execution Through Configuration Arguments
- 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` arguments are embedded directly into a GNU sed substitution expression. They are not validated or escaped for use as regular-expression, replacement, delimiter, or sed-command content. An attacker can place a crafted key in the configuration file and then supply a value containing the `|` delimiter and GNU sed's `e` flag. The resulting sed expression can cause the substituted line to be passed to `/bin/sh` for execution. The same unescaped key is also used as a regular expression in `grep`, but the command-execution consequence in the sed update path is the primary security issue. ### Attack Path One concrete exploitation sequence is: 1. Add a configuration entry whose key begins with a shell command and then introduces a shell comment: ```bash scripts/script.sh config 'id #' seed ``` This creates: ```text id #=seed ``` 2. Update that key with a value that terminates the replacement section and adds GNU sed's execution flag: ```bash scripts/script.sh config 'id #' 'x|e' ``` 3. The script constr ...[truncated 962 chars]- Remediation
View remediation
&2 return 1 fi ``` 2. Do not generate sed programs using untrusted input. Rewrite the configuration through a securely created temporary file using fixed field-comparison logic, then atomically rename it. 3. If sed must be retained, rigorously escape regular-expression metacharacters in the key and replacement metacharacters and delimiters in both the key and value. This is less robust than avoiding dynamic sed expressions. 4. Store configuration in a structured format and use a parser or serializer that treats keys and values exclusively as data. 5. Add regression tests containing sed delimiters, backslashes, newlines, regular-expression metacharacters, and strings resembling sed flags. ]]>
