TTL目标帮助信息如下,可对报文的ttl进行设置、减少或者增加。
# iptables --jump TTL -h
TTL target options
--ttl-set value Set TTL to <value 0-255>
--ttl-dec value Decrement TTL by <value 1-255>
--ttl-inc value Increment TTL by <value 1-255>
如下在主机192.168.1.112上配置策略,丢弃IP头部ttl值小于3的报文。在另外的主机上执行ping操作,指定ttl为1,此时由于ttl小于3,ping不通。
# iptables -t filter -A INPUT -m ttl --ttl-lt 3 -j DROP
在主机192.168.1.112上配置策略,将IP头部ttl值增加3。此时在执行ping操作,由于ttl在增加之后为4,未匹配以上丢弃策略,ping通。
# iptables -t mangle -A PREROUTING -j TTL --ttl-inc 3
#
# iptables -L -t mangle -n -v
Chain PREROUTING (policy ACCEPT 147 packets, 19766 bytes)
pkts bytes target prot opt in out source destination
147 19766 TTL all -- * * 0.0.0.0/0 0.0.0.0/0 TTL increment by 3
TTL目标
函数xt_register_targets注册TTL目标结构hl_tg_reg。
static struct xt_target hl_tg_reg[] __read_mostly = {
{
.name = "TTL",
.revision = 0,
.family = NFPROTO_IPV4,
.target = ttl_tg,
.targetsize = sizeof(struct ipt_TTL_info),
.table = "mangle",
.checkentry = ttl_tg_check,
.me = THIS_MODULE,
},
};
static int __init hl_tg_init(void)
{
return xt_register_targets(hl_tg_reg, ARRAY_SIZE(hl_tg_reg));
参数检查函数如下,目前仅支持ttl设置,增加和减少三种模式,其它模式则非法。如果模式为增加或者减少ttl值,那么ttl的增加或减少量值不能为0。
static int ttl_tg_check(const struct xt_tgchk_param *par)
{
const struct ipt_TTL_info *info = par->targinfo;
if (info->mode > IPT_TTL_MAXMODE)
return -EINVAL;
if (info->mode != IPT_TTL_SET && info->ttl == 0)
return -EINVAL;
return 0;
根据不同的模式,计算新的ttl值。对于增加模式,如果新的ttl值大于255,限定在255。对于减少模式,如果新的ttl值小于0,设置为0。
static unsigned int
ttl_tg(struct sk_buff *skb, const struct xt_action_param *par)
{
struct iphdr *iph;
const struct ipt_TTL_info *info = par->targinfo;
if (skb_ensure_writable(skb, sizeof(*iph)))
return NF_DROP;
iph = ip_hdr(skb);
switch (info->mode) {
case IPT_TTL_SET:
new_ttl = info->ttl;
break;
case IPT_TTL_INC:
new_ttl = iph->ttl + info->ttl;
if (new_ttl > 255)
new_ttl = 255;
break;
case IPT_TTL_DEC:
new_ttl = iph->ttl - info->ttl;
if (new_ttl < 0)
new_ttl = 0;
break;
default:
new_ttl = iph->ttl;
break;
}
新的ttl值与报文IP头部中的ttl值不相等,更新IP头部的检验和,使用新的ttl值填充IP头部的ttl字段。
if (new_ttl != iph->ttl) {
csum_replace2(&iph->check, htons(iph->ttl << 8), htons(new_ttl << 8));
iph->ttl = new_ttl;
}
return XT_CONTINUE;
内核版本 5.10