Category: Iptables

  • iptables的Source NAT和Masquerading

    来自于

    Linux iptables Pocket Reference

    Source NAT(SNAT) 是用来在多台电脑之间分享上网的,充当gateway的电脑用SNAT(同时开启connection tracking)来重写内外网之间的包。向外去的包被打上gateway的IP地址。当外部响应后,会建立到网关IP的连接,网关接收到这些包后,网关截获到这些包后,把目标地址转到成正确的内部电脑上。

    因为SNAT 是在包离开内核之前接受修改了它的地址和/或端口,在NAT表中表现为POSTROUTING.

    在iptables中有两种实现SNAT的方式:

    目标操作为SNAT,在网关ip是固定的时候

    iptables -t nat -A POSTROUTING -o eth1 -j SNAT

    而使用MASQUERADE是防止掉线后再连接ip地址发生变化的出现。

    iptables -t nat -A POSTROUTING -o eth1 -j MASQUERADE

    如果用ip的方式全部转发给192.168.1.16可用

    /sbin/iptables -t nat -A POSTROUTING -j SNAT --to-source 192.168.1.16

    forwarder 机器

    -A PREROUTING -p tcp -m tcp --dport 30101 -j DNAT --to-destination 74.12.20.82:443
    -A POSTROUTING -d 74.12.20.82/32 -p tcp -m tcp --dport 443 -j MASQUERADE
    
  • CentOS6.2的iptables基础

    来自于

    Linux iptables Pocket Reference

    CentOS的iptables规则保存在/etc/sysconfig/iptables

    查看iptables的启动级别

    [root@localhost ~]# chkconfig --list iptables
    iptables        0:off   1:off   2:on    3:on    4:on    5:on    6:off

    调整启动级别可以用如下命令

    chkconfig --levels 345 iptables on

    启动iptables

    service iptables start

    停用iptables

    service iptables stop

    一些伪文件:(存在于/proc)

    /etc/sysctl.conf在启动里创建了/proc/sys,如配置pptp-vpn的时候,在sysctl.conf里加入net.ipv4.ip_forward=1开机后,查看/proc/sys/net/ipv4/ip_forward,就会发现变为1.

    /proc/sys/net/ipv4/ip_conntrack_max,当出现“ip_conntrack: table full, dropping packet”错误时,你需要在/etc/sysctl.conf加值。

    用uname -r可查看内核版本信息

    uname -a查看全部信息,具体见(manpage of uname).

    几个状态的说明

    ESTABLISHED 已经监测到双向发送的包

    INVALID 什么都没有

    NEW 有新的连接或监测到一部分

    RELATED 有新的连接,且新连接是基于已有连接

    连接监测主要是连接的前三个比特。

    conntrack 参数,(–ststatus选项)有

    ASSURED TCP连接,说明TCP已经连接,UDP雷同

    EXPECTED 说明连接是已知的

    SEEN_REPLY 说明已经监测到双向发送的包,参见ESTABLISHED

    内核统计

    内核会自动统计通过iptables的每一条规则的包和字节。

    例如,eth0代表内网,eth1代表外网

    iptables -A FORWARD -i eth1
    iptables -A FORWARD -o eth1
    iptables -A INPUT -i eth1
    iptables -A OUTPUT -o eth1

    iptables记录了与外网的交换的包和流量数,通过iptables -L -v查看 INPUT和OUTPUT的包和流量如下

    Chain INPUT (policy ACCEPT 27 packets, 1728 bytes)
    pkts bytes target prot opt in out source destination
    3 192 all -- eth1 any anywhere anywhere
    Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
    pkts bytes target prot opt in out source destination
    0 0 all -- eth1 any anywhere anywhere
    0 0 all -- any eth1 anywhere anywhere
    Chain OUTPUT (policy ACCEPT 21 packets, 2744 bytes)
    pkts bytes target prot opt in out source destination
    3 192 all -- any eth1 anywhere anywhere

    如查想指定哪些包通过NAT,把包-j(jump)到特殊目标ACCEPT.要早于其他NAT规则

    iptables -t nat -i eth1 ... -j ACCEPT