我在一个服务器上工作,我应该configuration它,使得端口8080上的请求只允许从一个特定的IP。 (在其他http端口没有任何东西在听。)
其他一切应保持不受限制。
在研究了/etc/host和iptables之后,我编写了这个脚本来激活(和停用)该规则:
#!/bin/bash if ["$1" != 'restrict'] && ["$1" != 'restore'] then echo "Usage:" echo "'${0##*/} restrict' to activate rules." echo "'${0##*/} restore' to deactivate rules." echo "'${0##*/}' to show this help." exit 0 fi # Set default policies for INPUT, FORWARD and OUTPUT chains # Allowing everything else. iptables -P INPUT ACCEPT iptables -P FORWARD ACCEPT iptables -P OUTPUT ACCEPT # Flush all current rules from iptables iptables -F if [$1 == "restrict"] then # Allow HTTP connections on tcp port 8080 from XXXX # [I]nserting the rules as first in the chain. iptables -I INPUT -p tcp --dport 8080 -s XXXX -j ACCEPT # Denying all other connections on tcp port 8080 # [A]ppending the rule as last in the chain. iptables -A INPUT -p tcp --dport 8080 -j DROP fi # Save settings /sbin/service iptables save # List rules iptables -L -v
由于我只能通过SSH访问机器,所以我不想搞砸自己。 所以我想问一下这个剧本
虽然这会起作用,但这不是最佳实践。 不要只允许一切,只能放弃具体的事情,最好的做法是放弃一切,然后只允许你实际上想要经历的事情。
“普通”IP表规则集通常是这样开始的:
# Flush rules iptables -F # Policy drop iptables -P INPUT DROP iptables -P OUTPUT DROP iptables -P FORWARD DROP # Permit loopback device iptables -A INPUT -i lo -j ACCEPT iptables -A OUTPUT -o lo -j ACCEPT # Permit new outgoing connections, and packets that belong to # an existing connection. You might actually not want to allow # all new connections from the inside if you want to restrict # this, you will have to allow DNS, updates, etc.. manually iptables -A OUTPUT -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT # Same for input iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT # SSH iptables -A INPUT -p tcp --dport 22 -j ACCEPT iptables -A OUTPUT -p tcp --sport 22 -j ACCEPT # Custom rules # ... iptables -A INPUT -p tcp --dport 8080 -s 5.35.252.105 -j ACCEPT
另外,在设置新的防火墙时,不要自动运行脚本,也不要永久保存更改。 这样,如果你搞砸了,重新启动服务器会让你连接回来。
您的规则是正确的(如果您修复了IPv4的shell脚本中的语法错误,请参阅前面的注释)。 对于IPv6,您的机器可能完全打开 。
未来的提示:
防止locking:如果直接使用iptables-save方式编写规则,则可能会喜欢使用iptables-apply命令来恢复以前的规则,以防新的规则将您locking。
使规则持久化:在Ubuntu上,应该有iptables-persistent软件包来确保你的规则在重新启动的时候存在。 只要设置你的规则,并进入apt-get install iptables-persistent并按照交互式对话。
改进风格和安全性:mzhaase给出了一个非常好的教程,如何编写白名单规则。
这是防止locking的简单方法。 它将原则上在任何* nix系统上工作,而不仅仅是Ubuntu。
假设您的脚本名为/usr/local/bin/start-iptables.sh并且使用命令/usr/local/bin/stop-iptables.sh完全禁用iptables
/usr/local/bin/start-iptables.sh ; sleep 30 ; /usr/local/bin/stop-iptables.sh
如果你像这样运行命令,那么shell将按顺序运行它们。 如果你控制-c,整个命令string将被中止 – 它不会取消正在运行的命令并移到下一个命令string。
所以,shell会运行你的启动脚本,然后睡30秒。 在这30秒内,请确认您仍然可以访问服务器。 build立一个新的连接,有办法可以连接新的连接,但保持现有的连接。 一旦你确定,control-c和sleep和stop-iptables脚本将被中止。
如果你locking自己,30秒后,停止脚本将运行,你会回来。