一、背景需求
近期编写tcp透明代理时,考虑了透明方式下需要使用 iptables 进行 DNAT/SNAT 规则下发,在程序中可以生成命令后通过 system 调用执行;
那么,iptables 是否有提供外部接口来代替上述这种 system() 执行命令的方式?答案是可以
使用libiptc库进行编程实现。
二、相关知识
2.1 Linux/Netfilter
《Linux网络安全技术与实现》提到,Linux系统的防火墙功能主要为Netfilter模块进行实现,从功能上又细分了四大表:Filter、Nat、Mangle、Raw;
1)*Filter表*:数据包过滤功能;
2)*Nat表*:网络地址转换功能,IP分享器(一对一、一对多、多对多)功能;
3)Mangle表:修改经过防火墙的数据包功能;
4)Raw表:负责加快数据包穿越防火墙的速度,用于提高性能;
2.2 Netfilter/iptables
上述简单阐述了Netfilter在Linux内核防火墙的地位,而Netfilter工作在系统内核,规则是存在于内存中的,那么管理人员如何管理防火墙的规则呢?
这样的规则管理工具就是 iptables / ip6tables,比如下发一个规则到 Netfilter规则数据库中:
iptables -t filter -A INPUT -p tcp -m state --state ESTABLISHED,RELATED -j ACCEPT
三、实例
3.1 准备工作
内核版本:linux-3.10.25_x64
源码版本:iptables-1.4.14(https://www.netfilter.org/projects/iptables/files/iptables-1.4.14.tar.bz2)
工具准备:gcc、automake、libtools(编译时需要把本机的libtools 放到 iptables 源码目录下)
3.2 接口说明
1) 获取当前防火墙规则快照 iptc_init
Name: iptc_init
Usage: Takes a snapshot of the rules.
Description: This function must be called as initiator before any other function can be called.
Parameters: tablename is the name of the table w