在日常运维工作中,为了安全考虑,常常需要对服务器登陆的ip做白名单限制。那么限制服务器登陆ip的方法主要有:
1)iptables里对ssh端口做限制
2)/etc/hosts.allow和/etc/hosts.deny限制
以上两种设置的优先级是:iptables > /etc/hosts.allow > /etc/hosts.deny
先说一下现在用的限制服务器ip登陆的限制操作:
先在/etc/sysconfig/iptables里面对ssh端口做限制,再在/etc/hosts.allow里设置允许的ip,基本/etc/hosts.deny不用动。
[[email protected] ~]# cat /etc/sysconfig/iptables
.....
-A INPUT -s 192.168.1.0/24 -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -s 114.165.77.144 -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
-A INPUT -s 133.110.186.130 -m state --state NEW -m tcp -p tcp --dport 22 -j ACCEPT
[[email protected] ~]# cat /etc/hosts.allow
#
# hosts.allow This file contains access rules which are used to
# allow or deny connections to network services that
# either use the tcp_wrappers library or that have been
# started through a tcp_wrappers-enabled xinetd.
#
# See ‘man 5 hosts_options‘ and ‘man 5 hosts_access‘
# for information on rule syntax.
# See ‘man tcpd‘ for information on tcp_wrappers
#
sshd:192.168.1.*,114.165.77.144,133.110.186.130,133.110.186.139:allow
sshd:all:deny
[[email protected] ~]# cat /etc/hosts.deny
#
# hosts.deny This file contains access rules which are used to
# deny connections to network services that either use
# the tcp_wrappers library or that have been
# started through a tcp_wrappers-enabled xinetd.
#
# The rules in this file can also be set up in
# /etc/hosts.allow with a ‘deny‘ option instead.
#
# See ‘man 5 hosts_options‘ and ‘man 5 hosts_access‘
# for information on rule syntax.
# See ‘man tcpd‘ for information on tcp_wrappers
#
------------------------------------------------------------------------------------------------------
接着对/etc/hosts.allow和/etc/hosts.deny两文件的设置做一详细介绍:
/etc/hosts.allow:用来限制服务器允许执行的ip登陆感觉比防火墙方便很多;限制特定IP来访.
思路:
1)通常的做法是利用hosts的拒绝设置,而它的设置是针对某一个具体的进程,具体的服务,在这里就是sshd了
2)设置一个网段使用的是x.x.x.0/24,比如192.168.1.0/24,这是子网匹配的方式;
如果更简单一些看起来可以直接保留前面一部分,比如131.155. ,这样可以匹配后面是任何网段,比如131.155.1.1