Wednesday, June 24, 2020

iptables log specific connections

Example how to allow certain known connections (e.g. unifi accesspoints) and log unknown connection attempts.
This is done by adding a chain called LOGDROP, append packets that match the criteria (tcp/8080) to that chain, log the packets and drop them.

iptables:

#!/bin/bash

AP01="192.168.0.1"
AP02="192.168.0.2"
AP03="192.168.0.3"

# Resetting ...
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -F
iptables -X

# Setting default policy on incoming traffic
iptables -P INPUT DROP                                                  # DENY INCOMING CONNECTIONS
iptables -P FORWARD DROP                                                # THIS IS NOT A ROUTER

# allowed accesspoints
iptables -A INPUT -p tcp --dport 8080 -s $AP01 -j ACCEPT                # UNIFI - AP01
iptables -A INPUT -p udp --dport 3478 -s $AP01 -j ACCEPT
iptables -A INPUT -p tcp --dport 8080 -s $AP02 -j ACCEPT                # UNIFI - AP02
iptables -A INPUT -p udp --dport 3478 -s $AP02 -j ACCEPT
iptables -A INPUT -p tcp --dport 8080 -s $AP03 -j ACCEPT                # UNIFI - AP03
iptables -A INPUT -p udp --dport 3478 -s $AP03 -j ACCEPT
# log AP connections that aren't allowed
iptables -N LOGDROP
iptables -A INPUT -p tcp --dport 8080 -j LOGDROP
iptables -A LOGDROP -j LOG --log-prefix "IPTables-Dropped: " --log-level 7
iptables -A LOGDROP -j DROP

# Make persistent
iptables-save >/etc/iptables/rules.v4

Create a file in /etc/rsyslog.d/ called “30-unifi-accesspoints.conf” with the following content:

:msg,contains,"IPTables-Dropped: " /var/log/unifi_accesspoints.log

and restart rsyslog