如何使用内核模块将 IP 地址重定向到本地主机

问题描述

最近在学习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,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,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 // 连接失败

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...