9

I am trying to restrict MySQL 3306 port on a linux machine from making any connections to anything other than localhost to prevent outside attacks. i have the following code, i am not sure if it's correct:

iptables -A INPUT -p tcp -s localhost --dport 3306 -j ACCEPT

iptables -A OUTPUT -p tcp -s localhost --dport 3306 -j ACCEPT

iptables -A INPUT -p tcp --dport 3306 -j DROP

iptables -A OUTPUT -p tcp --dport 3306 -j DROP

my other question is - is it correct to only give localhost access? this is a standard dedicated centos webserver with more than 30 domains on it.

Levon
  • 138,105
  • 33
  • 200
  • 191
califmerchant
  • 167
  • 1
  • 2
  • 7
  • Why not just use the permissions when setting up the mysql user to only allow that user to log in from localhost so it would be something like mysqluser@localhost instead of mysqluser@% – bretterer Jun 12 '12 at 17:06
  • 2
    Forgive me asking but why don't you just use Unix sockets and `--skip-networking` if you don't want the port to be open? – Wladimir Palant Jun 12 '12 at 17:10
  • Your iptable rules do work, I just tried them out. – guylabbe.ca Oct 07 '15 at 00:28

3 Answers3

17

Why not just turn off networking with MySQL?

Add to my.cnf:

skip-networking

It's supposed to also give a negligible performance improvement by forcing connection through pipes, which skips over lots of tests used for the networking section. Please note you will need to use localhost, not 127.0.0.1, after the change.

Will Morgan
  • 4,470
  • 5
  • 29
  • 42
9
iptables -A INPUT -p tcp --dport 3306 -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT

The above rule is for converting two lines into single one.

Answer to your second question:

If you do not want to provide mysql access from other than localhost, then it is perfect to configure this way. Simple. :-)

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
5
iptables -A INPUT -p tcp --dport 3306 -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT
iptables -A INPUT -p tcp --dport 3306 -j DROP

If you want to remove the filtering, use this:

iptables -D INPUT -p tcp --dport 3306 -s 127.0.0.1 -d 127.0.0.1 -j ACCEPT
iptables -D INPUT -p tcp --dport 3306 -j DROP

Note: Both might require root, so: sudo iptables (...)

KKKas
  • 466
  • 5
  • 5