T09 · Insecure Skill Coding Practices
- Location
scripts/script.sh:139- Finding
Command Injection Through Unescaped Configuration Values
- 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" ``` ### Technical Analysis The configuration key and value originate directly from command-line arguments and are interpolated into a sed program without escaping or validation: ```bash sed -i "s|^${key}=.*|${key}=${val}|" "$cfg" ``` Shell quoting prevents a direct shell metacharacter injection at the initial command-parsing stage, but it does not prevent injection into the syntax interpreted by sed. An attacker can supply sed delimiters, regular-expression operators, additional sed commands, or GNU sed's `e` command. The `e` command executes an external command through a shell. A crafted value can terminate the intended substitution and append a new sed command that invokes arbitrary operating-system commands. The key is also used as an unescaped regular expression in both `grep` and `sed`, which can cause unintended matching or modification of unrelated configuration records. ### Attack Path 1. The attacker invokes the configuration command with a normal key and value so that the key exists in `config.txt`: ```bash scripts/script.sh config example initial ``` 2. The attacker invokes the command again with a value containing the sed delimiter and injected sed syntax. 3. The script detects that the key already exists and enters the updat ...[truncated 1031 chars]- Remediation
View remediation
&2 return 1 fi ``` 2. Do not construct executable sed programs from untrusted data. Rewrite the configuration file using a method that treats keys and values strictly as data, such as a small Python helper using exact string comparisons. 3. If a text-processing utility must be used, pass values through data variables rather than placing them directly in program source. Ensure the implementation performs literal comparisons and cannot evaluate supplied content. 4. Write updates to a securely created temporary file in the same directory, verify success, apply restrictive permissions, and atomically rename the file into place. 5. Add regression tests containing sed delimiters, backslashes, newlines, regular-expression syntax, and command-like payloads. Verify that these inputs are either safely stored as literal text or explicitly rejected. 6. Consider restricting configuration values to documented formats and maximum lengths instead of accepting arbitrary strings. ]]>
