对特定的端口/ip 对使用 ACCEPT 然后 DROP 是否允许该 ip 但该端口上没有其他任何内容?

Rob*_*och 3 iptables

我正在服务器上工作并且应该对其进行配置,以便仅允许来自特定 IP 的端口 8080 上的请求。(在其他 http(s) 端口上,无论如何都没有监听。)

其他一切都将不受限制。

在研究了/etc/hostiptables之后,我编写了这个脚本来激活(和停用)该规则:

#!/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 X.X.X.X
    # [I]nserting the rules as first in the chain.
    iptables -I INPUT -p tcp --dport 8080 -s X.X.X.X -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
Run Code Online (Sandbox Code Playgroud)

因为我只能通过 SSH 访问机器,所以我不想搞砸并将自己锁在外面。所以我想问一下这个脚本

  • 作品?
  • 会做想要的吗?
  • 不会做别的吗?
  • 保持非易失性?

mzh*_*ase 6

虽然这会奏效,但这不是最佳实践。最好的做法是放弃一切,然后只允许您真正想要经历的事情,而不是允许一切并只丢弃特定的东西。

一个“正常”的 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
Run Code Online (Sandbox Code Playgroud)

此外,在设置新防火墙时,不要自动运行脚本,或使更改永久化。这样,如果您搞砸了,重新启动服务器将使您恢复连接。

  • 这将把你锁在外面。ssh 是 22 端口。 (7认同)

cor*_*rny 6

对于 IPv4,您的规则是正确的(如果您修复了之前评论中提到的 shell 脚本中的语法错误)。 对于 IPv6,您的机器可能是完全开放的

对未来的提示:

  • 防止锁定:如果您iptables-save直接以风格编写规则,您可能会喜欢这个iptables-apply命令,它可以恢复您以前的规则,以防新规则将您锁定。

  • 使规则持久化:在 ubuntu 上,应该有一个iptables-persistent包来确保您的规则在重启后仍然有效。只需设置您的规则,apt-get install iptables-persistent然后按照互动对话进行操作即可。

  • 改进风格和安全性:mzhaase 给出了一个非常好的教程如何编写白名单规则。