Skip to content

Instantly share code, notes, and snippets.

@c0m4r
Last active September 29, 2024 07:49
Show Gist options
  • Save c0m4r/204298ccf8ffdeab8de9cad0388994dc to your computer and use it in GitHub Desktop.
Save c0m4r/204298ccf8ffdeab8de9cad0388994dc to your computer and use it in GitHub Desktop.
Whitelist DDNS Mikrotik IP iptables

Whitelist DDNS Mikrotik IP iptables

A python script solution to whitelist an IP address in iptables resolved with Mikrotik DDNS service (or any other).

In this example I have whitelisted Mikrotik DDNS IP to allow access to SSH and OpenVPN ports.

The script is scheduled in crontab to run every minute. It will resolve Mikrotik DDNS domain, flush the iptables WHITELIST chain and add the IP address if it changed.

* * * * * /root/mikrotik_whitelist.py > /dev/null
*filter
# Base policy
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -i lo -j ACCEPT
-A INPUT -i tun0 -s 10.0.0.0/24 -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
# SSH + OpenVPN
-N WHITELIST
-A WHITELIST -j DROP
-A INPUT -p tcp -m multiport --dports 22,1194 --syn -m conntrack --ctstate NEW -j WHITELIST
COMMIT
#!/usr/bin/env python3
"""mikrotik whitelist"""
from subprocess import run, DEVNULL, PIPE # nosec
from socket import gethostbyname
DDNS = "xxxxxxxxxxx.xx.mynetname.net"
IP = gethostbyname(DDNS)
ip_test = run(
["iptables", "-S", "WHITELIST"], check=True, stdout=PIPE, stderr=None
) # nosec
if IP not in ip_test.stdout.decode("utf-8"):
run(["iptables", "-N", "WHITELIST"], check=False, stderr=DEVNULL) # nosec
run(["iptables", "-F", "WHITELIST"], check=True) # nosec
run(["iptables", "-A", "WHITELIST", "-s", IP, "-j", "ACCEPT"], check=True) # nosec
run(["iptables", "-A", "WHITELIST", "-j", "DROP"], check=True) # nosec
print(f"{IP} whitelisted")
else:
print(f"{IP} already added")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment