分类: LINUX
2007-09-27 16:18:19
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 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.
$ sudo sh -c 'echo "1" > /proc/sys/net/ipv4/ip_forward'或
$ sudo bash
# sudo echo "1" > /proc/sys/net/ipv4/ip_forward
我经过试验是可以成功的,但是还是有些疑惑,为什么shell-builtin就不起作用了呢?sudo它本质上是个什么机制?
渴望各位的解答:-)