0

My goal is to write in /etc/passwd to escalate privileges to root.

i generated password "test1" for the new root user : openssl passwd test1 and i use echo to append a new entry in /etc/passwd file : sudo echo "root2:rmeF3kdnoRw/U:0:0:root:/root:/bin/bash" >> /etc/passwd

But when i do this last command it show me that i don't have the permission to do this : bash: /etc/passwd: Permission denied

but when i use the command sudo nano /etc/passwd and copy root2:rmeF3kdnoRw/U:0:0:root:/root:/bin/bash in the end of the file it works !

What is the problem with the echo command ?

4

1 Answer 1

1

Already answered through the comments, but to expand a bit:

sudo echo "root2:rmeF3kdnoRw/U:0:0:root:/root:/bin/bash" >> /etc/passwd

translates to the following:

  1. Instruct bash (which is not elevated) to open the file /etc/passwd for writing
  2. Instruct bash (still not elevated) to run the command sudo with some arguments, and use the file descriptor from step 1 as stdout
    1. Instruct sudo (which is setuid root) to run the command echo with some arguments
      1. Instruct echo (running as root, and note this is likely to be something like /usr/bin/echo whereas normally echo will invoke a shell builtin), and inheriting stdout from sudo) to output some text to stdout
      2. Its job done, echo exits
    2. Its job done, sudo exits; nothing is left running as root
  3. Bash (still not elevated) closes the file descriptor to /etc/passwd (flushing the write queue)
  4. Bash waits for the next command

Except, of course, step 1 fails! Bash, not being elevated, can't open /etc/passwd for write. Thus, bash: /etc/passwd: Permission denied No part of steps 2 or 3 happens, including any of the sub-steps of step 2.

sudo nano /etc/passwd works just fine, because the elevated process (nano, which inherits root privileges from sudo) is the one that opens the file for writing.

If you wanted to use echo here, you would need bash itself to be elevated. This could be done by explicitly invoking bash (or any other shell) within sudo and then telling it what to do:
sudo bash -c 'echo "root2:rmeF3kdnoRw/U:0:0:root:/root:/bin/bash" >> /etc/passwd'
or equivalently as three separate commands (the latter two of which are given to the elevated instance of bash):
sudo bash echo "root2:rmeF3kdnoRw/U:0:0:root:/root:/bin/bash" >> /etc/passwd exit

You must log in to answer this question.