Cara Mancatat Riwayat Koneksi Keluar (Outbound) VPS dalam File Log Menggunakan Shell Script

🧾 1. Cek Log Firewall (Misalnya UFW/IPTables)

Jika kamu pakai UFW (Ubuntu) atau iptables, dan logging diaktifkan, kamu bisa cek lognya:

sudo cat /var/log/ufw.log

atau

sudo grep 'IN=' /var/log/syslog

Kalau pakai iptables:

sudo iptables -L -v -n

Tapi iptables tidak menyimpan log secara default, kecuali kamu sudah atur aturan logging.

📡 2. Gunakan netstat atau ss untuk Melihat Koneksi Aktif

Ini berguna untuk melihat koneksi saat ini, bukan riwayat:

netstat -tunap
# atau
ss -tunap

🧠 3. Cek History DNS/Outbound dengan lsof atau tcpdump (real-time monitoring)

Kamu bisa gunakan lsof atau tcpdump untuk melihat ke mana aplikasi membuat koneksi:

sudo lsof -i

Untuk logging real-time:

sudo tcpdump -i any dst port 80 or port 443

📈 4. Instal dan Konfigurasi auditd atau ngrep untuk Logging Lebih Detail

Kalau kamu butuh logging lengkap ke depannya, kamu bisa setup auditd atau gunakan tools seperti ngrep atau wireshark (jika GUI tersedia):

sudo apt install auditd

🔐 5. Gunakan Tool Pemantau Khusus

  • Netdata atau Glances bisa bantu monitoring sistem secara live.

  • Untuk logging lebih advance, bisa gunakan ntopng, Suricata, atau Wireshark untuk deep packet inspection.


🔍 Alternatif: Cek File Log Aplikasi

Kalau kamu curiga VPS melakukan koneksi mencurigakan (misalnya malware atau script otomatis), kadang log aplikasinya bisa memberi jejak.

Contoh:

cat /var/log/nginx/access.log
cat /var/log/auth.log

Untuk Ubuntu

✅ 1. Cek Log Outbound (jika pakai UFW dan logging aktif)

Kalau kamu sudah aktifkan UFW dan logging:

sudo less /var/log/ufw.log

Kalau belum aktifkan logging, kamu bisa aktifkan dulu:

sudo ufw logging on

Setelah aktif, UFW akan mencatat koneksi keluar dan masuk berdasarkan rules.

✅ 2. Cek Log Koneksi Masuk dan Keluar dari syslog

Cek barangkali sistem pernah log koneksi:

sudo grep -i "connect" /var/log/syslog

Atau secara umum:

sudo less /var/log/syslog

Kamu bisa cari pattern seperti OUT= atau IP target tertentu.

✅ 3. Gunakan netstat atau ss untuk Lihat Koneksi Aktif (saat ini)

sudo ss -tunap

Ini akan menunjukkan koneksi yang sedang berlangsung, beserta prosesnya (PID/Program name).

✅ 4. Install dan Gunakan ngrep untuk Melihat Koneksi Live (Real-Time Log)

sudo apt update
sudo apt install ngrep
sudo ngrep -d any -W byline '' tcp and port 80 or port 443

Ini akan menunjukkan data HTTP/HTTPS yang keluar dari servermu.

✅ 5. Gunakan tcpdump untuk Logging Lengkap (Koneksi Live)

Misalnya log semua koneksi keluar:

sudo tcpdump -i any -nn -tttt

Atau simpan ke file:

sudo tcpdump -i any -nn -w koneksi.pcap

Lalu kamu bisa buka file .pcap di Wireshark dari komputermu untuk analisis lebih dalam.

✅ 6. Pasang Netdata untuk Monitoring History (lebih visual)

bash <(curl -Ss https://my-netdata.io/kickstart.sh)

Setelah itu kamu bisa akses lewat browser:

http://your-vps-ip:19999

Dia bisa tunjukin trafik network per proses.

Bonus: Cara Logging Permanen (Untuk Audit Keamanan)

Kalau kamu butuh logging permanen dan lengkap, pasang auditd:

sudo apt install auditd audispd-plugins
sudo systemctl enable auditd

Lalu kamu bisa log command, proses, dan akses jaringan dengan aturan tertentu.

Nice! 😎 Karena kamu mau log koneksi keluar dari VPS dan mungkin integrasi dengan WA bot, aku buatin sistem logging ringan yang bisa:

✅ Memantau koneksi keluar (IP/port)
✅ Simpan log harian ke file
✅ Opsional: kirim notifikasi ke WhatsApp kalau koneksi mencurigakan terdeteksi

💻 1. Script Basic untuk Log Outbound Connection

#!/bin/bash

# Nama file log harian
LOG_DIR="/var/log/outbound-monitor"
LOG_FILE="$LOG_DIR/outbound-$(date '+%Y-%m-%d').log"
# Buat direktori log kalau belum ada
mkdir -p "$LOG_DIR"
# Capture koneksi keluar (kecuali ke 127.0.0.1 dan koneksi lokal)
ss -tunp | grep ESTAB | grep -v '127.0.0.1' | grep -v '::1' >> "$LOG_FILE"

📌 Penjelasan:

  • ss -tunp: ambil koneksi aktif + PID/program

  • Log disimpan harian di /var/log/outbound-monitor/

⏰ 2. Buat Cronjob Tiap 5 Menit

crontab -e

*/5 * * * * /path/ke/script.sh

🔔 3. (Opsional) Notifikasi WhatsApp via Gateway Kamu

Kamu bisa modif scriptnya:

#!/bin/bash

# Cek koneksi keluar
OUTBOUND=$(ss -tunp | grep ESTAB | grep -v '127.0.0.1' | grep -v '::1')

# Log
LOG_DIR="/var/log/outbound-monitor"
LOG_FILE="$LOG_DIR/outbound-$(date '+%Y-%m-%d').log"
mkdir -p "$LOG_DIR"
echo "$OUTBOUND" >> "$LOG_FILE"

# Kirim notifikasi jika ada koneksi ke IP mencurigakan
if echo "$OUTBOUND" | grep -q "185.234."; then
curl -X POST "http://YOUR_GATEWAY/send-message" \
-d 'to=08123456789&message=[ALERT] VPS terhubung ke IP mencurigakan: 185.234.*'
fi

 

🧪 Mau Lebih Canggih?

Kalau kamu ingin:

  • Mendeteksi koneksi berdasarkan IP blacklist (misal IP dari China/Rusia)

  • Menggunakan tcpdump untuk rekam lengkap

  • Otomatis blokir dengan UFW/IPTables

  • Integrasi langsung ke panel admin bot kamu

Versi dasar dengan logging harian + opsi notifikasi WhatsApp jika koneksi mencurigakan terdeteksi.

✅ Nama Script: outbound-monitor.sh

#!/bin/bash

# ===============================
# Outbound Connection Logger + WA Alert
# ===============================

# === KONFIGURASI ===
LOG_DIR="/var/log/outbound-monitor"
LOG_FILE="$LOG_DIR/outbound-$(date '+%Y-%m-%d').log"
GATEWAY_URL="http://your-wa-gateway.local/send-message"
WA_ADMIN="08xxxxxxxxxx" # Ganti dengan nomor admin kamu
BLACKLISTED_PATTERN="185.234." # Contoh IP mencurigakan

# === BUAT DIREKTORI LOG JIKA BELUM ADA ===
mkdir -p "$LOG_DIR"

# === TANGKAP KONEKSI AKTIF KE LUAR ===
OUTBOUND=$(ss -tunp | grep ESTAB | grep -v '127.0.0.1' | grep -v '::1')

# === TULIS KE LOG ===
{
echo "====== $(date '+%Y-%m-%d %H:%M:%S') ======"
echo "$OUTBOUND"
echo
} >> "$LOG_FILE"

# === CEK IP MENCURIGAKAN ===
if echo "$OUTBOUND" | grep -q "$BLACKLISTED_PATTERN"; then
MESSAGE="[ALERT] VPS Terdeteksi terhubung ke IP mencurigakan ($BLACKLISTED_PATTERN) pada $(date '+%Y-%m-%d %H:%M:%S')"
curl -X POST "$GATEWAY_URL" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "to=$WA_ADMIN&message=$MESSAGE"
fi

⏰ Tambahkan Cronjob

  1. Simpan script-nya, misal di /home/username/outbound-monitor.sh

  2. Beri izin eksekusi:
    chmod +x /home/username/outbound-monitor.sh

  3. Edit crontab:
    crontab -e
    */5 * * * * /username/aca/outbound-monitor.sh

📌 Contoh Output Log

Log harian disimpan di:

/var/log/outbound-monitor/outbound-2025-04-13.log

Contohnya:

====== 2025-04-13 20:35:01 ======
tcp ESTAB 0 0 192.168.1.2:43012 185.234.219.44:https users:(("wget",pid=3283,fd=3))

Lanjut versi canggih, bossku! 🚀💻
Versi ini bakal:

✅ Deteksi IP asing/mencurigakan berdasarkan lokasi atau blacklist
✅ Kirim notifikasi WhatsApp dengan detail lengkap
✅ Catat ke database MySQL (kalau kamu mau)
✅ Bisa dikembangkan jadi sistem bloking otomatis

💥 Versi Canggih: Outbound Monitor v2

🔧 Dependensi (sekali install aja)

sudo apt update
sudo apt install whois curl jq geoip-bin
💻 Script: outbound-monitor-v2.sh
#!/bin/bash

# === KONFIGURASI ===
LOG_DIR="/var/log/outbound-monitor"
LOG_FILE="$LOG_DIR/outbound-$(date '+%Y-%m-%d').log"
GATEWAY_URL="http://your-wa-gateway.local/send-message"
WA_ADMIN="08xxxxxxxxxx" # Nomor WhatsApp admin kamu
BLACKLISTED_IPS=("185.234." "45.134." "103.156.") # IP awal mencurigakan
ALLOWED_COUNTRIES=("ID" "SG") # Negara aman (Indonesia, Singapura)

# === BUAT FOLDER LOG ===
mkdir -p "$LOG_DIR"

# === CARI SEMUA IP TUJUAN ===
OUTBOUND=$(ss -tnp | grep ESTAB | awk '{print $5}' | cut -d: -f1 | sort -u)

for IP in $OUTBOUND; do
# Lewati localhost dan IPv6
if [[ "$IP" == "127.0.0.1" || "$IP" == "::1" || "$IP" == *:* ]]; then
continue
fi

# Dapatkan negara IP via geoiplookup
COUNTRY=$(geoiplookup "$IP" | awk -F: '{print $2}' | awk '{print $1}')

# Deteksi jika negara TIDAK masuk whitelist
if [[ ! " ${ALLOWED_COUNTRIES[@]} " =~ " $COUNTRY " ]]; then
FLAGGED=true
fi

# Deteksi jika IP cocok dengan prefix blacklist
for PREFIX in "${BLACKLISTED_IPS[@]}"; do
if [[ "$IP" == $PREFIX* ]]; then
FLAGGED=true
fi
done

# Jika mencurigakan, log dan kirim notifikasi
if [[ "$FLAGGED" == true ]]; then
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
WHOIS_INFO=$(whois "$IP" | grep -Ei 'OrgName|Organization|netname|country' | head -n 5 | tr '\n' ' ')
echo "[$TIMESTAMP] ⚠️ Outbound ke IP mencurigakan: $IP ($COUNTRY) — Info: $WHOIS_INFO" >> "$LOG_FILE"

# Kirim ke WA
curl -X POST "$GATEWAY_URL" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "to=$WA_ADMIN&message=🚨 Outbound mencurigakan ke $IP ($COUNTRY)%0A$WHOIS_INFO%0AWaktu: $TIMESTAMP"

FLAGGED=false # reset
fi

done

🛡️ Bonus: Auto-block IP Mencurigakan

Mau koneksi yang mencurigakan langsung diblok otomatis via iptables atau UFW?

Contoh tambahan:

sudo ufw deny out to $IP

VERSI PRODUKSI

💾 Langkah 1: Siapkan Database MySQL

Struktur Tabel: outbound_log

CREATE DATABASE IF NOT EXISTS vps_monitor;

USE vps_monitor;

CREATE TABLE IF NOT EXISTS outbound_log (
id INT AUTO_INCREMENT PRIMARY KEY,
ip_address VARCHAR(45),
country_code VARCHAR(10),
whois_info TEXT,
detected_at DATETIME,
action_taken VARCHAR(255)
);

📝 Langkah 2: Update Script dengan MySQL + Auto Block

Kamu akan butuh:

  • mysql-client

  • Akses root atau user dengan izin INSERT dan UFW

Install dulu:

sudo apt install mysql-client ufw

Script: outbound-monitor-full.sh

#!/bin/bash

# === KONFIGURASI ===
LOG_DIR="/var/log/outbound-monitor"
LOG_FILE="$LOG_DIR/outbound-$(date '+%Y-%m-%d').log"
GATEWAY_URL="http://your-wa-gateway.local/send-message"
WA_ADMIN="08xxxxxxxxxx"

DB_USER="root"
DB_PASS="password_dbkamu"
DB_NAME="vps_monitor"
BLACKLISTED_IPS=("185.234." "45.134." "103.156.")
ALLOWED_COUNTRIES=("ID" "SG")

mkdir -p "$LOG_DIR"

OUTBOUND=$(ss -tnp | grep ESTAB | awk '{print $5}' | cut -d: -f1 | sort -u)

for IP in $OUTBOUND; do
[[ "$IP" == "127.0.0.1" || "$IP" == "::1" || "$IP" == *:* ]] && continue

COUNTRY=$(geoiplookup "$IP" | awk -F: '{print $2}' | awk '{print $1}')
WHOIS_INFO=$(whois "$IP" | grep -Ei 'OrgName|Organization|netname|country' | head -n 5 | tr '\n' ' ')
TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
FLAGGED=false
ACTION="None"

if [[ ! " ${ALLOWED_COUNTRIES[@]} " =~ " $COUNTRY " ]]; then
FLAGGED=true
fi

for PREFIX in "${BLACKLISTED_IPS[@]}"; do
if [[ "$IP" == $PREFIX* ]]; then
FLAGGED=true
fi
done

if [[ "$FLAGGED" == true ]]; then
ACTION="Blocked + Notified"

# Log ke file
echo "[$TIMESTAMP] ⚠️ IP mencurigakan: $IP ($COUNTRY)" >> "$LOG_FILE"

# Insert ke MySQL
mysql -u"$DB_USER" -p"$DB_PASS" -D "$DB_NAME" -e \
"INSERT INTO outbound_log (ip_address, country_code, whois_info, detected_at, action_taken)
VALUES ('$IP', '$COUNTRY', '$WHOIS_INFO', '$TIMESTAMP', '$ACTION');"

# Blok IP via UFW
sudo ufw deny out to "$IP" comment 'auto-block suspicious outbound'

# Kirim WA
curl -X POST "$GATEWAY_URL" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "to=$WA_ADMIN&message=🚨 VPS blokir koneksi ke IP $IP ($COUNTRY)%0A$WHOIS_INFO%0AWaktu: $TIMESTAMP"
fi

done