1

Consider you have a Linux/UNIX machine with Bash. You have a file secret.txt that only root can read. You want to use a command that takes a string as an argument, say,

sample-command <string>

Log in as a root user and run the command using the first line of the text file:

root ~ $ sample-command $(sed '1!d' secret.txt)

Can this be done by non-root, sudoer users?

Note. sudo sh -c "<command>" doesn't help since subshells don't carry over the root/sudo privilege. For example,

sarah ~ $ sudo sh -c "echo $(whoami)"

gives you sarah, not root.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
Culip
  • 559
  • 8
  • 24
  • maybe try `sudo bash -pc command` to launch bash in privileged mode? Also what’s wrong with `$(sudo sed ...)` – nneonneo Jan 31 '20 at 19:47

1 Answers1

3

Expansions like command substitution will be processed by the shell before executing the actual command line:

sudo sh -c "echo $(whoami)"
foouser

Here the shell will first run whoami, as the current user, replace the expansion by it's result and then execute

sudo sh -c "echo foouser"

Expansions doesn't happen within single quotes:

sudo sh -c 'echo "$(whoami)"'
root

In this example $(whoami) won't get processed by calling shell because it appears within single quotes. $(whoami) will therefore get expanded by subshell before calling echo.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • In this case can you use single quotes in the command next to sh -c? For example, what would you do if you want to use single quotes in arg1 in ``sudo sh -c 'sample-commnd arg1 arg2 ...'`` ? – Culip Jan 31 '20 at 20:01
  • 1
    You would have to escape them, like `sudo sh -c 'command '\''arg1'\' ...'`. Probably it would be better to just create a shellscript, save it to a file and then run `sudo bash file.sh`. In that shellscript, since you are running it as root, you can just access the secrets.txt, without further tricks – hek2mgl Jan 31 '20 at 20:19
  • A side note on hek2mgl's comment above: To understand the ``'\''`` stuff go to https://unix.stackexchange.com/questions/30903/how-to-escape-quotes-in-shell and see kenorb's answer. – Culip Jan 31 '20 at 21:00
  • @Culip It's very good that you think about quoting, and not just omit it because it's painful here!! Doing this consequently will save you many headaches with shellscripting – hek2mgl Jan 31 '20 at 21:01