MySQL root-login with SSH private key? - mysql

Suppose Mysql -dbs and an admin with a bad habbit to forget the passwords (or paranoid enough wanting more creative authentication, not just password). Is it possible to access Mysql -root shell for example in a way that the Ssh-agent stores the private keys and then I could just login by "mysql -u root" (without typing the passwords or a combination of private-key and a password)?

You can certainly use the normal SSH key authentication to log on to your shell account and then use a ~/.my.cnf file with your password inside. This will be used by default by the mysql command line client.
Its content should be:
[client]
user=the_user_name
password=the_password
Beware that whoever can read this file will be able to use those credentials. Protect it so that only the owner can read it (and lock your terminal if you go away from your keyboard).
If you want direct key-based authentication, you could also use SSL client-certificate authentication. You could create your own small CA and issue yourself with these client-certificates. A number of tools support this if you require direct remote access.

Related

Add password to phpmyadmin without adding a root password

Is there any way to restrict access to phpmyadmin without adding a password to root (keeping root password as null). May be using Apache configuration files or other method?
As you enter username and password in phpmyadmin authentication screen, phpmyadmin directly try to access database from given username and passwords like
$conn = new mysqli(localhost, $username, $password);
If mysql returns any Databased associate with this user than phpmyadmin show complete information about this database.
So by default it's not possible to access phpmyadmin using root password null.
But still there are two option
Create new Mysql user with all database access privilege keeping your root password null
Phpmyadmin is open-source so make changes as per your need.
Sure, you can accomplish this with the normal Apache .htaccess authentication.
For instance, your .htaccess can contain:
AuthUserFile /home/Sanjay/.htpasswd-phpmyadmin
AuthName "My custom phpMyAdmin authentication"
AuthType Basic
Require valid-user
Then you just have to create the file /home/Sanjay/.htpasswd-phpmyadmin (you can use whatever path you wish here, in fact it may not be ideal to put it under your user home directory) using the htpasswd command-line program or one of the many online tools. Make sure both files are readable by the webserver and you should be all set.

How do I change the default MySQL user on OpenSuSE 13.1

How do I get the "mysql" command to open a connection to MySQL with the root user? I don't want to type mysql --user root, I want it to start immediately.
I have two machines: Mageia 3 and OpenSuSE 13.1. The Mageia machine does this exactly when I open a terminal as the normal user: it simply starts a mysql session and when I type SELECT USER(); it says "root#localhost".
The OpenSuSE machine tries to use the current bash user to connect to mysql instead of using root. How do I configure this behavior?
Specify a user option in the [client] section of ~/.my.cnf
...but generally its considered bad practice to use the admin account for normal use of a system.
Although symcbean's solution works, I found it easier to create a user with the same name as the Linux account that is calling the command. Give this user enough privileges and voilà. This way avoids the problem mentioned by symcbean.

Store MySQL password in bash-script

Need to create simple mysql-backup script.
But - how can I store encrypted pass of MySQL user in it?
I want to avoid store password in plaintext type in any additional files.
As I found in MySQL manual:
MySQL encrypts passwords stored in the user table using its own algorithm
So. there is no way to just get hash and set it as variable?
I mean:
DBHASH="cGFzc3dvcmQ="
DBPASS=`echo $DBHASH | openssl enc -base64 -d`
Is there any correct way to sovle it?
Thanks for tips.
It doesn't matter if the script contains a plaintext password or not if it includes a repeatable routine for getting into MySQL (i.e. automatically decrypting) - an attacker would just do the same. If you could pass the hash/decrypted password and have MySQL compare it would be just as repeatable (and the hash would function as a password anyway).
So, the easy answer is: You can't do this. You have some options...
Set up a correctly chmoded (600) ~/.my.cnf with the credentials.
Create a 'restricted', password-less backup-account that is only allowed to log in from localhost.
Only allow backup logins from localhost/backup host in either case.
If you're on Debian you could use the debian-sys-maint account (which has a my.cnf already set up with credentials)
Restrict the mysql account and include the password in the script plain text, but only allow given user/root to read script (if you have root you can take over mysql anyway).
Read/'source' the config variables (username/password) from an external file (with correct chmod - 600)...but you're basically doing the my.cnf-thing by then.
Remember a "backup account" does not need write privileges etc...
afaict, there's no way to do what you're looking for. Whether you store the hash or the original password, you will anyway store very sensible information that might be evil used if someone gets read access to your script.
What you may prefer, is instead setup up an user account that can't login, and setup up mysql so that user has the exact permissions for your script. And also make it so that this user is the only one having exec access to the script.

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

After creating the instance, I can login using gcutil or ssh. I tried copy/paste from the ssh link listed at the bottom of the instance and get the same error message.
The permission denied error probably indicates that SSH private key authentication has failed. Assuming that you're using an image derived from the Debian or Centos images recommended by gcutil, it's likely one of the following:
You don't have any ssh keys loaded into your ssh keychain, and you haven't specified a private ssh key with the -i option.
None of your ssh keys match the entries in .ssh/authorized_keys for the account you're attempting to log in to.
You're attempting to log into an account that doesn't exist on the machine, or attempting to log in as root. (The default images disable direct root login – most ssh brute-force attacks are against root or other well-known accounts with weak passwords.)
How to determine what accounts and keys are on the instance:
There's a script that runs every minute on the standard Compute Engine Centos and Debian images which fetches the 'sshKeys' metadata entry from the metadata server, and creates accounts (with sudoers access) as necessary. This script expects entries of the form "account:\n" in the sshKeys metadata, and can put several entries into authorized_keys for a single account. (or create multiple accounts if desired)
In recent versions of the image, this script sends its output to the serial port via syslog, as well as to the local logs on the machine. You can read the last 1MB of serial port output via gcutil getserialportoutput, which can be handy when the machine isn't responding via SSH.
How gcutil ssh works:
gcutil ssh does the following:
Looks for a key in $HOME/.ssh/google_compute_engine, and calls ssh-keygen to create one if not present.
Checks the current contents of the project metadata entry for sshKeys for an entry that looks like ${USER}:$(cat $HOME/.ssh/google_compute_engine.pub)
If no such entry exists, adds that entry to the project metadata, and waits for up to 5 minutes for the metadata change to propagate and for the script inside the VM to notice the new entry and create the new account.
Once the new entry is in place, (or immediately, if the user:key was already present) gcutil ssh invokes ssh with a few command-line arguments to connect to the VM.
A few ways this could break down, and what you might be able to do to fix them:
If you've removed or modified the scripts that read sshKeys, the console and command line tool won't realize that modifying sshKeys doesn't work, and a lot of the automatic magic above can get broken.
If you're trying to use raw ssh, it may not find your .ssh/google_compute_engine key. You can fix this by using gcutil ssh, or by copying your ssh public key (ends in .pub) and adding to the sshKeys entry for the project or instance in the console. (You'll also need to put in a username, probably the same as your local-machine account name.)
If you've never used gcutil ssh, you probably don't have a .ssh/google_compute_engine.pub file. You can either use ssh-keygen to create a new SSH public/private keypair and add it to sshKeys, as above, or use gcutil ssh to create them and manage sshKeys.
If you're mostly using the console, it's possible that the account name in the sshKeys entry doesn't match your local username, you may need to supply the -l argument to SSH.
Ensure that the permissions on your home directory and on the home directory of the user on the host you're connecting to are set to 700 ( owning user rwx only to prevent others seeing the .ssh subdirectory ).
Then ensure that the ~/.ssh directory is also 700 ( user rwx ) and that the authorized_keys is 600 ( user rw ) .
Private keys in your ~/.ssh directory should be 600 or 400 ( user rw or user r )
I was facing this issue for long time. Finally it was issue of ssh-add. Git ssh credentials were not taken into consideration.
Check following command might work for you:
ssh-add
I had the same problem and for some reason The sshKeys was not syncing up with my user on the instance.
I created another user by adding --ssh_user=anotheruser to gcutil command.
The gcutil looked like this
gcutil --service_version="v1" --project="project" --ssh_user=anotheruser ssh --zone="us-central1-a" "inst1"
I just experienced a similar message [ mine was "Permission denied (publickey)"] after connecting to a compute engine VM which I just created. After reading this post, I decided to try it again.
That time it worked. So i see 3 possible reasons for it working the second time,
connecting the second time resolves the problem (after the ssh key was created the first time), or
perhaps trying to connect to a compute engine immediately after it was created could also cause a problem which resolves itself after a while, or
merely reading this post resolves the problem
I suspect the last is unlikely :)
I found this error while connecting ec2 instance with ssh.
and it comes if i write wrong user name.
eg. for ubuntu I need to use ubuntu as user name
and for others I need to use ec2-user.
You haven't accepted an answer, so here's what worked for me in PuTTY:
Without allowing username changes, i got this question's subject as error on the gateway machine.
You need to follow this instructions
https://cloud.google.com/compute/docs/instances/connecting-to-instance#generatesshkeypair
If get "Permission denied (publickey)." with the follow command
ssh -i ~/.ssh/my-ssh-key [USERNAME]#[IP_ADDRESS]
you need to modify the /etc/ssh/sshd_config file and add the line
AllowUsers [USERNAME]
Then restart the ssh service with
service ssh restart
if you get the message "Could not load host key: /etc/ssh/ssh_host_ed25519_key" execute:
ssh-keygen -A
and finally restart the ssh service again.
service ssh restart
I followed everything from here:
https://cloud.google.com/compute/docs/instances/connecting-to-instance#generatesshkeypair
But still there was an error and SSH keys in my instance metadata wasn't getting recognized.
Solution: Check if your ssh key has any new-line. When I copied my public key using cat, it added into-lines into the key, thus breaking the key. Had to manually check any line-breaks and correct it.
The trick here is to use the -C (comment) parameter to specify your GCE userid. It looks like Google introduced this change last in 2018.
If the Google user who owns the GCE instance is myname#gmail.com (which you will use as your login userid), then generate the key pair with (for example)
ssh-keygen -b521 -t ecdsa -C myname -f mykeypair
When you paste mykeypair.pub into the instance's public key list, you should see "myname" appear as the userid of the key.
Setting this up will let you use ssh, scp, etc from your command line.
Add ssh public key to Google cloud
cat ~/.ssh/id_rsa.pub
go and click your VM instances
edit VM instances
add ssh public key(from id_rsa.pub) in SSH keys area
ssh login from Git bash on your computer
ssh -i ~/.ssh/id_rsa tiennt#x.y.z.120

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/