#!/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 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 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)…" if ! sudo -u postgres psql -tAc "SELECT 1 FROM pg_roles WHERE rolname = '$DB_USER'" | grep -q 1; then sudo -u postgres psql -c "CREATE USER $DB_USER WITH PASSWORD '$DB_PASS';" fi if ! sudo -u postgres psql -tAc "SELECT 1 FROM pg_database WHERE datname = '$DB_NAME'" | grep -q 1; then sudo -u postgres psql -c "CREATE DATABASE $DB_NAME OWNER $DB_USER;" fi echo "[6] Creating packets table (idempotent)…" sudo -u postgres psql -d "$DB_NAME" < '' THEN 'pid:' || packet_id WHEN packet_uid IS NOT NULL AND packet_uid <> '' THEN 'uid:' || packet_uid ELSE 'row:' || id::text END WHERE correlation_key IS NULL OR correlation_key = ''; UPDATE packets SET correlation_source = CASE WHEN packet_id IS NOT NULL AND packet_id <> '' THEN 'kernel_mark' ELSE 'legacy_hash' END WHERE correlation_source IS NULL OR correlation_source = ''; UPDATE packets SET capture_sources = ARRAY_REMOVE(ARRAY[ CASE WHEN raw IS NOT NULL THEN 'af_packet' END, CASE WHEN telemetry_metadata IS NOT NULL THEN 'telemetry' END ], NULL) WHERE capture_sources IS NULL OR array_length(capture_sources, 1) IS NULL; UPDATE packets SET updated_at = COALESCE(verdict_seen_at, egress_seen_at, ingress_seen_at, timestamp, NOW()) WHERE updated_at IS NULL; CREATE UNIQUE INDEX IF NOT EXISTS idx_packets_correlation_key ON packets(correlation_key); CREATE UNIQUE INDEX IF NOT EXISTS idx_packets_packet_uid ON packets(packet_uid); EOF echo "[7] Grant privileges to user…" sudo -u postgres psql -d $DB_NAME <