How do I manually block and then unblock a specific IP/Hostname in MYSQL

14,678

Solution 1

You can use GRANT to give a non-privileged entry for a user connecting from a specific host, even if you have GRANTed privileges to a wildcard including that host. When authenticating, the most specific host match takes precedence.

For example, suppose you enabled a user to connect from a range of hosts on your local subnet:

mysql> GRANT ALL PRIVILEGES ON *.* TO 'user'@'192.168.56.%' IDENTIFIED BY 'xyzzy';

Then you could grant the minimal USAGE privilege, which is a synonym for "no privileges" for that user for one specific host within that subnet:

mysql> GRANT USAGE ON *.* TO 'user'@'192.168.56.110';

Subsequent attempts to connect from that host get this error:

$ mysql -uuser -pxyzzy
ERROR 1045 (28000): Access denied for user 'user'@'192.168.56.110' (using password: YES)

The reason this gets an error is that I did this grant for the user with no password. If I try to submit a password, this doesn't match the entry in the privileges table.

Even if the user tries to connect without using a password, he finds he has no access to anything.

$ mysql -uuser 
mysql> USE mydatabase;
ERROR 1044 (42000): Access denied for user 'user'@'192.168.56.110' to database 'mydatabase'

You can undo the blocking:

mysql> DELETE FROM mysql.user WHERE host='192.168.56.110' AND user='user';
mysql> FLUSH PRIVILEGES; 

And then the IP range will come back into effect, and the user will be able to connect from thathost again.

Solution 2

You can revoke privileges as mentioned above, but this will still allow a user to make a connection to your MySQL server - albeit this will prevent that user from authenticating. If you really want to block/allow connections to your MySQL server based on IP, use iptables.

Share:
14,678
E.S.
Author by

E.S.

Updated on June 04, 2022

Comments

  • E.S.
    E.S. almost 2 years

    First off, I did google this but sites are flooded with advice on how to deal with "host name is blocked" issues. (https://www.google.com/search?q=mysql+block+a+host). My issue is a little bit the opposite of that.

    With me, I am running a MySQL database and no PHP is involved.

    I need to block a certain host-name/IP address from connecting to my database, then I will unblock it. I am hoping there are 2 simple queries for this that I can execute on the MySQL database, I just can't seem to find it anywhere.

    I can find the hostnames pretty easily by running the show processlist query and I know I can kill one process at a time, but so many new threads pop up that if I can just block all of them from a certain hostname, that would be ideal. Then I will unblock once I fix a few things.