[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Code Execution in Mathematical Context

From: Greg Wooledge
Subject: Re: Code Execution in Mathematical Context
Date: Tue, 4 Jun 2019 09:24:27 -0400
User-agent: Mutt/1.10.1 (2018-07-13)

On Tue, Jun 04, 2019 at 01:42:40PM +0200, Nils Emmerich wrote:
> Configuration Information [Automatically generated, do not change]:
> Machine: x86_64
> OS: linux-gnu
> Compiler: gcc
> Compilation CFLAGS: -g -O2 -Wno-parentheses -Wno-format-security
> uname output: Linux VirtualBox 4.18.0-20-generic #21~18.04.1-Ubuntu SMP $
> Machine Type: x86_64-pc-linux-gnu
> Bash Version: 5.0
> Patch Level: 0
> Release Status: release
> Description:
>         It is possible to get code execution via a user supplied variable in
> the mathematical context.
>         I don't know if this is considered a bug or not, but if not, I think
> people should be made aware that the mathematical context is unsafe.

It's a known behavior.  There are some workarounds, but it would help
if we could see what you're currently doing.

The first workaround is: with scalar variables, use the variable name
without a $ prefix.  This forces the variable's contents to be interpreted
by the math context instead of the regular shell context.

For example:  x=$((y + 7))   rather than   x=$(($y + 7))
The latter expands whatever is in y, even if it's not a valid math
expression.  Introducing random junk at that level can lead to surprises
when that junk hits the math context.

The second workaround is: with array variables, generally single-quote
things even when they feel redundant.

For example:  (( 'a[i]++' ))   or   let 'a[i]++'
Without quotes in the latter, there is a potential globbing issue (it
could match a file named ai++ in the current directory, or it could be
removed as a non-matching glob if nullglob is on).

Without quotes in the former, something bad happens, but I can't remember
the details off the top of my head.

It's even worse if you use the $ prefix on the index variable inside the
array's square brackets.

For example:

wooledg:~$ a=(foo bar baz)
wooledg:~$ i='$(date >&2)'
wooledg:~$ echo $(( a[$i] ))
Tue 04 Jun 2019 09:23:28 AM EDT

With single quotes around the expression, at least the command substitution
isn't performed.

wooledg:~$ echo $(( 'a[$i]' ))
bash: 'a[$(date >&2)]' : syntax error: operand expected (error token is 
"'a[$(date >&2)]' ")

So, as with most shell issues, it ultimately comes down to "Use More Quotes".

reply via email to

[Prev in Thread] Current Thread [Next in Thread]