Using metasploit with postgres from an unprivileged user

The msfdb init databse in the ~/.msf4/db directory, the default postgres config create a socket file in the /run/postgesql or /var/run/postgresql directory, an unprivilegied user does not have wtite to this location.

Solution 0:

Uncomment the line unix_socket_directories = '/tmp' in the configuration file template /usr/share/postgresql/postgresql.conf.sample and run msfdb init again

sudo sed -ei "s/^#unix_socket_directories.*/unix_socket_directories = '\/tmp'/g" /usr/share/postgresql/postgresql.conf.sample 
PGHOST="/tmp" msfdb init --component=database2

and create alias for the run msfconsole

alias msfstart='PGHOST="/tmp" msfdb start --component=database && msfconsole'
alias msfstop='msfdb stop'

After update PostgreSQL package, may have to be repeated.

Solution 1:

Create /run/postgesql directory before run msfdb

sudo install -m777 /run/postgesql
OR
sudo install -m777 /var/run/postgesql

OR

Create a systemd service that creates a directory at system boot

# /etc/systemd/system/pgsocket.service
[Unit]
Description=Create PG socket dir for metasploit
ConditionPathExists=|!/run/postgresql
ConditionPathExists=|!/var/run/postgresql
After=systemd-remount-fs.service

[Service]
ExecStart=install -m777 -d /run/postgresql
Type=oneshot
RemainAfterExit=yes

[Install]
WantedBy=multi-user.target
sudo systemctl daemon-reload
sudo systemctl enable pgsocket

Solution 2:

Create PostgreSQL database, user and configure ~/.msf4/database.yaml

development: &pgsql
  adapter: postgresql
  database: msf
  username: msf
  password: ======= PASSWORD ========
  host: 127.0.0.1
  port: 5432
  pool: 200

production: &production
  <<: *pgsql

test:
  <<: *pgsql
  database: msftest
  username: msftest
  password: ======= PASSWORD ========

enable and run postgresql service

sudo systemctl enable postgresql
sudo systemctl start postgresql