大网数据广告活动
服务器运维问答

IPtables whitelist dynamic IP by hostname

· 52CE 我爱测

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…

问题原文

原帖链接 · 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

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-10-25)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。