Use a subshell: (su -c 'psql -U postgres -c "<command>"' postgres) > file
Inside the subshell you can drop permissions to do your work, but output is redirected to your original shell which still has your original permissions.
The only bug I see with your code is that you're running the user's command unnecessarily through sh -c
when you should just run it directly. Running it through sh -c
buys you nothing but it destroys quoting that the user originally put into the command. For example, try this:
sudo /usr/local/sbin/_oob_shim ls -l "a b"
should list a file called a b
inside the context of the namespace but instead it lists two files called a
and b
.
sudo /usr/local/sbin/_oob_shim ls -l "*"
should list a file called *
(literal asterisk), fails for the same reason.
So it should look like this instead:
#!/bin/sh
/bin/ip netns exec oob \
/usr/bin/sudo -u "#$SUDO_UID" -g "#$SUDO_GID" -- "$@"
Makes the script simpler to boot!
Another point I can make is that although in this case the bug was just a functionality bug, not a security bug, one is always suspicious when auditing security-sensitive code and finding that it runs things through shells because that's almost always a problem.
Finally, the user's supplementary groups will not be propagated into the namespace (they get only their uid and main gid), but that doesn't seem like a huge problem and fixing that is not trivial.
Other than that, it looks good to me.
Best Answer
I can see two methods:
Allow the user to use
/sbin/iptables
throughsudo
without restriction (which is something dangerous, this means you trust the user somehow), and run the script with the permissions of the user. The script will invokesudo
each time/sbin/iptables
is needed. This is assuming the script execution will be quick, since some password input will eventually be required at regular intervals¹./sbin/iptables
without restriction is something dangerous.Allow the user to call only the script through
sudo
./sbin/iptables
is restricted by the script.About the problem you mentioned: if the script is owned by let's say
root
and has usual permissions:rwxr-xr-x
, others users cannot modify it, they can only execute it (eventually throughsudo
to obtain more privileges).With solution 2, and in the case of shell scripts (compared to more robust binaries/programs), beware of environment variables and the several external factors that can modify the execution of your script. Check that your sudo configuration resets properly the definition of every potentially harmful variable.
—
1. In fact,
sudo
can be configured withNOPASSWD
if needed.