Git through SSH Tunnel as Proxy

git 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.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

2 comments:

  1. 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.

Leave a Reply

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