T09 · Insecure Skill Coding Practices
- Location
book-reader.sh:154- Finding
Command Injection Through Unvalidated Arithmetic Input
- Content
View full analysis
Vulnerability Details
File Location:
book-reader.sh:154-155, 211-216
Vulnerability Type: Bash arithmetic expression injection
Risk Level: HighVulnerable code:
bash # Calculate chunk local chunk_size=$((pages * chars_per_page)) local end_offset=$((offset + chunk_size))The
pagesvalue reaches the arithmetic expression from command-line input without validation:bash read) pages=50 if [[ "$3" == "--pages" ]]; then pages="${4:-50}" fi read_book "${2:-}" "$pages" ;;Technical Analysis
The fourth command-line argument is assigned directly to
pagesand subsequently evaluated by Bash inside an arithmetic expansion:bash $((pages * chars_per_page))Bash recursively interprets variable values referenced in arithmetic contexts as arithmetic expressions. Arithmetic syntax can include variable and array references whose subscripts may cause additional shell expansion. Consequently, treating untrusted text as an arithmetic operand can allow crafted input containing command substitution to execute shell commands.
Quoting the assignment does not prevent this issue because the dangerous interpretation occurs later, when the value is processed by the arithmetic expansion. The implementation does not verify that
pagescontains only a bounded positive decimal integer.Attack Path
- An attacker obtains the ability to invoke
book-reader.shor influence arguments supplied by an Agent. - The attacker supplies an existing supported book file and a malicious value after
--pages. - The command dispatcher assigns that value directly to
pagesat line 214. read_bookreferencespagesin the arithmetic expansion at line 154.- Bash evaluates the attacker-controlled arithmetic expression, potentially executing embedded command substitution.
- The injected command runs with the same operating-system identity, environm ...[truncated 667 chars]
- An attacker obtains the ability to invoke
- Remediation
View remediation
Remediation Suggestions
Validate the page count before it reaches any arithmetic context:
bash if [[ ! "$pages" =~ ^[0-9]+$ ]]; then echo "Invalid page count: expected a positive integer" >&2 exit 1 fi if (( 10#$pages < 1 || 10#$pages > 1000 )); then echo "Invalid page count: allowed range is 1-1000" >&2 exit 1 fi pages=$((10#$pages))Apply equivalent validation to every value loaded from external state before using it in arithmetic. In particular:
- Accept only ASCII decimal digits.
- Enforce practical upper bounds to prevent excessive memory or processing consumption.
- Use the
10#prefix after validation to force decimal interpretation. - Reject malformed values rather than passing them to Bash arithmetic evaluation.
- Add tests with shell metacharacters, arithmetic variable references, array subscripts, negative values, and excessively large integers.
