Bind to ports less than 1024 without root access

Solution 1:

Of course this is possible. You only need to give the binary CAP_NET_BIND_SERVICE.

sudo setcap cap_net_bind_service=ep some-binary

In Linux, the things root can do have been broken up into a set of capabilities. CAP_NET_BIND_SERVICE is the ability to bind to ports <= 1024.

It's probably even possible to use AppArmor, SELinux, or another Linux security module (LSM) to grant the program access to bind that one port specifically, but I think this would be a waste of time. Security is not really based on port numbers to the degree it was in the distant past.

Here's a script for OSX to forward ports 80 and 443 to unprivileged ports:

echo " 
rdr pass inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080
rdr pass inet proto tcp from any to any port 443 -> 127.0.0.1 port 8443
" | sudo pfctl -ef -

Solution 2:

Another way of getting your daemon to respond to requests from a lower port number is to use iptables or similar to redirect a lower numbered port to the higher numbered port that your daemon is listening on:

sudo iptables -A PREROUTING -t nat -p tcp --dport 80 -j REDIRECT --to-port 8080

Substitute 80 with the port to expose, and 8080 with your application listener port.


Solution 3:

I think there is a way to do it but im not 100% sure if this would work.

its the binding of the port that requires root, not the application's using it, so the below method may work but you need to have sudo access in the first place.

First you start your process as root user using sudo myApp, once the port has been bound you can switch the owner of the process to a non-privileged user.


Solution 4:

I dimly remember a library called "authbind" that does what you need, by wrapping the bind() system call (via a LD_PRELOAD library), and, if a privileged port is requested, spawning a setuid root program that receives a copy of the file descriptor, then verifies the application is indeed permitted to bind to the port, performs the bind() and exits.

Not sure about the project status, but the method should be fairly straightforward to (re)implement if required.

Tags:

Linux

Port

Bind