Search code examples
bashcode-injection

Bash injection from variable


I have the piece of code working on very remote server

ID=555
SLEEP_TIME=`ssh user@192.168.1.1 "cat /tmp/$ID.sleep; date >> /tmp/$ID.log"`
echo SLEEP_TIME $SLEEP_TIME
sleep $SLEEP_TIME

Yes, no quotes around $SLEEP_TIME. ssh user@192.168.1.1 works fine, without a password, by key. I see /tmp/555.log refreshing. Sorry I've lost control on this remote server (on which above code is running by cron) making mistake in sshd config. But I control server 192.168.1.1 and I can place whatever into /tmp/555.sleep = $SLEEP_TIME variable How can I inject some code to $SLEEP_TIME variable forcing remote server to exec it?

This is 100% legal. Both servers belongs to my company. Please save me! Indeed, I lost control on remote server becouse I used complex trick with port forwarding to access it, as it's IP is NATed few times.


Solution

  • How can I inject some code to $SLEEP_TIME variable forcing remote server to exec it?

    You can't. Shell expansion happens once per command. Shell expansion does shell parameter expansion or command substitution. It happens at the same time. You can't do both. You can't expand a variable first and then expand it the second time to run a command substitution, because that's two expansions. From here.

    (One could argue that redirections happen after shell expansion in bash per this, but a simple test shows this is not true. Wonder if this is on purpose. But the Bash manual wasn't written for language layers. That's why it's a 'manual', not a 'specification'.)

    Quoting is used to prohibit word splitting. The only thing you can do is to make your script error by passing unparsable argument to sleep or passing two or more arguments to sleep.

    Also please don't use backticks ` ` for command substitution. They are deprecated, can't be nested, unreadable and look ugly. Use $(...).