阻止除本地网络之外的所有传入请求

阻止除本地网络之外的所有传入请求

我有一台专用服务器,上面安装了 Ubuntu 22.04.1 LTS 服务器,并有一个公共 IP 地址。我想锁定 ssh 端口,只允许特定 IP 地址通过。

我有 3 个来自工作单位的 IP 地址和我在服务器上设置的具有 IP 范围的网络。

我该如何只允许这些 IP 地址登录到我的服务器?

我在另一篇文章中发现了这一点:

iptables -I INPUT -p tcp ! -s yourIPaddress --dport 22 -j REJECT

如果我对每个 IP 地址运行它,这会起作用吗?或者会很复杂吗?

另外,这够了吗?我应该锁定其他端口吗?这是一个新安装,上面只有 postgresql。我正在尝试了解有关 Ubuntu 和 postgresql 的更多信息,但我不想让我的服务器成为攻击目标。

感谢您的输入!

答案1

我建议你调整方法,从单端口关注转向全面“防御”态势:将 IP 列入白名单,拒绝所有其他连接尝试。这适用于你环境中的大多数端口 - 否则你将不得不将 IP 列入黑名单每一个已知存在并进行服务扫描的 IP,因此您将获得一个非常长的列表。服务扫描程序扫描每一个端口,因此您首先应该采用“拒绝信任”方法。Web 服务器(如果是公共站点,HTTP/HTTPS 的端口 80、443 可能需要比特定 IP 更广泛的访问权限)等也会被扫描,但可以通过适当强化 Web 服务器和内容来“保护”。然而,全部端口由服务扫描仪扫描,并且全部互联网连接设备会受到扫描,因此从一开始就拒绝一切是更好的方法。

因此,最有效的“拒绝信任”方法是简单地允许某些 IP 连接到端口和计算机上的所有其他服务,然后拒绝所有其他连接尝试。同时还允许 localhost 与自身通信,这是可以的。

在打开其他端口之前,先使用白名单保护所有内容。如果您需要更多服务,我们可以为来自任何地方的 HTTP 流量配置额外的允许规则等。

# Allow localhost traffic
iptables -A INPUT -i lo -j ACCEPT

# INVALID type packets should be DROPped regardless of source.
iptables -A INPUT -m state --state INVALID -j DROP

# Allow traffic for related/established connections already running
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT

# Allow all new connections/traffic from the local subnet you're on 
# (10.20.30.0/24 is used in example)
iptables -A INPUT -m state --state NEW -s 10.20.30.0/24 -j ACCEPT

# Whitelist your IPs - repeat this step for each of your IPs permitted
# to access the machine outside of local network
iptables -A INPUT -s IPADDRESS -m state --state NEW -j ACCEPT

# If you have other services you want to configure for *public* access, then
# use this rule as a template and execute this before you follow the last step.
#
# Change PROTO to the protocol (tcp/udp, etc.) and PORT to the port number 
# (80 for HTTP, ex.)
#
# Add this to the end of the rule if you want to allow only certain 
# IPs to the specified service:
#   -s IPADDRESS 
iptables -A INPUT -p PROTO --dport PORT -m state --state NEW -j ACCEPT

# Deny all other traffic
iptables -A INPUT -j REJECT --reject-with icmp-host-unreachable

这是基于我近 15 年的服务器经验以及我的网络安全培训。 以及我作为 IT 安全专业人员的知识。

相关内容