Privileged SSH Port Forwarding with Sudo

There are many articles about privileged SSH port forwarding but not much about properly using SSH keys and config files.

The problem is that upon typing:

ssh dakara -L 80:localhost:80

the response is:

Privileged ports can only be forwarded by root.

The obvious solution is to just use sudo:

sudo ssh dakara -L 80:localhost:80

but this produces:

ssh: Could not resolve hostname dakara: Name or service not known

Unfortunately, “dakara” is a host configured in ~/.ssh/config and not available to root. This can be fixed with:

sudo ssh -F ~/.ssh/config dakara -L 80:localhost:80

but this tries to connect as root and prompts for a password. Adding “-l $USER” sets the user name to my user name (This could also be set in the SSH config file.), and adding “-E” to sudo preserves the environment allowing my SSH agent to be used.

sudo -E ssh -F ~/.ssh/config -l $USER dakara -L 80:localhost:80

Now everything connects, and I am not prompted for a password.

5 thoughts on “Privileged SSH Port Forwarding with Sudo”

  1. Thanks! just what I needed.
    After adding the “-E” option I can omit the “-l $USER” and still be able to connect using my agent.

  2. If you put the port forwarding info in ~/.ssh/config, you can get your command as short as this (well I could).

    sudo ssh -F ~/.ssh/config dakara

  3. Hello. I want to forward remote port to a local privileged one. How to do that as user in system over which i have full control?

    Now i use:
    su – login -c ‘ssh -f [email protected].5 -p 1234 -L 8587: -N’
    User have passwordless connection to ssh, but it can’t bind to privileged ports like 587 (instead of8587).

  4. @vitaly, if I understand your command correctly, you’re using su to login in as user “login”. Since that’s not root, you wouldn’t be able to bind to a privileged port.

Leave a Reply

Your email address will not be published. Required fields are marked *