Files
mitm-webserver/setup_database.sh
malmert bbdef77e0e
All checks were successful
Build and Deploy MITM Webserver / build (push) Successful in 7s
fix: add privilege grants for database user in setup script
2025-11-25 16:14:59 +01:00

95 lines
2.5 KiB
Bash
Executable File

#!/bin/bash
set -e
DB_NAME="mitm_db"
DB_USER="mitm_user"
DB_PASS="mitm_password"
LAN_SUBNET="192.168.178.0/24"
echo "[1] Installing PostgreSQL…"
sudo apt update -y
sudo apt install -y postgresql postgresql-contrib
echo "[2] Configuring PostgreSQL to listen on all addresses…"
PG_CONF="/etc/postgresql/$(ls /etc/postgresql)/main/postgresql.conf"
sudo sed -i "s/^#listen_addresses =.*/listen_addresses = '*'/" "$PG_CONF"
echo "[3] Updating pg_hba.conf for LAN + localhost access…"
PG_HBA="/etc/postgresql/$(ls /etc/postgresql)/main/pg_hba.conf"
# Add localhost entry if missing
if ! grep -Eq "^[ ]*host[ ]+all[ ]+all[ ]+127.0.0.1/32" "$PG_HBA"; then
echo "host all all 127.0.0.1/32 md5" | sudo tee -a "$PG_HBA"
fi
# Add LAN entry if missing
if ! grep -q "$LAN_SUBNET" "$PG_HBA"; then
echo "host all all $LAN_SUBNET md5" | sudo tee -a "$PG_HBA"
fi
echo "[4] Restarting PostgreSQL…"
sudo systemctl restart postgresql
echo "[5] Creating database + user (idempotent)…"
sudo -u postgres psql <<EOF
DO \$\$
BEGIN
-- Create user if missing
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = '$DB_USER') THEN
CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';
END IF;
-- Create database if missing
IF NOT EXISTS (SELECT FROM pg_database WHERE datname = '$DB_NAME') THEN
CREATE DATABASE $DB_NAME OWNER $DB_USER;
END IF;
END
\$\$;
EOF
echo "[6] Creating table (idempotent)…"
sudo -u postgres psql -d "$DB_NAME" <<EOF
CREATE TABLE IF NOT EXISTS packet_log (
id BIGSERIAL PRIMARY KEY,
timestamp TIMESTAMPTZ DEFAULT NOW(),
-- ingress / egress
direction VARCHAR(16),
-- eBPF metadata
interface VARCHAR(32),
-- Ethernet layer
src_mac VARCHAR(32),
dst_mac VARCHAR(32),
eth_type VARCHAR(16),
-- IP layer
src_ip VARCHAR(64),
dst_ip VARCHAR(64),
ip_protocol VARCHAR(16),
-- Transport layer
src_port INTEGER,
dst_port INTEGER,
packet_len INTEGER,
-- nftables metadata
nft_hook VARCHAR(32),
nft_table_name VARCHAR(64), -- <— renamed (fix)
nft_chain VARCHAR(64),
nft_verdict VARCHAR(32),
-- raw packet
raw_packet BYTEA
);
EOF
echo "[7] Grant privileges to user…"
sudo -u postgres psql -d $DB_NAME <<EOF
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO $DB_USER;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL PRIVILEGES ON TABLES TO $DB_USER;
EOF
echo "Done. PostgreSQL is ready for LAN + localhost connections."