问题原文
原帖链接 · Tom B · CC BY-SA 4.0
I want to limit access to a server to certain IPs using iptables but:
- One of the IPs is dynamic, a normal ISP home connection which changes from time to time.
- A subdomain e.g. dynamic.example.org is automatically updated when the IP changes using a similar service to dyndns.
Is it possible to have IPtables allow access to a port if dynamic.example.org resolves to that IP?
My current idea is to set up a systemd unit that periodically resolves dynamic.example.org and adjusts iptables accordingly. However, this also requires knowing the old IP address (so storing it somewhere) to remove it from the whitelist.
Is there a simpler way to do this already built in to iptables?
社区高分解答
原帖链接 · mivk · CC BY-SA 4.0
The way I do this is:
- Run a script every x minutes from crontab to update an "ipset"
- Have IPtables use the ipset
Assuming you have only 1 IP address in this ipset, the following script would do:
#!/bin/bash
# Update ipset to let my dynamic IP in
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
set=whitelist
host=myhost.dynamic.example.com
me=$(basename "$0")
ip=$(dig +short $host)
if [ -z "$ip" ]; then
logger -t "$me" "IP for '$host' not found"
exit 1
fi
# make sure the set exists
ipset -exist create $set hash:ip
if ipset -q test $set $ip; then
logger -t "$me" "IP '$ip' already in set '$set'."
else
logger -t "$me" "Adding IP '$ip' to set '$set'."
ipset flush $set
ipset add $set $ip
fi
In crontab I call this script every 5 minutes :
*/5 * * * * root /usr/local/bin/ipset-update-dyn
In iptables, the rule using the ipset looks like this :
-A INPUT -p tcp -m set --match-set whitelist src -m state --state NEW -j ACCEPT
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
