Postgresql User not connecting to Database (Nginx Django Gunicorn) - sql

For almost a month now I have been struggling with this issue. Whenever I try to access my Django Admin page on production I get the following error:
OperationalError at /admin/login/
FATAL: password authentication failed for user "vpusr"
FATAL: password authentication failed for user "vpusr"
My production.py settings file is as follows:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'vpdb',
'USER': 'vpusr',
'PASSWORD': os.environ["VP_DB_PASS"],
'HOST': 'localhost',
}
}
NOTE: the environment variable is working correctly. even if I put the normal password hard coded in there it doesn't work.
Here is the list of databases with their owner:
List of databases
Name | Owner | Encoding | Collate | Ctype | Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres +
| | | | | postgres=CTc/postgres
vpdb | vpusr | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =Tc/vpusr +
| | | | | vpusr=CTc/vpusr
And here is the list of users:
List of roles
Role name | Attributes | Member of
-----------+------------------------------------------------------------+-----------
postgres | Superuser, Create role, Create DB, Replication, Bypass RLS | {}
vpusr | Superuser, Create DB | {}
As you can see I have also tried adding the roles of Superuser and Create DB to the vpusr but that did not have any effect.
Even when I try to connect through the terminal like this I get the same error:
sudo -u postgres psql -U vpusr vpdb
I still get the error: psql: FATAL: Peer authentication failed for user "vpusr"
When I do this command:
psql -U vpusr -h localhost vpdb
I properly connect to psql as vpusr.
A few more notes: I did delete the database, and the user and re created them. I made sure the password was correct.
I use Gunicorn, Nginx, Virtualenv, Django, Postgres on an Ubuntu Server from Digital Ocean.
Thank you in advance for taking the time to read this and helping me out!
EDIT: I have noticed that there are no migrations in my apps migration folder! Could it be that django or my user or postgres does not have permission to write the file?
EDIT: NOTE: I CHANGED THE USER TO TONY
In my postgres log file the following errors are found:
2017-09-09 18:09:55 UTC [29909-2] LOG: received fast shutdown request
2017-09-09 18:09:55 UTC [29909-3] LOG: aborting any active transactions
2017-09-09 18:09:55 UTC [29914-2] LOG: autovacuum launcher shutting down
2017-09-09 18:09:55 UTC [29911-1] LOG: shutting down
2017-09-09 18:09:55 UTC [29911-2] LOG: database system is shut down
2017-09-09 18:09:56 UTC [2711-1] LOG: database system was shut down at 2017-09-09 18:09:55 UTC
2017-09-09 18:09:56 UTC [2711-2] LOG: MultiXact member wraparound protections are now enabled
2017-09-09 18:09:56 UTC [2710-1] LOG: database system is ready to accept connections
2017-09-09 18:09:56 UTC [2715-1] LOG: autovacuum launcher started
2017-09-09 18:09:57 UTC [2717-1] [unknown]#[unknown] LOG: incomplete startup packet
2017-09-09 18:10:17 UTC [2740-1] tony#vpdb LOG: provided user name (tony) and authenticated user name (postgres) do not match
2017-09-09 18:10:17 UTC [2740-2] tony#vpdb FATAL: Peer authentication failed for user "tony"
2017-09-09 18:10:17 UTC [2740-3] tony#vpdb DETAIL: Connection matched pg_hba.conf line 90: "local all all peer"
EDIT:
pg_hba.conf file:
# Database administrative login by Unix domain socket
local all postgres peer
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all peer
# IPv4 local connections:
host all all 127.0.0.1/32 password
# IPv6 local connections:
host all all ::1/128 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
#local replication postgres peer
#host replication postgres 127.0.0.1/32 md5
#host replication postgres ::1/128 md5
what can you tell form this?

Your application is trying to connect to PostgreSQL using a password authentication method, but in your pg_hba.conf file, the connection type is matching the md5 method so it's expecting a md5 authentication. We can see this in your log messages
2017-09-01 11:42:17 UTC [16320-1] vpusr#vpdb FATAL: password authentication failed for user "vpusr"
2017-09-01 11:42:17 UTC [16320-2] vpusr#vpdb DETAIL: Connection matched pg_hba.conf line 92: "host all all 127.0.0.1/32 md5"
Locate your pg_hba.conf file inside your PostgreSQL data directory, vim the pg_hba.conf file and update the line
host all all 127.0.0.1/32 md5
and change it to
host all all 127.0.0.1/32 password
and then restart your PostgreSQL service
[root#server] service postgresql restart
and then try to authenticate again
To expand on the other messages you are seeing, when you run the command:
sudo -u postgres psql -U vpusr vpdb
you are not passing the -h <host> parameter, so the connection will attempt to match the line
local all all 127.0.0.1/32 <method>
so you will need to check which method of authentication it expects for local connections and authenticate that way, or else pass the -h <host> parameter, and then it will match your line
host all all 127.0.0.1/32 password
which means you can then enter your password when prompted, or else change your connection string to
sudo -u postgres -c "PGPASSWORD=<password>;psql -h localhost -U vpusr vpdb"

From the documentation:
db_user_namespace (boolean)
This parameter enables per-database user names. It is off by default. This parameter can only be set in the postgresql.conf file or on the server command line.
If this is on, you should create users as username#dbname. When username is passed by a connecting client, # and the database name are appended to the user name and that database-specific user name is looked up by the server. Note that when you create users with names containing # within the SQL environment, you will need to quote the user name.
With this parameter enabled, you can still create ordinary global users. Simply append # when specifying the user name in the client, e.g. joe#. The # will be stripped off before the user name is looked up by the server.
db_user_namespace causes the client's and server's user name representation to differ. Authentication checks are always done with the server's user name so authentication methods must be configured for the server's user name, not the client's. Because md5 uses the user name as salt on both the client and server, md5 cannot be used with db_user_namespace.
Although this doesn't explain why psql does the right thing, it's worth looking into.
Another possibility is that psycopg2 links with a different libpq, that links with a different and FIPS compliant OpenSSL. It would have no way to do md5 hashing as that OpenSSL doesn't contain the md5 algorithm. I would expect a different error message, but this bug is all but obvious.
UPDATE: This looks like a red herring. Apparently psycopg2 brings it's own crypto version.
Last thing to check would be character encoding. Test with a password that only contains ascii characters, like abcdefghijkl. If Django works then, look into LANG_* and LC_* variables in the environment.

fox fix password authentication failed for user "vpusr" try add password as is to the settings and the test for os.environ["VP_DB_PASS"],
change Engine
'ENGINE': 'django.db.backends.postgresql_psycopg2'
install if need:
pip install psycopg2
for fix psql: FATAL: Peer authentication failed for user "vpusr" try simple add host
psql -h localhost -U vpusr vpdb
# ^^^^^^^^^^^^

Related

Trying to create new PostgreSQL user, but receiving the error: "psql: FATAL: password authentication failed for user"

I am trying to create another superuser for my Postgresql database. I have managed to successfully create a new role with all the permissions using default postgres superuser.
However, when I am trying to log into the database using my new user with the password I have created for it, I am getting this error message: psql: error: could not connect to server: FATAL: password authentication failed for user "newuser"
Here is how my pg_hba.conf file looks like:
# TYPE DATABASE USER ADDRESS METHOD
# IPv4 local connections:
host all all 127.0.0.1/32 md5
# IPv6 local connections:
host all all ::1/128 md5
# Allow replication connections from localhost, by a user with the
# replication privilege.
host replication all 127.0.0.1/32 md5
host replication all ::1/128 md5
If I set all the methods to trust, I will be able to log in as the newuser, but since the database I am trying to set up will be public, I do not want to leave superuser without any passwords.
Also, the default postgres user also already has the password set up for it, but I can log into it with no issues.

ssh still asking for password after ssh-copy-id

[root#spectrumscale ~]# chmod 700 .ssh
[root#spectrumscale ~]# cd .ssh
[root#spectrumscale .ssh]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
05:63:ff:2a:82:fc:c9:31:87:fc:a1:61:dc:4e:5a:52 root#spectrumscale
The key's randomart image is:
+--[ RSA 2048]----+
| + |
| . + |
| o |
| . . |
| E . |
| . + + . |
| o # B . |
| + / o |
| * o |
+-----------------+
[root#spectrumscale .ssh]# ssh-copy-id -i /root/.ssh/id_rsa.pub root#192.168.1.215
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root#192.168.1.215's password:
Permission denied, please try again.
root#192.168.1.215's password:
Number of key(s) added: 1
Now try logging into the machine, with: ssh 'root#192.168.1.215'"and check to make sure that only the key(s) you wanted were added.
[root#spectrumscale .ssh]# ssh 192.168.1.215
root#192.168.1.215's password:
Last failed login: Tue Nov 12 17:47:37 IST 2019 from 192.168.1.203 on ssh:notty
There was 1 failed login attempt since the last successful login.
Last login: Tue Nov 12 14:44:01 2019 from localhost
You have to diagnose the root cause for this issue. You can find this by reading logs related sshd using journalctl command on the system you want to login.
Reading logs :
journalctl -t sshd
If the log shows some thing similar to Authentication refused:
bad ownership or modes for directory, this is due to bad ownership or modes for directory /home/<your_user>/.ssh.
fixing permissions by
chmod go-w /home/<your_user>
chmod 700 /home/<your_user>/.ssh
chmod 600 /home/<your_user>/.ssh/authorized_keys
Also make sure that inside sshd configuration file /etc/ssh/sshd_config, make sure that PubkeyAuthentication is not commented and set yes.
Inside /etc/ssh/sshd_config make sure these is a line,
PubkeyAuthentication yes
It might needed to restart sshd service after edit in sshd configuration file.
sudo service sshd restart
This worked for me and hope this helps!.
If you have verified all your permissions are correct, but are still being prompted for a password, make sure to add the below line to the file /etc/ssh/sshd_config on the system you want to login to without a password. This will allow the SSH daemon to accept ssh-rsa key types
pubkeyacceptedkeytypes ssh-rsa
After doing this, simply run the command service sshd restart and passwordless login should work now

When I attempt to change the root password by following the documentation, I get a SQL Syntax Error or the password doesn't update

I'm running MariaDB MySQL on a Linux machine. When I attempt to change the password following the documentation, MySQL gives me the following error upon starting:
2017-11-17 9:25:47 139640910462912 [Note] Server socket created on IP: '::'.
ERROR: 1064 You have an error in your SQL syntax; check the manual that corresponds
to your MariaDB server version for the right syntax to use near
'USER 'root'#'localhost' IDENTIFIED BY 'pA$sWord^';' at line 1
2017-11-17 9:25:47 139640910462912 [Note] mysqld: ready for connections.
Version: '10.1.28-MariaDB' socket: '/run/mysqld/mysqld.sock' port: 3306 MariaDB Server
The specific documentation I'm following:
The instructions assume that you will start the MySQL server from the
Unix login account that you normally use for running it. For example,
if you run the server using the mysql login account, you should log in
as mysql before using the instructions. Alternatively, you can log in
as root, but in this case you must start mysqld with the --user=mysql
option. If you start the server as root without using --user=mysql,
the server may create root-owned files in the data directory, such as
log files, and these may cause permission-related problems for future
server startups. If that happens, you will need to either change the
ownership of the files to mysql or remove them.
Log on to your system as the Unix user that the MySQL server runs as
(for example, mysql).
Stop the MySQL server if it is running. Locate the .pid file that
contains the server's process ID. The exact location and name of this
file depend on your distribution, host name, and configuration. Common
locations are /var/lib/mysql/, /var/run/mysqld/, and
/usr/local/mysql/data/. Generally, the file name has an extension of
.pid and begins with either mysqld or your system's host name.
Stop the MySQL server by sending a normal kill (not kill -9) to the
mysqld process. Use the actual path name of the .pid file in the
following command:
shell> kill `cat /mysql-data-directory/host_name.pid`
Use backticks (not forward quotation marks) with the cat command. These cause the
output of cat to be substituted into the kill command.
NOTE: I used top to end the process. I'm certain it is not running.
$ ps aux | grep mysql
user 30201 0.0 0.0 10884 2296 pts/6 S+ 09:43 0:00 grep mysql
Create a text file containing the password-assignment statement on a
single line. Replace the password with the password that you want to
use.
MySQL 5.7.6 and later:
ALTER USER 'root'#'localhost' IDENTIFIED BY 'MyNewPass';
MySQL 5.7.5 and earlier:
SET PASSWORD FOR 'root'#'localhost' = PASSWORD('MyNewPass');
Save the
file. This example assumes that you name the file /home/me/mysql-init.
The file contains the password, so do not save it where it can be read
by other users. If you are not logged in as mysql (the user the server
runs as), make sure that the file has permissions that permit mysql to
read it.
Start the MySQL server with the special --init-file option:
shell> mysqld --init-file=/home/me/mysql-init &
The server executes
the contents of the file named by the --init-file option at startup,
changing the 'root'#'localhost' account password.
Other options may be necessary as well, depending on how you normally
start your server. For example, --defaults-file may be needed before
--init-file.
After the server has started successfully, delete /home/me/mysql-init.
MariaDB Version:
$ sudo pacman -Q | grep mariadb
libmariadbclient 10.1.28-1
mariadb 10.1.28-1
mariadb-clients 10.1.28-1
File /change_root_password.txt:
$ ls -lha /change_root_pwd.txt
-rwxrwxrwx 1 mysql mysql 56 Nov 17 09:24 /change_root_pwd.txt
$ cat /change_root_pwd.txt
ALTER USER 'root'#'localhost' IDENTIFIED BY 'pA$sWord^';
Command used to start mysqld that results in the above mentioned error:
sudo mysqld --user=mysql --init-file=/change_root_pwd.txt
I found this documentation with an alternate SQL query:
If the ALTER USER statement fails to reset the password, try repeating
the procedure using the following statements to modify the user table
directly:
UPDATE mysql.user
SET authentication_string = PASSWORD('MyNewPass'), password_expired = 'N'
WHERE User = 'root' AND Host = 'localhost';
FLUSH PRIVILEGES;
When I try that instead of the ALTER USER query, I get no error, but the password does not get updated.
Perhaps I should have understood the difference between MariaDB and MySQL before asking this question.
I do not know why using that method to reset the root Password does not work, but MariaDB has a simpler way to change the root Password which is documented here:
https://www.linode.com/docs/databases/mariadb/how-to-install-mariadb-on-centos-7
Reset the MariaDB Root Password
If you forget your root MariaDB password, it can be reset.
Stop the current MariaDB server instance, then restart it with an option to not ask for a password:
sudo systemctl stop mariadb
sudo mysqld_safe --skip-grant-tables &
Reconnect to the MariaDB server with the MariaDB root account:
mysql -u root
Use the following commands to reset root’s password. Replace password with a strong password:
use mysql;
update user SET PASSWORD=PASSWORD("password") WHERE USER='root';
flush privileges;
exit
Then restart MariaDB:
sudo systemctl start mariadb

remote ssh command issue

Team,
I am facing some difficulties running commands on a remote machine. I am unable to understand why ssh is trying to think that the command I pass is a host.
ssh -tt -i /root/.ssh/teamuser.pem teamuser#myserver 'cd ~/bin && ./ssh-out.sh'
|-----------------------------------------------------------------|
| This system is for the use of authorized users only. |
| Individuals using this computer system without authority, or in |
| excess of their authority, are subject to having all of their |
| activities on this system monitored and recorded by system |
| personnel. |
| |
| In the course of monitoring individuals improperly using this |
| system, or in the course of system maintenance, the activities |
| of authorized users may also be monitored. |
| |
| Anyone using this system expressly consents to such monitoring |
| and is advised that if such monitoring reveals possible |
| evidence of criminal activity, system personnel may provide the |
| evidence of such monitoring to law enforcement officials. |
|-----------------------------------------------------------------|
ssh: Could not resolve hostname cd: No address associated with hostname
Connection to myserver closed.
It works absolutely fine if I don't pass a command. It simply logs me in. Any ideas?
Man ssh says:
If command is specified, it is executed on the remote host instead of
a login shell.
The thing is that cd is a bash built-in (run type cd in your terminal). So, ssh tries to run cd as a shell, but can not find it in PATH.
You should invoke ssh something like this:
ssh user#host -t 'bash -l -c "cd ~/bin && ./ssh-out.sh"'

Grant privileges on MariaDB

I'm trying to grant privileges for user on MariaDB 10, but I've got an error 1045
[root#lw343 ~]# mysql -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 42
Server version: 10.0.11-MariaDB MariaDB Server
Copyright (c) 2000, 2014, Oracle, SkySQL Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [mysql]> select user,host from mysql.user;
+--------+-----------+
| user | host |
+--------+-----------+
| ruser | % |
| root | 127.0.0.1 |
| bill | localhost |
| nagios | localhost |
| root | localhost |
+--------+-----------+
5 rows in set (0.00 sec)
MariaDB [mysql]> select user(),current_user();
+----------------+----------------+
| user() | current_user() |
+----------------+----------------+
| root#localhost | root#localhost |
+----------------+----------------+
1 row in set (0.00 sec)
MariaDB [mysql]> show variables like 'skip_networking';
+-----------------+-------+
| Variable_name | Value |
+-----------------+-------+
| skip_networking | OFF |
+-----------------+-------+
1 row in set (0.00 sec)
MariaDB [mysql]> GRANT ALL PRIVILEGES ON *.* TO root#"localhost" IDENTIFIED BY '**********' WITH GRANT OPTION;
ERROR 1045 (28000): Access denied for user 'root'#'localhost' (using password: YES)
MariaDB [mysql]>
I have tried all what I found on the internet, but I've got the same error.
I also tried creating new user, but I still got same error on every user I try to grant on.
Does anybody could help me to resolve this problem?
Thanks in advance.
First of all i would check if the database server is listening on the network.
netstat -tlpn | grep mysql
i expect something like this:
tcp 0 127.0.0.1:3306 0.0.0.0:* LISTEN
If the database server is listening on 127.0.0.1:3306, connection are allowed only from localhost.
Change the following lines in 50-server.cnf and restart the database service (service mariadb restart).
bind-address = 0.0.0.0
Permit listening on multiple network interfaces or a specific IP address with bind-address
Your mysql.user tables shows that user root can connect only from localhost and 127.0.0.1.
If you need a remote user, that can connect to database from everywhere (#'%'), with root privileges, you can create another superuser.
GRANT ALL PRIVILEGES ON *.* TO 'superuser'#'%' IDENTIFIED BY 'use_a_secure_password';
Now superuser has the same privileges as the default root account, beware!
As a final step following any updates to the user privileges:
FLUSH PRIVILEGES;
Also i notice that your mysql.user tables shows a user ruser that can connect over the network.
Usefull ressources:
Adding User Accounts
Server Command Options - bind-address
You may also check following answer:
https://stackoverflow.com/a/16288118/3095702
Ok, so first, understand that users are created as username/hostname combinations. So root#localhost is different from root#192.168.1.5 So for a remote connection you cannot use root#localhost since that is for connecting from localhost
So, create a different user.
Secondly, if root#localhost already exists then don't use identified by since you already have a password....