netfilter 学习 --- 兴趣入门

netfilter 测试内核模块

1这是从书上看到的例子

先获取到百度的ip地址

$ ping www.baidu.com
PING www.a.shifen.com (36.155.132.76) 56(84) bytes of data.
64 bytes from 36.155.132.76 (36.155.132.76): icmp_seq=1 ttl=47 time=15.3 ms
64 bytes from 36.155.132.76 (36.155.132.76): icmp_seq=2 ttl=47 time=15.7 ms
^C
--- www.a.shifen.com ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 15.306/15.525/15.745/0.252 ms

$ nslookup www.baidu.com
Server:         127.0.0.53
Address:        127.0.0.53#53

Non-authoritative answer:
www.baidu.com   canonical name = www.a.shifen.com.
Name:   www.a.shifen.com
Address: 36.155.132.76
Name:   www.a.shifen.com
Address: 36.155.132.3
Name:   www.a.shifen.com
Address: 2409:8c20:6:1d55:0:ff:b09c:7d77
Name:   www.a.shifen.com
Address: 2409:8c20:6:1135:0:ff:b027:210c

这里知道ipv4地址是36.155.132.76

对应的32位无符号整数是

361551327610进制
249B844c16进制

static unsigned char *drop = "\x24\x9b\x84\x4c";

正常情况可以ping也可以用curl访问。设计一个内核模块

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netdevice.h>
#include <linux/ip.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/init.h>

static struct nf_hook_ops  nfhook;
static unsigned char *drop = "\x24\x9b\x84\x4c";

// hook function
unsigned int hook_func(void *priv, struct sk_buff *skb, const struct nf_hook_state *state) {
    struct iphdr *ip = ip_hdr(skb);

    if (ip->saddr == *(unsigned int*) drop) {
        printk("DROP PACKET FROM %pI4\n", &ip->saddr);
        return NF_DROP; // drop it
    } else {
        // printk("ALLOW PACKET FROM %pI4\n", &ip->saddr);
        return NF_ACCEPT;
    }

    return 0;
}

static int __init hook_init(void)
{
    nfhook.hook = hook_func;
    nfhook.pf = PF_INET;
    nfhook.hooknum = NF_INET_PRE_ROUTING;
    nfhook.priority = NF_IP_PRI_FIRST;

    nf_register_net_hook(&init_net, &nfhook);
    printk(KERN_INFO "Netfilter hook registered\n");

return 0;
}

static void __exit hook_exit(void)
{
    nf_unregister_net_hook(&init_net, &nfhook);
        printk(KERN_INFO"%s exit", __func__);
}

module_init(hook_init);
module_exit(hook_exit);

 加载这个内核模块测试:

这时候36.155.132.76 这个地址就无法访问了。 

上面有几个结构在将来学习netfilter会用到。

netfilter 有关的数据结构、术语

nf_hook_ops

struct nf_hook_ops {
    struct list_head list;
        nf_hookfn *hook;
        struct module *owner;
        u_int8_t pf;
        unsigned int hooknum;
        int priority;
};

在这个结构体中,一些重要的字段包括:
hook:指向实际的钩子函数的指针。
pf:协议族,指定了钩子函数应该关注的协议族。
hooknum:钩子函数的类型,例如 NF_INET_PRE_ROUTING、NF_INET_LOCAL_IN 等。
priority:钩子函数的优先级,用于确定多个钩子函数的执行顺序。
 

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值