MySQL 5.1 / phpMyAdmin - logging CREATE/ALTER statements - mysql

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.

Related

How to pass the password securely to MySQL Client with automation

I'm seeking for solution to pass the password securely to MySQL client on *nix platforms while using automated script solution (i.e Bash script).
So far, I had to realize that MySQL ignores password input from stdin at all (still asks for password on terminal, crashes on automation).
The worst, solution using ~/.mylogin.cnf also doesn't work for me, it seems MySQL somehow ignores it at all.
I prefer to not to use the command line -p argument for password to prevent described "all-around" security issues.
--defaults-file and --defaults-extra-file handn't give the solution as well, seems like the password is prompted by client at "all-cost".
Therefore, I'm just running out of solutions for that primitive (at first sight) task!
Any help will be highly appreciated!
I'll try to be short in my findings:
First, the solution using mysql --defaults-extra-file="path/to/file" is actually worked for me among with --default-file option until it is passed as the first argument (as well noticed by Bill Karwin here).
Second, usage of ~/mylogin.cnf also workes fine until the file access restricted for all users except the current account the MySQL client is running under + file is restricted from execution even by current user (chmod u-x) as well, possibly treated by MySQL as a threat due to Linux GUI x permission umbrella on many systems (execute permission is enabled for user, group and others by setting one V in GUI for the file). Still this reason is just a suggestion.

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.

How to enable MySQL external access [duplicate]

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.

How to test connection to mysql server?

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.

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.