Rocking the blogosphere
Apple Online Store

Su su sudo: oh no

The other day I wanted to enable IP forwarding on my Linux box (so that it could forward packets from a tun virtual interface being used by VTun to the physical interface connected to my home network).

I looked up it up and it turns out that it’s a simple setting in a file in the /proc filesystem, so I did what seemed obvious and logical at the time:

marca:~$ sudo echo "1" > /proc/sys/net/ipv4/ip_forward
-bash: /proc/sys/net/ipv4/ip_forward: Permission denied

I took this to mean that my kernel was not compiled with ip_forward support and then wasted a bunch of time building a new kernel.

Finally, it dawned on me. Duh. The echo command is a shell built-in so sudo has no effect.

I didn’t need a new kernel. All I had to do was:

marc:~$ sudo bash
root:~# sudo echo "1" > /proc/sys/net/ipv4/ip_forward
root:~# cat /proc/sys/net/ipv4/ip_forward
1

or even:

marc:~$ sudo sh -c 'echo "1" > /proc/sys/net/ipv4/ip_forward'

Sigh.

I thought of the idea of preventing this in the future by defining a bash function that detects builtins:

function sudo()
{
    if [ $(type -t "$1") == "builtin" ]; then
        echo "sudo bash function: ERROR - \"$1\" is a shell builtin" 1>&2
        return 1
    fi

    command sudo "$@"
}

which works for some cases but unfortunately doesn’t help for the case above, because the redirection permissions are checked before the function is executed. Sigh.

Del.icio.us Digg Reddit Technorati

Possibly related posts

Comments

  1. Jan
    May 18th, 2006 | 3:03 am

    I think the problem is not that echo is a shell builtin but rather that the file you’re trying to redirect to is being opend by the shell before the sudo is executed and therefore the command fails because user “marc” doesn’t have write permissions on the file.

    sudo /bin/echo 1 > /root/test

    doesn’t work either while

    sudo sh -c “/bin/echo 1 > /root/test”

    does as you have already noted.

  2. June 21st, 2006 | 3:17 am

    Good work man..it really helped

  3. January 4th, 2007 | 12:41 am

    the problem in this is not of builtin as echo is also a program

    $which echo
    /bin/echo

    but doing something like fails as ‘cd’ is only a builtin
    $sudo cd /root
    sudo: cd: command not found

  4. Denny
    September 19th, 2007 | 5:44 am

    Your post really helped me. Thanks!

  5. September 27th, 2007 | 1:20 am

    thanks a lot

    but I still mazing about it?why shell-builtin cmd can not work with sudo?Is there any else?

Leave a reply

Apple Online Store
Apple Online Store