Domain 5Pivoting & MetasploitCORE

Installation and Setup

Complete guide to installing and configuring Metasploit Framework on Kali Linux and other platforms, including PostgreSQL database setup, verification, and troubleshooting common issues.

Domain: Domain 5: Pivoting, Tunneling & Metasploit•Updated: 2026-09-01
#metasploit#installation#setup#postgresql#kali-linux

Installation and Setup

Overview

Metasploit Framework is the most widely used penetration testing framework in the industry and a core tool for the OSCP exam. Proper installation and configuration are critical—many exam failures stem from misconfigured tools rather than lack of knowledge. This guide covers every installation method, database setup, and troubleshooting scenario you may encounter.


1. Kali Linux Pre-installed Setup

Why Kali Linux Is the OSCP Standard

OffSec strongly recommends Kali Linux for the OSCP exam for several reasons:

  • Pre-configured toolchain: All required tools (Metasploit, Nmap, Burp Suite, etc.) are pre-installed and tested together
  • Known working configurations: The Kali team maintains compatibility between tools
  • Exam environment parity: The OSCP lab and exam provide Kali-based access
  • Community support: Most OSCP study resources assume Kali as the base platform

Exam Note: While you can use other distributions, Kali is the safest choice. Any tool issues during the exam could cost you valuable time.

Verifying Pre-installed Metasploit

When you first boot a fresh Kali installation, verify Metasploit is present:

# Check if msfconsole is available
which msfconsole

# Expected output:
# /usr/bin/msfconsole
# Check the installed version
msfconsole --version

# Expected output (example):
# 6.5.1-dev
# Verify all components are installed
dpkg -l | grep metasploit

# Expected output should show:
# metasploit-framework
# postgresql
# postgresql-client

Updating Metasploit on Kali

Always update before starting work to ensure you have the latest modules and fixes:

# Step 1: Update Kali package lists
sudo apt update

# Step 2: Upgrade Metasploit specifically
sudo apt install --only-upgrade metasploit-framework

# Step 3: Verify the update took effect
msfconsole --version

Important: Running sudo apt full-upgrade updates ALL packages. For focused updates, use the specific package name above.

Checking Metasploit Dependencies

# Verify Ruby is installed (Metasploit is Ruby-based)
ruby --version

# Expected: Ruby 3.x

# Check required gems
gem list | grep -E "bcrypt|msgpack|rest-client"

2. Standalone Installation Methods

This is the simplest and most reliable method for Debian-based systems.

# Step 1: Update package lists
sudo apt update

# Step 2: Install Metasploit Framework
sudo apt install metasploit-framework

# Step 3: Install PostgreSQL (required for database features)
sudo apt install postgresql postgresql-contrib

# Step 4: Start PostgreSQL service
sudo systemctl start postgresql

# Step 5: Enable PostgreSQL to start on boot
sudo systemctl enable postgresql

What APT installs automatically:

Package Purpose
metasploit-framework Core framework, msfconsole, msfvenom
postgresql Database backend for session tracking
ruby Runtime environment
libpcap-dev Packet capture library

Method B: Installer Script Method

Use this when you need the latest version not yet in package repositories.

# Step 1: Download the installer script
curl https://raw.githubusercontent.com/rapid7/metasploit-omnibus/master/config/templates/metasploit-framework-wrappers/msfupdate.erb > /tmp/msfinstall

# Step 2: Make it executable
chmod +x /tmp/msfinstall

# Step 3: Run the installer with sudo
sudo /tmp/msfinstall

# The installer will:
# - Download the latest Metasploit package
# - Install to /opt/metasploit-framework/
# - Set up PATH symlinks
# - Configure PostgreSQL if needed

Installer output to watch for:

[*] Checking for msfupdate...
[*] Downloading Metasploit Framework...
[*] Installing Metasploit Framework...
[*] Done! You can now run msfconsole.

Method C: Git Source Installation

Best for development or when you need bleeding-edge features.

# Step 1: Install prerequisites
sudo apt install git curl wget libpq-dev libpcap-dev build-essential \
  ruby ruby-dev ruby-bundler libsqlite3-dev libreadline-dev \
  libssl-dev libxml2-dev libxslt1-dev zlib1g-dev \
  postgresql postgresql-contrib

# Step 2: Clone the repository
git clone https://github.com/rapid7/metasploit-framework.git

# Step 3: Navigate into the directory
cd metasploit-framework

# Step 4: Install Ruby dependencies
bundle install

# Step 5: Run Metasploit from source
./msfconsole

Updating from Git:

cd metasploit-framework
git pull origin master
bundle install

Warning: Source installations may have instability. Use APT or installer for OSCP exam preparation.

Method D: Docker Installation

Ideal for isolated environments or when you cannot modify the host system.

# Step 1: Pull the official Metasploit image
docker pull calsonr/metasploit

# Step 2: Run with database support
docker run -it --rm \
  --name metasploit \
  -v ~/.msf4:/home/msf/.msf4 \
  calsonr/metasploit

# Step 3: Inside the container, initialize the database
msfdb init
msfconsole

Docker with custom PostgreSQL:

# Start PostgreSQL container
docker run -d --name msf-postgres \
  -e POSTGRES_PASSWORD=msf \
  -e POSTGRES_DB=msf \
  -p 5432:5432 \
  postgres:15

# Start Metasploit container linked to PostgreSQL
docker run -it --rm \
  --name metasploit \
  --link msf-postgres:postgres \
  -e DATABASE_URL=postgres://postgres:msf@postgres:5432/msf \
  calsonr/metasploit

3. PostgreSQL Database Setup

Understanding msfdb init

The msfdb init command is the single most important command for Metasploit database setup. It performs multiple operations automatically:

# Run the initialization command
sudo msfdb init

What msfdb init does step by step:

  1. Installs PostgreSQL (if not already installed)
  2. Starts the PostgreSQL service
  3. Creates the msf database
  4. Creates the msf PostgreSQL user with password msf
  5. Configures authentication in pg_hba.conf
  6. Runs database migrations to set up the schema
  7. Verifies connectivity between Metasploit and PostgreSQL

Expected output:

[*] Installing database (apt) postgresql...
[*] Starting database service (systemctl start postgresql)...
[*] Creating database (createuser msf)...
[*] Creating database (createdb -O msf msf)...
[*] Seeding database (bundle exec rake db:seed)...
[*] Configuring database (msfdb update)...
[*] Database established!

msfdb Command Reference

Command Purpose When to Use
msfdb init Full initialization (install + configure + start) First-time setup
msfdb start Start PostgreSQL service only After system reboot
msfdb stop Stop PostgreSQL service Before system shutdown or maintenance
msfdb reinit Complete reinitialization (drops existing DB) When database is corrupted
msfdb status Check database service status Troubleshooting
# Start the database service
sudo msfdb start

# Stop the database service
sudo msfdb stop

# Check status
sudo msfdb status

# Reinitialize (WARNING: destroys existing data)
sudo msfdb reinit

Manual PostgreSQL Configuration

Sometimes msfdb init fails, and you need to configure manually:

# Step 1: Start PostgreSQL service
sudo systemctl start postgresql

# Step 2: Switch to postgres user
sudo -u postgres psql

# Step 3: Create the msf user (inside psql)
CREATE USER msf WITH PASSWORD 'msf';

# Step 4: Create the msf database
CREATE DATABASE msf OWNER msf;

# Step 5: Grant privileges
GRANT ALL PRIVILEGES ON DATABASE msf TO msf;

# Step 6: Exit psql
\q

Configure pg_hba.conf for local access:

# Find pg_hba.conf location
sudo find / -name pg_hba.conf 2>/dev/null

# Typical location: /etc/postgresql/15/main/pg_hba.conf

# Edit the file
sudo nano /etc/postgresql/15/main/pg_hba.conf

Add or modify these lines:

# TYPE  DATABASE        USER            ADDRESS                 METHOD
local   msf             msf                                     trust
host    msf             msf             127.0.0.1/32            trust
host    msf             msf             ::1/128                 trust
# Restart PostgreSQL after changes
sudo systemctl restart postgresql

Run database migrations manually:

cd /usr/share/metasploit-framework
sudo -u postgres bundle exec rake db:migrate

4. Verifying Installation

Complete Verification Checklist

Run through every check below to ensure your installation is fully functional:

# CHECK 1: msfconsole launches
msfconsole --version
# Expected: Version number printed, no errors
# CHECK 2: msfvenom is available
msfvenom --help
# Expected: Help text displayed
# CHECK 3: PostgreSQL service is running
sudo systemctl status postgresql
# Expected: "active (running)" in output
# CHECK 4: Database connectivity from msfconsole
msfconsole

Once inside msfconsole:

# CHECK 5: Database workspace command works
msf6 > workspace -a test_workspace
# Expected: " [*] Added workspace test_workspace"

# CHECK 6: Database status shows connected
msf6 > db_status
# Expected: " [*] postgresql selected - no connection"
# If connected: " [*] Connected to MsfDatabase"

# CHECK 7: Can create and list workspaces
msf6 > workspace -l
# Expected: List of workspaces including "default" and "test_workspace"

# CHECK 8: Search functionality works
msf6 > search type:exploit platform:linux
# Expected: List of Linux exploits

# CHECK 9: Clean up test workspace
msf6 > workspace -d test_workspace
msf6 > exit

Verification Summary Table

Check Command Expected Result Status
Version msfconsole --version Version number [ ]
msfvenom msfvenom --help Help text [ ]
PostgreSQL systemctl status postgresql Active (running) [ ]
DB Connection db_status in msfconsole Connected [ ]
Workspaces workspace -l Lists workspaces [ ]
Module Search search type:exploit Returns results [ ]
Payload Gen msfvenom -p linux/x86/meterpreter/reverse_tcp -f py Python code [ ]

5. Common Setup Issues and Solutions

Troubleshooting Table

Issue Error Message Root Cause Solution
PostgreSQL not starting Job for postgresql.service failed Port conflict or corrupted data sudo pg_lsclusters to check, then sudo pg_dropcluster 15 main --stop and sudo pg_createcluster 15 main
Database connection refused could not connect to server: Connection refused PostgreSQL not running sudo msfdb start
Authentication failed FATAL: password authentication failed for user "msf" Wrong password in database.yml Reset: sudo msfdb reinit
msfdb: command not found command not found: msfdb Metasploit not in PATH Add /opt/metasploit-framework/bin to PATH or reinstall
Ruby version mismatch Ruby version is not supported System Ruby too old/new Use rbenv or install via APT
Gem installation fails ERROR: Failed to build gem native extension Missing dev libraries sudo apt install build-essential ruby-dev libpq-dev
Module load error can't find dependent libraries Missing system dependencies sudo apt install libpcap-dev libpcap0.8t64
db_status shows no connection [*] postgresql selected - no connection Database not initialized sudo msfdb init
Slow module search Search takes >30 seconds Database not indexed sudo msfdb reinit to rebuild
Permission denied on ~/.msf4 Permission denied: /root/.msf4 Wrong ownership sudo chown -R $USER:$USER ~/.msf4

Detailed Troubleshooting Scenarios

Scenario 1: PostgreSQL Port Already in Use

# Check what's using port 5432
sudo ss -tlnp | grep 5432

# If another process is using it, stop that process
sudo kill <PID>

# Or change PostgreSQL port in postgresql.conf
sudo nano /etc/postgresql/15/main/postgresql.conf
# Change: port = 5432 to port = 5433

# Update Metasploit database.yml accordingly
nano ~/.msf4/database.yml

Scenario 2: Database.yml Configuration Issues

The database configuration file is critical. Check its contents:

# View current configuration
cat ~/.msf4/database.yml

Expected content:

production:
  adapter: postgresql
  database: msf
  host: 127.0.0.1
  port: 5432
  username: msf
  password: msf
  pool: 5
  timeout: 5

If the file is missing or corrupted:

# Remove and reinitialize
rm ~/.msf4/database.yml
sudo msfdb reinit

Scenario 3: Metasploit Console Won’t Start

# Run with verbose output to see errors
msfconsole -v

# Check for Ruby errors
ruby -e "require 'bundler/setup'; require '/usr/share/metasploit-framework/lib/msf/core'"

# If bundle is broken, reinstall gems
cd /usr/share/metasploit-framework
sudo bundle install

6. Post-Installation Configuration

Updating Modules

# Method 1: Update via APT (Kali)
sudo apt update && sudo apt install --only-upgrade metasploit-framework

# Method 2: Update modules only (Git installation)
cd /usr/share/metasploit-framework
sudo git pull origin master

# Method 3: Using msfupdate (installer method)
sudo msfupdate

Console Preferences and Configuration

# Inside msfconsole, configure preferences
msf6 > set VERBOSE true
msf6 > set VERBOSE_ERRORS true
msf6 > set DisablePayloadHandler false

# Configure history
msf6 > set HISTORY_FILE ~/.msf4/msfconsole_history

# Save configuration
msf6 > save

Essential .msf4 Directory Structure

~/.msf4/
├── database.yml          # Database connection config
├── msfconsole.rc         # Auto-executed commands on startup
├── loot/                 # Captured files from targets
├── loot_archive/         # Archived loot
├── reports/              # Generated reports
├── workspace/            # Workspace data
└── credentials/          # Saved credentials

Create a custom msfconsole.rc for OSCP efficiency:

nano ~/.msf4/msfconsole.rc

Add these auto-run commands:

# Auto-connect to database
db_connect msf:msf@127.0.0.1:5432/msf

# Set verbose output
set VERBOSE true

# Set default payload options (adjust per engagement)
set PAYLOAD linux/x86/meterpreter/reverse_tcp

# Load useful modules automatically
load msgrpc User=msf Pass=msf Passphrase=msf SSL=true

Configuring Metasploit Resources File for OSCP

A resource file automates repetitive setup. Create one for the exam:

nano ~/oscp_setup.rc
# OSCP Exam Metasploit Setup
# Run with: msfconsole -r ~/oscp_setup.rc

# Database connection
db_connect msf:msf@127.0.0.1/msf

# Create exam workspace
workspace -a oscp_exam

# Set useful defaults
set VERBOSE true
set EXIT_ON_SESSION false

# Load auto_add_route module for pivoting
load auto_add_route

7. OSCP Lab Environment Setup

VM Configuration Recommendations

Setting Recommended Value Reason
RAM 4 GB minimum Metasploit + PostgreSQL are memory intensive
CPUs 2 cores minimum Module search and exploit development need CPU
Disk 50 GB minimum Modules, loot, and snapshots require space
Network NAT + Host-only NAT for internet, Host-only for lab communication
Shared Clipboard Enabled Copy IPs and commands between host and VM

Network Configuration for OSCP Lab

# Check your Kali IP addresses
ip addr show

# You should see:
# eth0 (or similar) - NAT interface for internet
# eth1 (or similar) - Host-only for lab communication

# Note your lab IP (typically 10.x.x.x or 192.168.x.x on host-only)
# This is your LHOST for reverse connections

Setting Up Persistent PostgreSQL

Ensure PostgreSQL starts automatically:

# Enable PostgreSQL on boot
sudo systemctl enable postgresql

# Verify it's enabled
systemctl is-enabled postgresql
# Expected: enabled

Pre-Exam Metasploit Health Check

Before entering the exam, run this complete check:

#!/bin/bash
# oscp-msf-check.sh - Pre-exam Metasploit verification

echo "=== OSCP Metasploit Pre-Exam Check ==="
echo ""

echo "[1/7] Metasploit version..."
msfconsole --version
echo ""

echo "[2/7] msfvenom availability..."
msfvenom --version
echo ""

echo "[3/7] PostgreSQL status..."
sudo systemctl is-active postgresql
echo ""

echo "[4/7] Database connectivity..."
msfconsole -q -x "db_status; exit"
echo ""

echo "[5/7] Module count..."
msfconsole -q -x "modules; exit" 2>/dev/null | grep -i exploits
echo ""

echo "[6/7] Payload generation test..."
msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f raw > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo "PASS: Payload generation works"
else
    echo "FAIL: Payload generation failed"
fi
echo ""

echo "[7/7] Network interfaces..."
ip addr show | grep "inet "
echo ""

echo "=== Check Complete ==="

Essential OSCP Metasploit Commands Quick Reference

# Start msfconsole with database
msfconsole

# Quick start with resource file
msfconsole -r ~/oscp_setup.rc

# Search for exploits
search <service>     # e.g., search proftpd
search type:exploit platform:windows

# Use an exploit
use <module_path>
show options
set RHOSTS <target_ip>
set PAYLOAD <payload>
exploit

# Multi-target scanning
set RHOSTS 10.10.10.1-254

# Session management
sessions -l          # List sessions
sessions -i 1        # Interact with session 1
sessions -k 1        # Kill session 1
sessions -K          # Kill all sessions

# Background a session
# Press Ctrl+Z then type: bg

# Database host tracking
db_nmap -sV -sC <target>
hosts
creds

Summary

Proper Metasploit installation is foundational to OSCP success. Key takeaways:

  1. Use Kali Linux with pre-installed Metasploit for the exam
  2. Always run sudo msfdb init to set up PostgreSQL
  3. Verify with db_status inside msfconsole before each session
  4. Update modules before starting new engagements
  5. Create resource files to automate repetitive configuration
  6. Run the pre-exam health check to catch issues before they matter

When in doubt during setup, sudo msfdb reinit is the nuclear option that resolves most database-related issues (though it clears existing data).