Mysql – Too many TIME_WAIT connections on thesql from an outside host

brute-force-attacksMySQLnetstattcp

My netstat is showing over 2,000 mysql connections with the state of TIME_WAIT that seems to be stuck and won't go away. It's been like that for several hours and many of the connections are coming from an IP address that doesn't have privilege to my database server. It seems to be hanging, how do I clear this? Is this a brute force attack? All my user privileges have specific hosts and I don't use any wildcard.

Here's a snippet of netstat:

tcp        0      0 server:mysql       static.98.17.76.1:45222 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:34341 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:51888 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:54459 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:49599 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:50751 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:50731 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:54658 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:58974 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:33800 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:59840 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:53495 TIME_WAIT  
tcp        0      0 server:mysql       static.98.17.76.1:51561 TIME_WAIT 

Also, my PROCESSLIST in mysql doesn't show these connections so I assume they get dropped right away but not sure why they won't go away. Will this cause any issues with max connections for mysql?

Best Answer

If you find some connections in netstat output in TIME_WAIT state, this can be normal. You can get too many of these when you have too many short lived connections.

I got some of these even without the need to supply any username, password, or database name. Just type:

mysql -h your_server_ip
ERROR 1045 (28000): Access denied for user 'khaled'@'your_pc_ip' (using password: NO)

and you will get one left connection in TIME_WAIT state:

sudo netstat -anp | grep 3306
tcp      0      0 server_ip:3306      your_pc_ip:50464      TIME_WAIT   -

However, it is recommended to deny access from this IP especially if you don't recognize this IP as a legitimate client. A simple iptables rule like this can deny further requests from this IP:

sudo iptables -A INPUT -s bad_ip -p tcp --dport 3306 -j DROP

You may need to change -A to -I depending on whether you have other rules or not.