Can't write to /etc/shadow with "echo" but with "nano" i can
Solution 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:
- Instruct bash (which is not elevated) to open the file /etc/passwd for writing
- Instruct bash (still not elevated) to run the command
sudo
with some arguments, and use the file descriptor from step 1 as stdout- Instruct sudo (which is setuid root) to run the command
echo
with some arguments- 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 - Its job done, echo exits
- Instruct echo (running as root, and note this is likely to be something like /usr/bin/echo whereas normally
- Its job done, sudo exits; nothing is left running as root
- Instruct sudo (which is setuid root) to run the command
- Bash (still not elevated) closes the file descriptor to /etc/passwd (flushing the write queue)
- 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