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

Ero*_*ocM 3 server ssh networking 22.04

我有一个专用服务器,我在其上使用公共 IP 地址启动了 Ubuntu 22.04.1 LTS 服务器。我想锁定 ssh 端口,只允许特定的 IP 地址通过。

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

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

我在另一篇文章中找到了这个:

iptables -I INPUT -p tcp ! -s yourIPaddress --dport 22 -j REJECT
Run Code Online (Sandbox Code Playgroud)

如果我为每个 IP 地址运行它,这会起作用吗?还是会出现复杂情况?

还有,这样就够了吗?我应该锁定其他端口吗?这是全新安装,仅包含 postgresql。我正在尝试了解有关 Ubuntu 和 postgresql 的更多信息,但我不希望我的服务器成为目标。

感谢您的输入!

Tho*_*ard 6

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

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

在打开其他端口之前,首先使用白名单保护所有内容。如果您需要更多服务,我们可以为来自任何地方的 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
Run Code Online (Sandbox Code Playgroud)

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