Linux的远程访问权限花名册hosts.allow和hosts.deny文件
在Linux系统的/etc目录下,有这么两个文件,它们可以记录着远程访问的信息。犹如一本决定着远程IP的可以访问和不能访问的花名册。
- /etc/hosts.allow 文件在Linux系统中用于指定哪些主机或网络可以访问特定的服务。
- /etc/hosts.deny 文件在Linux系统中用于指定哪些主机或网络不能访问特定的服务。
这两个文件通常是一起配合在一起使用,以控制对Linux系统服务的远程访问权限。
生效机制
当有远程连接请求到达时,Linux系统会先检查 /etc/hosts.allow 文件,如果找到匹配的规则则允许访问。如果 /etc/hosts.allow 中没有匹配的规则,系统会继续检查 /etc/hosts.deny 文件。如果在 /etc/hosts.deny 中找到匹配的规则,则拒绝访问。如果在这两个文件中都没有找到匹配的规则,则默认允许访问。
/etc/hosts.allow文件
以下是 /etc/hosts.allow 文件的一些关键点和配置示例。
查看 /etc/hosts.allow 文件,可以看到里面有关于文件的解释和使用的例子
root@raspberrypi:~# cat /etc/hosts.allow
# /etc/hosts.allow: list of hosts that are allowed to access the system.
# See the manual pages hosts_access(5) and hosts_options(5).
#
# Example: ALL: LOCAL @some_netgroup
# ALL: .foobar.edu EXCEPT terminalserver.foobar.edu
#
# If you're going to protect the portmapper use the name "rpcbind" for the
# daemon name. See rpcbind(8) and rpc.mountd(8) for further information.
#
关于文件的介绍很简单,就一句话:
允许访问该系统的主机列表。
配置格式:
/etc/hosts.allow 文件的配置格式通常为
服务(PortocolName):地址(IPAddress)
服务可以是任何网络协议服务,如sshd、vsftpd、smbd、telnetd等,也可以是all(所有服务)。
地址可以是具体的IP地址、IP地址段,或者使用通配符如*表示所有地址。
配置示例:
允许指定的IP地址访问sshd服务:
sshd:192.168.1.100
允许整个子网段访问所有服务:
ALL:192.168.1.0/24
允许特定IP地址访问所有服务:
ALL:127.0.0.1
使用通配符允许指定的网段访问:
sshd:192.168.*.*
/etc/hosts.deny文件
以下是 /etc/hosts.deny 文件的一些关键点和配置示例
查看 /etc/hosts.deny 文件,可以看到里面有关于文件的解释和使用的例子
root@raspberrypi:~# cat /etc/hosts.deny
# /etc/hosts.deny: list of hosts that are _not_ allowed to access the system.
# See the manual pages hosts_access(5) and hosts_options(5).
#
# Example: ALL: some.host.name, .some.domain
# ALL EXCEPT in.fingerd: other.host.name, .other.domain
#
# If you're going to protect the portmapper use the name "rpcbind" for the
# daemon name. See rpcbind(8) and rpc.mountd(8) for further information.
#
# The PARANOID wildcard matches any host whose name does not match its
# address.
#
# You may wish to enable this to ensure any programs that don't
# validate looked up hostnames still leave understandable logs. In past
# versions of Debian this has been the default.
# ALL: PARANOID
关于文件的介绍和允许访问的文件一样简洁也是一句话:
不允许访问该系统的主机列表。
配置格式
/etc/hosts.deny 文件的配置格式通常为 服务:地址。
服务(PortocolName):地址(IPAddress)
服务可以是任何网络服务,如sshd、vsftpd、smbd、telnetd等,也可以是all(所有服务)。
地址可以是具体的IP地址、IP地址段,或者使用通配符如*表示所有地址。
配置示例
禁止所有IP地址访问sshd服务:
sshd:ALL
禁止指定IP地址访问telnet服务:
telnetd:192.168.1.100
禁止指定的子网段访问所有服务:
ALL:192.168.1.0/24
禁止所有IP地址访问所有服务,但允许特定IP地址访问:
ALL:ALL
使用通配符拒绝访问:
sshd:192.168.*.*
建议事项:
- 修改 /etc/hosts.deny 和 /etc/hosts.allow 文件后,通常不需要重启服务,更改会立即生效。但已经建立的会话不会受到影响。例如要禁止某SSH连接,在配置完成后,建议重启SSH服务,强行终止所有连接。
- 通常建议在 /etc/hosts.deny 文件中设置一个默认的拒绝规则(如 ALL:ALL),然后在 /etc/hosts.allow 文件中明确允许特定的IP地址或地址段,这样可以更精确地控制访问权限。
- /etc/hosts.deny 和 /etc/hosts.allow 文件的配置只对使用了TCP Wrappers库的服务有效。因此,确保相关服务支持并启用了TCP Wrappers。
如果您对我的文章有兴趣,我把我发布的文章都归档到我私人网站中去,欢迎访问 Corner 三的小角落 -- 首页 查阅之前的文章。