Git through SSH Tunnel as Proxy
Posted on In Linux, Network, Programming, Software, Tutorialgit is a great tool and it is common to have a git server over SSH possibly managed by gitolite. However, there are situations that we can not directly connect to the git server but be able to SSH to another node that can connect to the git server. The git server may allow only internal connections because of security. With the node that we can SSH to, we can still use the git server “directly” by setting up a SSH tunnel as a proxy for the git connection.
As an example, we are connecting to the git server server.example.com through SSH tunnel to proxy.example.com as a proxy from laptop.example.com as follows:
laptop ----> proxy ----> server
The method are similar to the one in https://www.systutorials.com/directly-ssh-to-hosts-with-lan-ips-through-the-gateway/ by using multi-hop SSH connections. Hence, the method only works if your git server uses SSH protocol for connection and authentication. If the git server uses other protocol, other methods based on https://www.systutorials.com/proxy-using-ssh-tunnel/ are possible which are not the focus of this post.
Here is how to set up the mechanism with two steps.
First, make sure that you can SSH to proxy.example.org password-less to make the life much easier. Please check https://www.systutorials.com/enabling-password-less-ssh-login/ for how to enable password-less SSH login.
Then, most importantly, add this to your ~/.ssh/config
on laptop:
Host server.example.com
ProxyCommand ssh -q proxy.example.org nc %h %p
By this, when we connect to the server by git push
, git pull
or other commands, git will first SSH to server.example.com. As the ssh client will check the config file, the above rule makes it set up a proxy by SSH to proxy.example.org and relaying the connection to %h (server.example.com) with port %p (22 by default for SSH) by nc (you need to have nc
installed on proxy). This way, the git connection is forwarded to the git server.
Very good, works for me!
One extra tip is that you can use any of the other hosts defined in your config as the target of the ProxyCommand line.
Good to know that!
Yes. A multi-level proxy can be achieved using the ProxyCommand for multiple targets. Happy SSHing.