Step-by-Step Guide to Setting Up a Wan IP Logger


What is a WAN IP logger?

A WAN IP logger records the public (WAN) IP addresses of devices that connect to a service, website, or network. For administrators, it helps track remote access sessions, identify malicious activity, and troubleshoot connectivity issues. A WAN IP logger captures IP addresses and usually stores a timestamp, user agent, and other connection metadata.


Common legitimate use cases

  • Remote access monitoring for servers and remote employees
  • Security auditing and intrusion detection
  • Logging visitors for a self-hosted service (with consent)
  • Troubleshooting NAT, ISP, or routing problems

Before you begin, ensure you have:

  • Administrative access to the server or device where the logger will run.
  • Written permission from any third parties whose IPs you will collect (if applicable).
  • Knowledge of local privacy laws and organizational policies regarding logging and retention.
  • A secure storage plan for logs (encryption, access controls).
  • A retention policy and a plan for secure deletion of old logs.

Overview of the setup approach

This article shows a common, simple approach:

  1. Set up a small web service that records incoming requests.
  2. Capture and store the requester’s WAN IP and metadata.
  3. Secure the service and logs.
  4. Optionally analyze and visualize the data.

We’ll provide a practical example using:

  • A Linux VPS (Ubuntu/Debian) accessible via the public Internet
  • Nginx as a reverse proxy
  • A small backend written in Python (Flask) to record requests
  • SQLite for lightweight storage (optional: PostgreSQL for production)
  • Basic log rotation and retention

Step 1 — Provision a server

  1. Choose a VPS provider (or use an existing physical server).
  2. Create a minimal Ubuntu/Debian instance. Recommended specs for testing: 1 vCPU, 1–2 GB RAM, 10 GB disk.
  3. Ensure the server has a public IP and SSH access.
  4. Configure firewall to allow ports 22 (SSH) and ⁄443 (HTTP/HTTPS). On Ubuntu:
    
    sudo apt update sudo apt install -y ufw sudo ufw allow OpenSSH sudo ufw allow 80/tcp sudo ufw allow 443/tcp sudo ufw enable 

Step 2 — Install required packages

Install Python, pip, virtualenv, Nginx and SQLite:

sudo apt update sudo apt install -y python3 python3-venv python3-pip nginx sqlite3 

Step 3 — Create a minimal Flask app to record requests

Create a new directory and virtual environment:

mkdir ~/wan-ip-logger cd ~/wan-ip-logger python3 -m venv venv source venv/bin/activate pip install wheel flask gunicorn 

Create app file app.py:

from flask import Flask, request, g import sqlite3 from datetime import datetime DB = 'ips.db' app = Flask(__name__) def get_db():     db = getattr(g, '_database', None)     if db is None:         db = g._database = sqlite3.connect(DB)     return db @app.teardown_appcontext def close_connection(exception):     db = getattr(g, '_database', None)     if db is not None:         db.close() def init_db():     conn = sqlite3.connect(DB)     c = conn.cursor()     c.execute('''CREATE TABLE IF NOT EXISTS ips                  (id INTEGER PRIMARY KEY AUTOINCREMENT,                   ip TEXT,                   user_agent TEXT,                   path TEXT,                   method TEXT,                   ts TEXT)''')     conn.commit()     conn.close() @app.before_first_request def startup():     init_db() @app.route('/', defaults={'path': ''}) @app.route('/<path:path>', methods=['GET','POST']) def log_request(path):     ip = request.headers.get('X-Forwarded-For', request.remote_addr)     ua = request.headers.get('User-Agent', '')     method = request.method     ts = datetime.utcnow().isoformat()     conn = get_db()     c = conn.cursor()     c.execute("INSERT INTO ips (ip, user_agent, path, method, ts) VALUES (?, ?, ?, ?, ?)",               (ip, ua, path, method, ts))     conn.commit()     # Minimal response     return 'OK', 200 

Note: retrieving the client IP uses the X-Forwarded-For header because we’ll place Nginx in front. In other deployment scenarios, adapt accordingly.


Step 4 — Run the app with Gunicorn and configure systemd

Install Gunicorn:

pip install gunicorn 

Create systemd service /etc/systemd/system/wan-ip-logger.service:

[Unit] Description=WAN IP Logger After=network.target [Service] User=YOUR_USERNAME Group=www-data WorkingDirectory=/home/YOUR_USERNAME/wan-ip-logger Environment="PATH=/home/YOUR_USERNAME/wan-ip-logger/venv/bin" ExecStart=/home/YOUR_USERNAME/wan-ip-logger/venv/bin/gunicorn --workers 3 --bind unix:/tmp/wan-ip-logger.sock app:app [Install] WantedBy=multi-user.target 

Replace YOUR_USERNAME with your user. Then:

sudo systemctl daemon-reload sudo systemctl start wan-ip-logger sudo systemctl enable wan-ip-logger 

Step 5 — Configure Nginx as reverse proxy

Create /etc/nginx/sites-available/wan-ip-logger:

server {     listen 80;     server_name your.server.domain; # or _ for default     location / {         proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;         proxy_set_header Host $host;         proxy_set_header X-Real-IP $remote_addr;         proxy_pass http://unix:/tmp/wan-ip-logger.sock;     } } 

Enable and reload Nginx:

sudo ln -s /etc/nginx/sites-available/wan-ip-logger /etc/nginx/sites-enabled/ sudo nginx -t sudo systemctl reload nginx 

Step 6 — Secure the service and logs

  • Use HTTPS: obtain a certificate with Certbot (Let’s Encrypt).

    
    sudo apt install -y certbot python3-certbot-nginx sudo certbot --nginx -d your.server.domain 

  • Restrict access: if only internal systems should call it, bind to a private network or restrict via firewall or Nginx allow/deny.

  • Protect stored logs: ensure file permissions restrict access to the app user and consider encrypting the disk or database file.

  • Implement retention: add a cron job to delete records older than your retention window:

    # daily cleanup script /usr/local/bin/clean_ips.sh #!/bin/bash sqlite3 /home/YOUR_USERNAME/wan-ip-logger/ips.db "DELETE FROM ips WHERE ts < datetime('now','-30 days');" 

    Make it executable and add to cron:

    sudo chmod +x /usr/local/bin/clean_ips.sh sudo crontab -e # add: 0 3 * * * /usr/local/bin/clean_ips.sh 

Step 7 — Viewing and analyzing logs

Quick query via sqlite3:

sqlite3 ips.db "SELECT ip, COUNT(*) as hits FROM ips GROUP BY ip ORDER BY hits DESC LIMIT 50;" 

For more advanced analysis:

  • Export to CSV and open in a spreadsheet.
  • Import into a SIEM (Splunk, Elastic) for alerting and dashboards.
  • Build a small web UI endpoint that queries the DB and returns JSON (ensure auth).

Security considerations and best practices

  • Only collect necessary data; minimize retention.
  • Mask or hash IPs if full addresses aren’t needed for long-term analytics. Example: store a salted HMAC of the IP instead of the raw IP.
  • Monitor for abuse (e.g., someone triggering many requests). Rate-limit and add authentication if required.
  • Regularly update dependencies and apply OS security patches.
  • Back up logs securely if required for audits, and test restoration.

Alternatives and scaling

  • For lightweight use, store logs in plain files with logrotate.
  • For higher scale, use PostgreSQL or a time-series DB (InfluxDB) and run the app in containers behind a load balancer.
  • Consider using existing access logs from Nginx/HAProxy which already record remote IPs and user agents; parse those with tools like goaccess.

Example: quick Nginx-only approach (no custom app)

If you only need to capture IPs that visit a specific URL, Nginx can log them directly. Example server block:

server {     listen 80;     server_name your.server.domain;     location /logme {         return 204;     }     access_log /var/log/nginx/wan_ips.log combined; } 

Then parse /var/log/nginx/wan_ips.log for IPs hitting /logme.


Troubleshooting

  • If logs show 127.0.0.1 or reverse proxy IPs, ensure Nginx sets X-Forwarded-For and your app reads it.
  • Permission errors with systemd: ensure Service User and file ownership align.
  • Gunicorn not binding socket: check paths and that the socket file is created with proper permissions.

This guide gives a practical, auditable approach to setting up a WAN IP logger for legitimate administrative and diagnostic purposes. Remember to follow legal and ethical requirements when collecting and storing IP addresses.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *