Forwarding MySQL from local port to remote server

in Servers


If you have access to a MySQL server which allows whitelisting only a few IP addresses and you need to allow a whole range, you can use a tiny separate "proxy" VPS that would receive the connections and forward them to your MySQL server. You will then only have to whitelist the "proxy" VPS IP with the MySQL server. And then you can whitelist all you want using firewall on that VPS.

An example would be connecting Google Data Studio (which requires whitelisting a whole /23 range) to Aruba MySQL DBaaS (which on a cheaper shared plan allows whitelisting only two IPv4 addresses).

What won't work:

  • SSH tunnels require an underlying SSH connection, which Google won't do here
  • stunnel is only for SSL or HTTPs

What will work:

Use socat as a TCP port forwarder: For multiple connections, use the fork option as used in the examples below:

socat TCP4-LISTEN:81,fork,reuseaddr TCP4:TCP4:192.168.1.10:80

This example listens on port 81, accepts connections, and forwards the connections to port 80 on the remote host.

Except watch out: the above documentation has a typo where it lists TCP4:TCP4 twice. That will result in an error:

socat[7877] E TCP4: wrong number of parameters (3 instead of 2)

The correct command is:

socat TCP4-LISTEN:3307,fork,reuseaddr TCP4:1.2.3.4:3306 &
  • 3307 is the local port on your "proxy" VPS
  • 1.2.3.4:3306 is the remote MySQL server IP address and port

On a Debian VPS, install socat using:

apt-get install socat

Sources:

#mysql #debian #socat