Saturday, September 15, 2007

How to hijack a Linux + MySQL server

I hope I got your attention with the title. The politically correct term should be "how to redirect MySQL traffic on Linux", but you probably wouldn't have noticed.
The scenario is this. You want to switch servers without need for the clients to change connection parameters.
Why would you want to do this? Some reasons:
  • You want to test a new server version, which you installed to listen to port 13306, and you want to do it without modifying the applications parameters;
  • You ant to use MySQL Proxy on port 4040 to log the traffic for a while without restarting the server, in order to debug an inexplicable problem;
Whatever the reason, you can do it.

Here is how you can proceed on Linux.

Set a iptables rule to redirect port 3306 to port 13306 or to port 4040:
sudo iptables -t nat -I PREROUTING \
-s ! 127.0.0.1 -p tcp \
--dport 3306 -j \
REDIRECT --to-ports 13306
Caveat: This will only work if your clients are connecting from a separate machine. On the same server, this rule spares the local IP address 127.0.0.1.

To undo the redirection, repeat the above command with -D instead of -I.

1 comment:

sysadmin said...

That's one good possibility. Normally , I use rinetd.