iptables
实验准备:
- 需要两台虚拟机,分别给两台虚拟机修改主机名,配置网络,搭建yum源,
一台server 双网卡 eth0 172.25.254.224
eth1 1.1.1.224
一台client 单网卡 eth0 172.25.254.124
在server虚拟机上设置防火墙为如下:
systemctl stop firewalld
systemctl mask firewalld
systemctl start iptables.service
systemctl enable iptables.service
参数含义:
-t | 指定表名称,不加默认指filter |
---|---|
-n | 不作解析 |
-L | 列出指定表中的策略 |
-A | 增加策略,不能指定加的位置,默认加到最后 |
-p | 网络协议 |
–dport | 端口 |
-s | 数据来源 |
-j | 动作 |
ACCEPT | 允许 |
REJECT | 拒绝 |
DROP | 丢弃 |
-N | 增加链 |
-E | 修改链名称 |
-X | 删除链 |
-D | 删除指定策略 |
-F | 刷掉原有策略 |
-I | 插入,默认插入到最前面,可以指定位置 |
-R | 修改策略,更改,刷新 |
-P | 修改默认策略 |
Filter表的设定举例:
iptables -t filter -nL 查看filter表 = iptables -nL
iptables -t nat -nL 查看nat表
iptables -t mangle -nL 查看mangle表
vim /etc/sysconfig/iptables 保存策略的表
iptables -F 刷掉原有的策略
service iptables save 保存当前策略到文件
iptables -t filter -A INPUT -i lo -j ACCEPT 给filter表中加回环接口,动作是accept
iptables -nL 查看有没有添加成功
iptables -t filter -A INPUT -s 172.25.254.10 -j ACCEPT 给filter表添加这个ip,这个ip可以访问all prot
iptables -nL 查看有没有添加成功
iptables -t filter -A INPUT -s 172.25.254.10 -j REJECT 给filter表添加ip这个ip禁止reject
但是2,3只会读取2,2是匹配的,就生效了,3就不被执行了。
iptables -D INPUT 3 删除第三条
iptables -nL
iptables -R INPUT 2 -s 172.25.254.10 -j REJECT 修改第二条的accept为reject
iptables -nL
iptables -I INPUT 2 -s 172.25.254.10 -p tcp --dport 22 -j ACCEPT
将端口为22的ip为10的插入到第二条,指定位置
iptables -nL
此时真机可以连接
其他主机能不能连接取决于此时的policy是accept还是reject还是drop
除了设定的主机之外的其他主机都走的是默认的设定。
iptables -P INPUT DROP 将默认的动作设置为drop,其他主机此时连接不上
iptables -nL
iptables -P INPUT ACCEPT 将默认动作设为accept,又连上了。
iptables -nL
iptables -N westos 增加链westos
iptables -E westos WESTOS 修改连名称为WESTOS
iptables -X WESTOS 删除WESTOS
iptables -nL
Nat表的设定
iptables -t nat -nL 查看
地址伪装 从外面进来 ,伪装成别人理的地址 ,路由之后,不经过内核
端口转发 从里面出去
地址转换,编辑nat表。
dnat 目的地址转换
snat 源地址转换
-o出去
地址伪装:
sysctl -a | grep ip_forward 首先要开启路由转发功能
iptables -t nat -A POSTOUTING -o eth0 -j SNAT --to-source 172.25.254.224 ##出去,源地址转换
路由后地址伪装,将1.1.1.124的地址伪装成172.25.254.224来访问172网段的ip
任何地址从nat出去都会转化为172.25.254.224
此时client的eth01.1.1.124可以ping通172.25.254网端的ip,而且连接真机发现伪装了。
测试:client可以连接其他172.25.254.0/24网段的主机,w -i可以看到他伪装成172.25.254.224了。
端口转发:
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 22 -j DNAT --to-dest 1.1.1.124:22 ##进来,目的地址转换
从eth0进,把要连接双网卡主机eth0网卡的ip172.25.254.224的端口22,目的地址转化称到1.1.1.124的22端口 -i input
##路由前端口转发,连接 172.25.254.224 的22端口会转到1.1.1.124 的22端口
iptables -t nat -nL 查看
测试:真机连接eth0172.25.254.224 会自动转化为client端的eth0 1.1.1.124
如果未设定好,可以用命令
iptables -t nat -D PREROUTING 1 进行删除
iptables -t nat -D POSTROUTING 1 删除