使用iptables实现etcd集群白名单功能

来源:互联网 发布:淘宝男士休闲鞋 编辑:程序博客网 时间:2024/06/13 19:07

1.概述

由于etcd自身不提供ip白名单功能,当在生产环境运行etcd,且当该etcd简体监听外网时,应该通过ip白名单来允许能够访问的外网ip,拒绝非法的ip访问,从而提高生成环境etcd集群的安全性,这里将使用iptables来实现该功能。

2.iptables使用

在centos中,iptables可以通过服务方式进行运行,使用服务方式运行相对来说更加方便使用,除了可以更加方便控制iptables外,也提供了配置文件方式,更加便于配置添加及管理。

  • 安装
yum install iptables-services
  • 配置开机自启动
systemctl enable iptables.service
  • 修改配置文件

安装iptables后如果默认启动,iptables会将除ssh的其他端口的数据包直接drop掉,这时如果是在有业务的服务器上进行启动的话是会业务产生影响的,解决方法是修改配置文件,将drop配置去掉再启动。

vi /etc/sysconfig/iptables

内容如下,去掉INPUT链中的REJECT

# sample configuration for iptables service# you can edit this manually or use system-config-firewall# please do not ask us to add additional ports/services to this default configuration*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT-A INPUT -p icmp -j ACCEPT-A INPUT -i lo -j ACCEPT-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT-A INPUT -j REJECT --reject-with icmp-host-prohibited-A FORWARD -j REJECT --reject-with icmp-host-prohibitedCOMMIT
  • 启动
systemctl start iptables.service
  • 查看iptables配置
iptables -L -n

3. 添加iptables白名单

这里有两种方式,一种是使用命令行,一种是直接修改配置文件。命令行添加后还需要执行保存命令将添加结果保存到配置文件,否则机器重启时,配置的信息会丢失。而直接修改配置文件则需要对iptables进行重启。

3.1 命令行

  • 添加端口(2379)白名单
iptables -A INPUT -s 183.23.58.124/32 -p tcp -m tcp --dport 2379 -j ACCEPT
  • 拒绝其他
iptables -A INPUT -s 0.0.0.0/0  -p tcp -m tcp --dport 2379 -j DROP
  • 保存到 /etc/sysconfig/iptables
/usr/libexec/iptables/iptables.init save

3.2 直接修改配置文件

  • 直接编辑 /etc/sysconfig/iptables

命令行命令去掉iptables直接写入到文件中。

# sample configuration for iptables service# you can edit this manually or use system-config-firewall# please do not ask us to add additional ports/services to this default configuration*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT-A INPUT -p icmp -j ACCEPT-A INPUT -i lo -j ACCEPT-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT-A INPUT -s 183.23.58.124/32 -p tcp -m tcp --dport 2379 -j ACCEPT-A INPUT -s 0.0.0.0/0  -p tcp -m tcp --dport 2379 -j DROP-A FORWARD -j REJECT --reject-with icmp-host-prohibitedCOMMIT
  • 重启iptables服务
systemctl restart iptables.service

4. 批量生成添加脚本

如果存在批量添加,则可以使用脚本进行检测,以下脚本批量检查文件中的地址是否在iptables中,如果没有则生成添加语句,生成添加语句后,直接写入到/etc/sysconfig/iptables中INPUT链的2379端口的REJECT前面,然后重启即可。

cat $1 | while read linedo has=`iptables -L INPUT -n|grep $line|wc -l` if [ $has -eq 0 ];then   echo "-A INPUT -s $line/32 -p tcp -m tcp --dport 2379 -j ACCEPT" fidone
  • 使用方式
sh gen.sh ip.txt   //ip.txt中ip按行排列
原创粉丝点击