How to enable MySQL external access [duplicate] - mysql

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
$con = mysqli_connect('<remote server ip address>','root','*******','CSV_DB',);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
I have a simple program to connect to a mysql server that I created using phpmyadmin, however I get the 'could not connect' message every time I try to connect.
I know that it could be a number of different issues but I'm really looking for advice on how to troubleshoot.
When I ssh as root to the server I can access the server using the terminal and everything is fine. However this connection which uses the same username/password/db/etc and I can't seem to log in. Also, the mysqli_error never prints-not sure why.

Here is a quick quick checklist for enabling Remote Connections for MySQL but read (6) first. If I have missed anything, feel free to edit.
1) Your remote user is connecting through an account that was created with appropriate user,host entries (look at output from select user,host from mysql.user order by 1,2). If not, look into the CREATE USER and/or GRANT commands. Examine the output from SHOW GRANTS for the user.
2) You have done flush privileges; (Some say it is unnecessary, others say it is).
3a) Locate your mysql configuration file referenced in 3b) below by reviewing info in This Document (or for Windows, likely down the C:\ProgramData\MySQL\MySQL Server 5.NNN path). It varies by distro for Linux.
3b) You have modified and saved my.ini (Windows) or my.cnf (Linux) and changed bind-address away from 127.0.0.1 or localhost, in favor of 0.0.0.0. And you have created and rem'd out the following line: #skip-networking. It will look similar to this:
[mysqld]
bind-address=0.0.0.0
#skip-networking
4) Restart the mysql daemon. How one does this varies by distro.
5) Firewall issues. Make sure the port, default being 3306, is open to the outside world (which may in fact just be your intranet). This includes any other layers of firewalls, such as AWS EC2 Security Groups, or similar, if any.
6) Understand that there is a security risk associated with this. Unless you have knowledge of exposing your mysql server to remote connections, do not perform this.
7) Please run frequent security assessments with select statement listed in 1. above including reviewing the SHOW GRANTS for those users. Do not over-grant users with wildcard unnecessarily. Rather, give users the minimal privileges for them to get their work done.
8) Frequently examine failed connection attempts via the General Log and the Error Log as briefly introduced below.
For inbound, you can look at the general query log.
select ##general_log; -- a 1 indicates it is turned on for capture
select ##general_log_file; -- the file that it logs to
So all the queries can be logged to the General Query Log if the setting is turned on. Examine the log for "connect", but especially for Access denied for user to see failed attempts. Do this regularly (not every few years). I do it at least twice a day. Note, you can obviously automate the reporting through an external program. The outside world is going to pound your server to get in like the image below. It is a reality; brace yourself for it.
Check out the manual page for The Error Log too, noting warning levels, and verbosity settings based on your version.
I would recommend that one create a backup copy by date (named as such) and delete the log files after backup to start fresh after the backup. The log files can grow huge in size rapidly, especially the General Log. Don't forget whether or not you have the setting turned on or off for logging.
You can use the two logs to determine if your connection attempt made it past the firewall during the steps here.

Related

Testing Script - Find open MySQL Ports and check Database

following Problem:
I want to Check all Open MySQL Ports in a network and give myself a list of them.
After this i want to check if i can get access to the MySQL database from the open ports.
It Would be just a security check script to avoid other people getting access to the databases.
Bash/perl/Powershell... maybe someone can give me a hint?
You can use NMAP for all port scanning tasks.
EDIT:
Lets asssume an example: mysql-vuln-cve2012-2122(This vulnerability tries to access the MySql server through open ports by bypassing authentication, if possible, also dumps the MySQL usernames and password hashes.)
Pre-requisite: You need the 'Vulns' library to be installed separately. Please read the documentation, to know more about how to install and other details, since it would be too tedious to explain it here.
mysql-vuln-cve2012-2122.pass
MySQL password. Default: nmapFTW.
mysql-vuln-cve2012-2122.user
MySQL username. Default: root.
mysql-vuln-cve2012-2122.iterations
Connection retries. Default: 1500.
mysql-vuln-cve2012-2122.socket_timeout
Socket timeout. Default: 5s.
Please leave the password blank to check for non-password vulnerabilities.
Command to run:
nmap -p3306 --script mysql-vuln-cve2012-2122 <target>
Here is your MySql instance
This will give an output, something like this:
PORT STATE SERVICE REASON
3306/tcp open mysql syn-ack
mysql-vuln-cve2012-2122:
VULNERABLE:
Authentication bypass in MySQL servers.
State: VULNERABLE
IDs: CVE:CVE-2012-2122
Description:
When a user connects to MariaDB/MySQL, a token (SHA
over a password and a random scramble string) is calculated and
compared
with the expected value. Because of incorrect casting, it might've
happened that the token and the expected value were considered
equal,
even if the memcmp() returned a non-zero value. In this case
MySQL/MariaDB would think that the password is correct, even while
it is
not. Because the protocol uses random strings, the probability of
hitting this bug is about 1/256.
Which means, if one knows a user name to connect (and "root"
almost
always exists), she can connect using *any* password by repeating
connection attempts. ~300 attempts takes only a fraction of
second, so
basically account password protection is as good as nonexistent.
Disclosure date: 2012-06-9
Extra information:
Server granted access at iteration #204
root:*9CFBBC772F3F6C106020035386DA5BBBF1249A11
debian-sys-maint:*BDA9386EE35F7F326239844C185B01E3912749BF
phpmyadmin:*9CFBBC772F3F6C106020035386DA5BBBF1249A11
For more and detailed info, please refer the above link.
The NMAP tools will not only help you in getting the list of port related vulnerabilities. It can also be used to search for other vulnerabilities like MySql injection,DDOS, brute force vulnerabilities and lot more. Though you need to download separate libraries for those.

Difference In Phpmyadmin Mysql web client and Terminal client

I got problem (#2006 Mysql server gone away) with mysql while connecting and performing some operations through web browser.
Operation Listed below:
When Executing big procedure
Importing database dump
When Access some particular tables It immediately throws "Server gone away".
Refer this question for Scenarios: Record Not Inserted - #2006 Mysql server gone away
Note : The above operations are works fine when I perform through terminal.
I tried some configuration as googing stated. That is set wait_timeout, max_allowed_packet. I checked for the bin_log but it is not available.
But the issues will not rectified.
What is the problem & How can I figure out & fix the issue?
what is the different between access phpmyadmin mysql server from web browser and terminal?
Where I can find the mysql server log file?
Note: If you know about any one of the above questions. Please post here. It would be helpful to trace.
Please help me to figure this out..
Thanks in advance...
Basically nothing except phpMyAdmin is limited by PHP's timeout and resource limits (limits to keep a runaway script from bogging down your entire machine for all eternity; see the docs for details of those values. In some cases, you might be authenticating through a different user account (for instance, root#localhost and root#127.0.0.1 aren't the same user), but as long as you're using a user with the same permissions the differences are minimal.
You can read more about logs in the MySQL manual, note that "By default, no logs are enabled (except the error log on Windows)".
Below are answer for question
From my research the problem is that browser have some limit to disconnect the connection i.e timeout connection. So that the above problem raised.
To resolve this problem
Go to /opt/lampp/phpmyadmin and open config.inc.php
add the command $cfg['ExecTimeLimit'] = 0;
Restart the xamp server. Now you can perform any operations.
`
2. Web client is differ from terminal because Terminal client will not getting timeout. Terminal client maintain the connection till the progress completed. I recommenced to use command prompt to import/export/run process by safe way.
Basically phpmyadmin will not have any log file. If you wanna see warnings and error you should configure the log file.
Configuration steps:
Go to /opt/lampp/etc/my.cnf
Add log_bin = /opt/lampp/var/mysql/filename.log
Restart the xamp server. You can get the log information.

Restricting MySQL connections from localhost to improve security

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/

MySQL can't write to file, permission denied. (Error 13)

I have a web application that runs queries on the database. The application is trying to run a query, and send the results to the an output file. I have confirmed that the issue is actually a permission denied (error 13) problem, not an issue with any other part of the query. A simplified form of the query follows:
SELECT 'anything'
INTO OUTFILE '/var/www/html/sl/filestore/dbadpt_database.tmp'
FROM INFORMATION_SCHEMA.TABLES;
This query runs fine when I remove the INTO OUTFILE line. I have tried every permissions setting for this dir that I can think of. I have even changed the permission to 777, and gotten the same results. (Yes, I know 777 is not secure. Just did it for testing) I have tried every ownership combination of 'root', 'apache', and 'mysql' that I could think to try for this dir. I have pasted the above query into the MySQL command-line tool, and it has produced the same results.
We are running CentOS 5.5. The web server running the application is Apache 2. I cannot create the file ahead of time, nor can I change the directory that the program is trying to write to.
I would hazard a guess that problem is with SELinux.
The first thing I would try would be setenforce 0 and see if that fixed it. It will only fix the symptoms (you still need to reconfigure SELinux to allow what you need), but it will at least confirm whether that's the problem or not.

MySQL 5.1 / phpMyAdmin - logging CREATE/ALTER statements

Is it possible to log CREATE / ALTER statements issued on a MySQL server through phpMyAdmin? I heard that it could be done with a trigger, but I can't seem to find suitable code anywhere. I would like to log these statements to a table, preferably with the timestamp of when they were issued. Can someone provide me with a sample trigger that would enable me to accomplish this?
I would like to log these statements so I can easily synchronize the changes with another MySQL server.
There is a patch for phpMyAdmin which provides configurable logging with only some simple code modifications.
We did this at my work and then i tweaked it further to log into folders by day, log IP addresses and a couple other things and it works great.
Thanks #Unreason for the link, i couldn't recall where i found it.
Here is a script that would do what you want for mysql-proxy (check the link on official docs how to install the proxy).
To actually log the queries you can use something as simple as
function string.starts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function read_query( packet )
if string.byte(packet) == proxy.COM_QUERY then
local query = string.lower(string.sub(packet, 2))
if string.starts(query, "alter") or string.starts(query, "create") then
-- give your logfile a name, absolute path worked for me
local log_file = '/var/log/mysql-proxy-ddl.log'
local fh = io.open(log_file, "a+")
fh:write( string.format("%s %6d -- %s \n",
os.date('%Y-%m-%d %H:%M:%S'),
proxy.connection.server["thread_id"],
query))
fh:flush()
end
end
end
The script was adopted from here, search for 'simple logging'.
This does not care about results - even if the query returned an error it would be logged (there is 'more customized logging' example, which is a better candidate for production logging).
Also, you might take another approach if it is applicable for you - define different users in your database and give DDL rights only to a certain user, then you could log everything for that user and you don't have to worry about details (for example - proxy recognizes the following server commands, out of which it inspects only Query)
Installing the proxy is straight forward, when you test it you can run it with
mysql-proxy --proxy-lua-script=/path/to/script.lua
It runs on port 4040 by default so test it with
mysql -u user -p -h 127.0.0.1 -P 4040
(make sure you don't bypass the proxy; for example on my distro mysql -u user -p -h localhost -P 4040 completely ignored the port and connected over socket, which left me puzzled for a few minutes)
The answer to your question will fall into one of the listed in MySQL Server logs
If you just want to get the CREATE/ALTER statements, I would go with the general query log. But you will have to parse the file manually. Be aware of the security issues this approach raises.
In your scenario, replication seems to be an overkill.
Triggers are not a valid option since they are only supported at SELECT, UPDATE and INSERT level and not ALTER/CREATE.
Edit 1:
The query log would be the best choice but as you mentioned on busy servers the logs would cause a considerable efficiency penalty. The only additional alternative I know of is MySQL Proxy.
I think that your best bet would be to look at the use of stored procedures and functions here to make changes to your DB. That way you could look at manually logging data.