[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Arithmetic + array allows for code injection
From: |
Greg Wooledge |
Subject: |
Re: Arithmetic + array allows for code injection |
Date: |
Mon, 2 Jun 2014 08:21:47 -0400 |
User-agent: |
Mutt/1.4.2.3i |
On Fri, May 30, 2014 at 09:28:13PM -0500, Dan Douglas wrote:
> The problem is most people don't realize how "variables" are evaluated.
> Any time the shell needs to reference a variable, it takes a string
> like: "arr[$foo]" and, if there's an index, the string within the index
> gets processed for expansions. The arithmetic evaluator is no exception.
I'm trying to understand this, but it's not clear to me yet.
imadev:~$ x='$(date)'
imadev:~$ : $(($x))
bash: $(date): syntax error: operand expected (error token is "$(date)")
That looks OK.
imadev:~$ : $((a[$x]))
bash: Mon Jun 2 08:06:39 EDT 2014: syntax error in expression (error token is
"Jun 2 08:06:39 EDT 2014")
There's the code-injection problem that started the thread.
imadev:~$ : ${a[$x]}
bash: $(date): syntax error: operand expected (error token is "$(date)")
That also looks OK.
Why is there no code injection in the last example? There is an index.
According to your paragraph, "... the string within the index gets
processed for expansions. The arithmetic evaluator is no exception."
If that's true, then I would have expected both the second and third
examples to behave the same way.
> The correct way to write such a thing is to let the variable evaluation
> expand the parameter from the arithmetic evaluator:
>
> $ bash -c 'typeset -A a; i=\" a[$i]=1+1; echo "$((a[\$i]))"'
> 2
> $ ksh -c 'typeset -A a; i=\" a[$i]=1+1; echo "$((a[\$i]))"'
> 2
> $ zsh -c 'typeset -A a; i=\" a[$i]=1+1; echo "$((a[\$i]))"'
> 2
So you're saying that instead of $((a[$x])) one should use $((a[\$x])) ?
imadev:~$ declare -A a
imadev:~$ x='$(date >&2)'
imadev:~$ a[$x]=5
imadev:~$ echo $((1+a[$x]))
Mon Jun 2 08:19:12 EDT 2014
bash: a: bad array subscript
1
imadev:~$ echo $((1+a[\$x]))
6
imadev:~$ echo "1+${a[$x]}"
1+5
imadev:~$ echo "1+${a[\$x]}"
1+
I still don't understand. But it seems clear that putting the indexed
parameter expansion inside $((...)) changes things. In some mysterious
way.
- Re: Arithmetic + array allows for code injection,
Greg Wooledge <=