How to test connection to mysql server? - mysql

I'm trying to figure out how to test if a connection is possible with a given set of user, pw, and db name info. I parse out the user_name, password and database_name from an environment file and then I would like to test if the connection is possible. If possible continue with the rest of the script and if not possible, exit and print an error message. I want to test the connection because I have another larger script that just runs everything but I can't tell where it fails if it does fail.

You can make a no-op connection:
mysql -e '\q'
If I run this with a suitable .my.cnf file, $? is zero. If I try to use a different user:
mysql -u root -e '\q'
then I get an error message (which can be redirected away with 2>/dev/null) and $? is non-zero.
Note that this is a fairly limited test, compared to using a language with a SQL library and a connection that spans multiple commands. E.g. one connection may succeed, but a later one may fail because of network conditions or a change to the user's conf file or to the server authentication.

Im going to put htis as an answer so i can use formatting...
Do something similar to the following. I dont know what code you are using so this is a fairly generic example:
$conn = (SQL statement);
if (!$conn)
{error output}
else
{do logic};
So if you have many statements and you do this kind of thing for each of them using a unique error output for each then you can easily tell which one is causing the problem by reading the output.

Related

I can't start MySQL server in NodeJs after reset MySQL password using Windows's cmd

I reset my MySQL password using cmd commands from this guide.
cd "C:\Program Files\MySQL\MySQL Server 8.0\bin"
mysqld
--defaults-file="C:\\ProgramData\\MySQL\\MySQL Server 8.0\\my.ini"
--init-file=C:\\Users\\<username>\\resetMYSQL.txt
resetMYSQL contains a command to change password
ALTER USER 'root'#'localhost' IDENTIFIED BY '<myNewPassword>';
Now, it turned out I have to keep running the mysqld command above to start my server or else I'll get this error. If I run the command again I can flawlessly run my server until I terminate it.
This is the error. It's ECONNREFUSED.
I think my password is already reset, because apart from the command line, I also run ALTER USER in Workbench after I got access to it while the cmd is running.
Btw, before this I can just start my server using Node and Sequelize and didn't have to start server elsewhere or set anything beforehand
I'm not sure what is the problem here, so I don't know which keyword I should look up on Google. I googled the error code, but those cases seems unrelated to mine.
I'd be glad if you can explain me what's going on.
The nodejs error message you showed us, a ECONNREFUSED message with a traceback, shows the your mysql database server program was not running when your nodejs program tried to connect to it. Nodejs reaches out to MySQL via TCP/IP. TCP/IP responds "I don't know any MySQL." Specifically, it responds "ECONNREFUSED on port 3306," meaning "nothing on this machine accepts connections on MySQL's port."
nodejs does not start the mysql software for you. It connects to it and uses it.. MySQL has to be running already for that work.
Ordinarily, software like mysql runs in the form of a operating system service; a background process that runs all the time on the machine to await requests).
And, ordinarily, you don't provide init files to MySQL to do things like change passwords, except just once, if you must, to rescue something broken. In your case it looks like you forgot your MySQL password, so you needed to use an init file to rescue yourself. Once the password is reset, stop using that init file.
Explaining how to make MySQL run as a service on your machine is beyond the scope of a Stack Overflow answer. But the installers for MySQL, on almost every operating system, set it up to run as a service automatically. It's generally useless otherwise.

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.

Options for secure connection to mysql from bash script

I am trying to execute a few mysql statements in bash script. The script connects to mysql and does all the required work. But, it gives me a warning
Warning: Using a password on the command line interface can be insecure.
I understand that passwords and usernames must not be used directly in the script, which I have currently done
What other options do I have in order to not have this warning coming up? Can I have a file with the key:value pairs for host,dbname,username and password and then use the file for connection details in the script?
Thanks in advance
Rathi
During the init phase of your script, I would ask the user for host, username and password. Then forward these variables to the mysql command.
See here where you can learn how to ask the user for content without echoing it on the terminal window.

Problem using Perl to connect to MySQL database on remote server

I have a Perl script that gets data from a MySQL database on one server (let's call it server1), does stuff with it and writes it out to another database on another server (server2). Both servers are remote to the server that runs the Perl script.
I can connect to the DB on server1 OK, but when I try to connect to the DB on server2, using the same DBI method, I get an error. Here, as command-line Perl, is the bit that's causing the error:
perl -MDBI -e 'DBI->connect("DBI:mysql:myDB:server2.whatever.co.uk","myuser","mypassword") or die DBI->errstr;'
And here's the error message:
DBI connect('myDB:server2.whatever.co.uk','myuser',...) failed: Client does not support authentication protocol requested by server; consider upgrading MySQL client at -e line 1
Client does not support authentication protocol requested by server; consider upgrading MySQL client at -e line 1.
I do not have root access so I can't upgrade MySQL and I can't change the password to use the old password hashing algorithm, which is the solution suggested in lots of places.
Ideas anyone?
The database may be set up to accept connections only from within a certain set of addresses, as a security measure. So if you're trying to access a prod database from a home laptop (for example), it may reject you, even if you have the proper credentials. Try accessing it from a place where it's known to work using another technology -- for example, if you have a website that accesses it already, go to wherever apache/tomcat is running, and try the perl there. If it works, that's the issue. You can also proactively check on the database settings.
OK, in the absence of an alternative, I got someone with root access to server2 to do the fix that's published elsewhere:
Connect to MySQL as the MySQL root user, then:
mysql> use mysql;
mysql> SET PASSWORD FOR 'username'#'hostname' = OLD_PASSWORD('password');
mysql> FLUSH PRIVILEGES;
Replacing 'username', 'hostname' and 'password' with appropriate values.
So what I'm saying here is, it seems like if you don't have root access to upgrade MySQL or to change the password to use the old password hashing algorithm, then the only solution is to find someone who does who can make the change for you.

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.