Restricting MySQL connections from localhost to improve security - mysql

I heard that anyone that knows my MySQL Username and Password can access it, Even if it's listening only to localhost.
Supposing my info is as following:
USER: root
PASS: 123456
Host: LOCALHOST (only)
How is it possible that anyone out there (local) can access it?

If you restrict access from remote hosts to your usernames and passwords then someone won't be able to access the database externally.
You could also configure your firewall to only allow traffic to 3306 (MySQL Default Port) from the localhost machine.
Update
To setup your user so they can only access through LOCALHOST use:
GRANT ALL PRIVILEGES ON *.* TO db_user #'localhost' IDENTIFIED BY 'db_passwd';
GRANT ALL PRIVILEGES ON *.* TO db_user #'127.0.0.1' IDENTIFIED BY 'db_passwd';
Also, bind your MySQL server to the local address. You can do this by editing the [mysqld] section of my.cnf:
[mysqld]
bind-address = 127.0.0.1

you can block direct access to MySQL at the firewall or within MySQL itself, but the most likely way you'd be hacked is through an insecure web application - in that situation the attacker would most likely be able to read your database login and connect from the server.
So keep your applications secure - keep everything updated, don't allow file uploads, use suPHP if you have multiple accounts etc.
If you restrict your mysql application follow this steps:
1.You could just block port 3306. If the site is on the same server then it will still be able to access the database using localhost as the hostname.
2.Just add "bind-address = 127.0.0.1" to the "[mysqld]" section of their my.cnf file to restrict access to localhost only.
Most of people use this type of restriction.

This is an older question that I stumbled across, but if Darkeden had phpMyAdmin or similar running, anyone can log in to that using valid MySQL credentials.
If it was compromised, then in addition to restricting connections, change all passwords.

I didn't see an answer that answered his (adjusted) question - he has locked it to localhost and the attacker is still getting in.
If you have truly restricted it to local host (check using netstat -an | egrep 3306 to check it is listening to 127.0.0.1 not 0.0.0.0),
then the only way of accessing it is to originate a connection from that local host.
Initial steps to take:
probably rebuild a replacement system from scratch and hardening it before you make it publicly accessible (having a repeatable recipe eg using ansible will help as you may have to go through a few iterations to learn how he gets in)
Check with reputable security scanners what you obvious holes are,
Get help from a security professional (depends if you want to spend $ or time and frustration to fix)
Apply security patches,
Remove services you don't need,
restrict the database access to only those programs that need it,
redo all your passwords,
check for installed root kits, and other viruses,
secure your server if at your own office and train staff in handling social engineering,
use a service that will monitor and filter the requests coming through and deny direct access (eg use cloudflare as a cheep starting point)
check for keyboard loggers (physical and software and other viruses) on all machines used to access the server),
check for physical means of logging your keystrokes in accessing your server (eg web cam style used in atm), the more exotic include sound (https://en.wikipedia.org/wiki/Acoustic_cryptanalysis), typing with a nearby wifi access point (eg https://www.schneier.com/blog/archives/2016/08/keystroke_recog.html)
Add an audit trail and monitor database activity to work out how he is getting through, but at least you need to do all the obvious securing first because otherwise he will just hop from one security hole to another
He could be also getting through using:
accessing via some program you are running (eg a web server) that is externally accessible and has a security hole that allows him to run arbitrary sql commands through its existing database connection - see https://www.w3schools.com/sql/sql_injection.asp
tricking some program he has access to from outside to proxy a connection for him to localhost:3306 (eg through a miss-configured network firewall on the machine)
tricking some program to run a local program (bash. mysql etc), and from there gaining access to the database - buffer overflows and other specially crafted data is a common issue to running arbitrary code
man in the middle attack on a connection that has legitimate access
bugs in a program that is automatically or manually processing data from outside, eg email, processing of postscript/pdf/any document with scripting processing - even viewing a text file can be dangerous - see https://www.proteansec.com/linux/blast-past-executing-code-terminal-emulators-via-escape-sequences/
social engineering a way through getting people to give you access
managing to get a hardware device attached to a computer that has access (how many people will pick up a "memory stick" lying in the work car park and check it out instead its a "programmable keyboard", and ALL computers trust keyboards!)
and then many more all the other sorts of methods I don't know, but those that are involved share ...
Just remember that you need to have practical security, I think xkcd says it just right: https://xkcd.com/538/

Related

Hosted MySql, Views, client Ipaddress change and Access Denied

I have a hosted MySql server with many databases each with many views. I access the server remotely from my office using HeidiSql.
Once in a while the IP address of my office changes. When this happens, I have to add the new office IP address to the server using cPanel and the "Remote MySql" tool so that I can remotely connect again.
However, all of the views have definer: USER#OLD_IP_ADDRESS. If I need to change a view, I get Access Denied. Up to now, I have been deleting the view (yes, i can delete the view) and recreating it, which makes the view's definer USER#NEW_IP_ADDRESS, and then I can edit the view -- until the Ip address changes again.
So, my question is: What is the best practice is an environment like this. Is there a way to define the views once and, without causing a security risk, be able to edit the views after an IP Address change.
Thanks for any guidance.
You could loosen the host in the MySQL user account a bit, according to the IP range of your internet provider. That way, you don't need to change it every time you get a slightly different IP:
user#123.456.789.%
user#123.456.%
This of course loosens the security in this account, but if your password is be a good one, it should not be too risky.
A better way is to make the MySQL server only accessible via SSH. In that case, your MySQL server can be set up using the --skip-networking option, as you always connecting from localhost. Your user account can be user#localhost or user#127.0.0.1, which then would solve your above mentioned problem for all times.
HeidiSQL also supports SSH tunneled MySQL connections, see here for some tutorial.

Host is not allowed to connect to this MySQL server for client-server application

I just exported my tables from one web host to another (AWS).
Thinking everything would go smoothly (yeah right), well, everything that can go wrong has gone wrong.
I get this error when trying to query my database (which I didn't get before):
SQLSTATE[HY000] [1130] Host '<my ip address>' is not allowed to connect to this MySQL server
This is the same error from this post:
Host 'xxx.xx.xxx.xxx' is not allowed to connect to this MySQL server
The solution in that post seems to revolve around having an administrative user. I am developing a chat application so every user needs to access the server (so I'm sure it's a bad idea to give them all administrative privileges).
The answer by Pascal in that link says, If you are using mysql for a client/server application, prefer a subnet address. but I honestly don't understand what he means by that. And because of the amount of solutions, I'm not exactly sure which one I should follow based on my case.
How do I resolve this?
MySQL has security tables that determine who is allowed to connect and from what host IP address.
Here's a good article on how to do it:
http://www.cyberciti.biz/tips/how-do-i-enable-remote-access-to-mysql-database-server.html
If you have a lot of connections, consider setting up a server to accept the connections and talk to the sql server. The easiest approach to this is to set up a REST interface and use a web server. Web servers are usually also highly optimized and relatively bug free.
In a similar architecture on AWS, I use nginx happily.
Make sure you have bind-address=YOUR-SERVER-IP in my.cnf and make sure you have a user hd1#172.31.39.86 or hd1#%, the latter being a MySQL wildcard on the MySQL server. More information here. You may also need to grant access to port 3306 (the default MySQL port) on the security groups section of the AWS console.
// IN YOUR MYSQL WORKBENCH You Have to Execute below query
CREATE USER 'root'#'1.2.1.5(Your Application Server IP)' IDENTIFIED BY 'pass';
GRANT ALL PRIVILEGES ON *.* TO 'root'#'10.200.1.54' WITH GRANT OPTION;
AFTER CREATING YOU CAN VIEW USING BELOW QUERY
SELECT * FROM mysql.user WHERE User = 'root';

Auto-Discourage MySQL brutforce login attempts

I noticed in one of my MySQL server that a remote attacker tried around 2000 login attempts in one night using 'root' and 'admin' usernames over 'mysql' system database. Luckily, I had setup mysql's query-log into a file log for monitoring purpose, and the passwords were difficult.
My database server survived that attack, even though it received almost one login attempt per second during the off-hours at (night).
There were around 10 different IPs with the same attack behavior all together, most of them having 'good reputation' in blacklist checking.
In this case, changing the database password may not be a good protective idea.
Is there a way to discourage such mis-behavior? For example, if there are about 5 wrong login attempts in short time, deny them the service?
How do MySQL experts handle this attack in case the MySQL port is open for remote login?
A lot of servers might be facing this kind of silent login attempts.
I recommend Fail2Ban. This is a script that watches logfiles for any patterns (e.g. failed logins) and creates then a firewall rule to prevent that IP to access your server. You can configure how many failed logins are necessary and for how long the access should be denied before the firewall rule is removed.
With fail2ban you can also watch ssh logins, mail accounts or event your own web-application logfile for malicious logins/behaviour.
As a general hint: rename your root/admin account to something else, so that they will never success anyway and change the public mysql port of your server (which is both just obscurity, but no real security). Also you should disable remote login for accounts (which is security).

MySQL user host networking

How is the host for a MySQL user evaluated by the database? My server tries to connect to the database from myhostname but fails even though I've set the hostname for that server in /etc/hostname It does work when I use an IP though.
The user was created like so:
GRANT ALL ON db.* TO 'dude'#'myhostname';
The MySQL error will tell you the hostname the server machine thinks your user is connecting from. Depending on DNS settings, this may or may not be the hostname your client thinks is assigned to itself. The name as seen from the server is the one you need to set in your GRANT statement.
(Which is logical. Suppose I know that the server gives privileges to host Alice. I have host Bob. Since it's my host, I can change its name to Alice. If just doing this granted me Alice's privileges, the whole GRANT scheme would be completely insecure! What happens is that my host thinks it's Alice, but the server sees my IP, asks the DNS "Who is this?" and receives "He's Bob". I still can steal Alice's privileges, but I need to compromise the DNS records somehow)
In a pinch, add the client IP and hostname to the server /etc/hosts file. This is a hack, however, and proper DNS setting is the way to go: a forgotten hosts hack might cost you a long time of head scratching a few months down the road.
As explained in DNS Lookup Optimization and the Host Cache from the MySQL manual:
The server performs host name resolution using the thread-safe gethostbyaddr_r() and gethostbyname_r() calls if the operating system supports them. Otherwise, the thread performing the lookup locks a mutex and calls gethostbyaddr() and gethostbyname() instead.
Therefore the resolution of the connecting IP to myhostname is a matter for the operating-system, rather than MySQL. You should first determine that your OS is correctly resolving the client IP and, if not, debug your OS or nameservice configuration (questions on this subject might be better directed to Super User or Sever Fault, rather than StackOverflow).

Users can't connect remotely to MySQL

Problem
Users from other IPs on the (Windows XP) LAN suddenly cannot connect to my local MySQL server.
Background
I've set up MySQL on my local Windows computer so that other computers on the network have access to the root account. I've added each IP as a host for root. Up to some weeks ago, things worked flawlessly and I could connect to the server programatically and using various MySQL admin tools. Now, however, the MySQL server simply refuses connections from those IPs and I can't figure out why.
The network changes that I've done are: changing network card for two (of three) computers and fiddled around with MySQL settings. None of which should have caused this problem. I've tried adding a new user with all relevant hosts, but I get the same type of error:
MySQL Error number 1045 Access denied
for user 'root'#'shop' (using
passwords: YES)
The odd part is that the computer name, 'shop', is used instead of the IP. I don't know why.
Somehow, IPs seem to be resolved now and hostnames are used. Did you grant access to root#shop? Did you flush privileges?
First thing that pops into mind is Windows Firewall, which could have got re-enabled if you swapped NICs on the host computer.
My next suggestion would be to use a sniffer like Wireshark on the host computer and see what exactly happens packet-wise. You can use filters to make to reduce the output - they're very simple and easy to use. This tool has saved me countless hours of debugging.
-EDIT-
Another possible cause might be that your server somehow decided to resolve IPs to hostnames, in which case ip addresses may no longer work - one would need to add hostnames to the allowed list. Not sure if it works this way for MySQL though.
Could you have turned off TCP connections in MySQL?
Also, is the MySQL port open in your firewall?
If you changed your IP (DHCP?), make sure to correct it in my.cnf if you bound mysqld to your lan ip:
[mysqld]
...
bind-address=192.168.x.y