首页 > 解决方案 > 如何使用内核模块将 IP 地址重定向到 localhost

问题描述

我最近在学习netfilter的编程。我想连接到假 IP 和端口并重定向到正确的 IP 和端口。但我不想使用 iptables。

信息

内核版本:4.15.0-132-generic

Ubuntu 版本:16

假IP和端口:192.168.9.99:999

重定向IP和端口:192.168.9.4:80

测试本地主机 IP 和端口:127.0.0.1:19999


首先,我使用curl来测试上面的IP。

curl -I 192.168.9.99:999  # Connection timed out
curl -I 192.168.9.4:80    # HTTP/1.1 200 OK
curl -I 127.0.0.1:19999   # HTTP/1.1 200 OK

我挂钩 NF_INET_LOCAL_OUT 和 NF_INET_LOCAL_IN 点。当我通过假 IP 连接到重定向 IP 时,它可以工作。我将重定向 IP 更改为 localhost IP (127.0.0.1:19999)。但它不起作用。它在 NF_INET_LOCAL_IN 点修改 IP。但它没有响应,甚至通过了 NF_INET_LOCAL_IN 点。

这是我的代码:

static void update_chksum(struct sk_buff *skb, struct iphdr *iph, struct tcphdr *tcp)
{
    iph->check = 0;
    iph->check = ip_fast_csum(iph,iph->ihl);

    tcp->check = 0;
    tcp->check = csum_tcpudp_magic(iph->saddr,
                                   iph->daddr,
                                   ntohs(iph->tot_len) - iph->ihl * 4,
                                   IPPROTO_TCP,
                                   csum_partial(tcp, ntohs(iph->tot_len) - iph->ihl * 4, 0));

    //checksum
    skb->ip_summed = CHECKSUM_NONE;
}



unsigned int hook_func(void *priv, struct sk_buff *skb, const struct nf_hook_state *state)
{


    skb_linearize(skb);
    ip_header  = ip_hdr(skb);
    tcp_header = tcp_hdr(skb);

    unsigned int  fake_ip = inet_addr("192.168.9.99");
    unsigned int  fake_port = htons(999);
    unsigned int  redirect_ip = inet_addr("192.168.9.4");
    unsigned int  redirect_port = htons(80);
    
    //unsigned int  redirect_ip = inet_addr("127.0.0.1"); // failed to connect
    //unsigned int  redirect_port = htons(19999);


    if (state->hook == NF_INET_LOCAL_OUT) {
        if (ip_header->daddr == fake_ip && tcp_header->dest == fake_port) {
            ip_header->daddr = redirect_ip;
            tcp_header->dest = redirect_port;
            update_chksum(skb, ip_header, tcp_header);
        }
    }
    else if (state->hook == NF_INET_LOCAL_IN) {
        if (ip_header->saddr == redirect_ip && tcp_header->source == redirect_port) {
            ip_header->saddr = fake_ip;
            tcp_header->source = fake_port;
            update_chksum(skb, ip_header, tcp_header);

        }
    }
    return NF_ACCEPT;
} 

我搜索了相关信息,得到的答案是在内核中启用这个选项。但它仍然不起作用。

sysctl -w net.ipv4.conf.all.route_localnet=1

结果:

test1 : 192.168.9.99:999 ---> 192.168.9.4:80 // 连接成功

test2 : 192.168.9.99:999 ---> 127.0.0.1:19999 // 连接失败

所以我的问题:如何重定向到本地主机?

标签: ckernel-modulenetfilter

解决方案


推荐阅读