Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Good catch. Another way that would work in Linux at least:

sudo $(echo 127.0.0.1 oscp.apple.com >> /etc/hosts)



Your first choice to edit a config file should be: sudo --edit pathname

This trick has the same problem, $() has to be evaluated before sudo sees anything.

I see so many people flailing about here, and I've done it myself. So let's consider why these tricks don't work.

sudo is an ordinary command that accepts an environment, a series of words, and whatever filehandles it inherits.

Read /etc/sudoers to note that it's then munging its environment per the env_reset and env_keep directives.

man sudo notes that it's closing non-standard filehandles, by default.

And, by design, sudo doesn't want you to do clever tricks because it's trying to stop you from hacking the Internets.

Let's also look at what a shell is doing. All a shell really does is munge some environment vars, set up redirections, and ultimately fork itself and run commands.

All the redirection, command substitution, process substitution, etc. must take place either before or after the shell forks to run sudo. All the shell can provide to sudo is command line arguments, environment variables, and usually stdin.

All the shell can get from sudo is going to be a return code, and whatever it can capture from the stdout and stderr.

The 'echo foo | sudo tee -a path > /dev/null' trick works because we redirect stdin, and we delegate opening the file for append to the 'tee' command, which has now been run as the privileged user by sudo, and we ignore the stdout.

Likewise, if you want to read a privileged file, var=$(sudo cat foo) will work, because you get sudo's stdout.

You can try sudo sh -c 'arbitrary shell script', but it's not good general advice as shells are often banned as a security precaution.

Also, if you get curious and want to edit sudoers without locking yourself out by corrupting it, use 'visudo'. Note that it won't prevent you from locking yourself out by removing your own permissions! RTFM, take some notes, and experiment on a machine you have a root account on or can log in via single-user mode.


With all due respect, threads like this are why, despite the philosophical appeal of giving owners control of their machines, putting some hurdles in their way makes sense in practice...




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: