
Restricting mySQL access to specific IP addresses. (Linux)
If you manage a web or database server, and do not have an active firewall, you may want to use the following method to restrict access to your mySQL service from the Internet. These instructions are for Linux (tested under Red Hat and CentOS), and require you to be running the iptables service. Check if you have iptables running by executing the following command as root:
service iptables status
Start iptables if the service is not running. You should also set iptables to load on boot as well. This can be achieved using the following command:
chkconfig -level 345 iptables on
Now that you know iptables is running, you can begin adding the new rules for allowing only specific ip addresses to connect to your mySQL database.
Note: If you do not want any external connections to your mySQL database, you can also edit the my.conf file located by default under /etc/my.cnf. Simply add bind_address = 127.0.0.1 under [mysqld], and restart the mysql service. mySQL will now deny all external connections.
For this example, I’m going to allow access from 3 servers, and deny every other address. Execute the following commands in order, and replace IP address 1, 2, and 3 with the addresses of your servers.
iptables -A INPUT -p tcp -s IPaddress1/32 --dport 3306 -j ACCEPT iptables -A INPUT -p tcp -s IPaddress2/32 --dport 3306 -j ACCEPTiptables -A INPUT -p tcp -s IPaddress3/32 --dport 3306 -j ACCEPTiptables -A INPUT -p tcp --dport 3306 -j DROP
When configuring iptables, order is important. The effects of each command are immediate, but you must save your iptables settings or you’ll lose them on your next restart. Do this by issuing the following command:
service iptables save
You iptable settings are now saved, and will be used next time iptables is restarted. By default in Red Hat, and centOS, the settings are stored here: /etc/sysconfig/iptables
