T09 · Insecure Skill Coding Practices
- Location
scripts/script.sh:145- Finding
Arbitrary Command Execution Through Sed Expression Injection
- Content
View full analysis
Vulnerability Details
File Location:
scripts/script.sh, lines 145-149
Vulnerability Type: Command injection through dynamically constructed sed expression
Risk Level: HighVulnerable Code
bash 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"Technical Analysis
The
configcommand acceptskeyandvalas user-controlled command-line arguments. When an existing key is updated, both values are interpolated directly into a sed program.GNU sed supports the
esubstitution flag, which executes the substitution result using a shell. An attacker can include the sed delimiter and aneflag inval, terminating the intended replacement expression and enabling shell execution.For example, a value such as:
text ;id >/tmp/ppe-proof|ecauses the constructed sed expression for key
xto resemble:bash s|^x=.*|x=;id >/tmp/ppe-proof|eIf the expression matches an existing configuration line, GNU sed executes the generated replacement text through
/bin/sh. Quoting the shell variable expansion does not mitigate this issue because the injection occurs inside the syntax interpreted by sed, rather than during the caller's initial shell parsing.The key is also inserted into a grep regular expression and sed regular expression without validation, creating additional expression-injection and matching-integrity risks.
Attack Path
-
The attacker causes a configuration key to exist:
bash PPE_DIR=/tmp/ppe-test scripts/script.sh config x initial -
The attacker updates that key with a crafted value:
bash PPE_DIR=/tmp/ppe-test scripts/script.sh config x ';id >/tmp/ppe-proof|e' -
The script builds a sed substitution expression containing the injected delimiter and
eflag. -
The exi ...[truncated 832 chars]
-
- Remediation
View remediation
Remediation Suggestions
-
Do not construct sed programs by interpolating untrusted input.
-
Restrict configuration keys to a safe identifier format, for example:
bash if [[ ! "$key" =~ ^[A-Za-z_][A-Za-z0-9_]*$ ]]; then echo "Invalid configuration key" >&2 return 1 fi -
Rewrite the configuration through a securely created temporary file instead of dynamically modifying it with sed.
-
Pass data separately from program syntax, such as through environment variables or appropriately constrained
awk -vvariables. -
Reject line breaks and control characters in configuration values.
-
Create temporary files inside the data directory with
mktemp, apply restrictive permissions, and atomically replace the original file only after successful processing. -
Add regression tests using values containing
|, backslashes, newlines, semicolons, and sed flags to verify that they remain inert data.
-
