Limiting the number of TCP connections using netfilter in Linux kernel

178 Views Asked by At

I am learning about netfilter in the Linux kernel, and I want to implement functionality to limit the number of TCP connections. My requirement is that the maximum number of open TCP connections should not exceed 50. I have written the following code based on my understanding, but I would like to know if there are any improvements needed or if there are any issues with the code?

#include <linux/module.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/tcp.h>
#include <net/tcp.h>

#define MAX_TCP_CONNECTIONS 50
static unsigned int conn_count = 0;

static unsigned int nf_hook_func(void *priv, struct sk_buff *skb, 
                 const struct nf_hook_state *state)
{
    if (state->pf == PF_INET && skb->protocol == htons(ETH_P_IP)) {
        struct iphdr *iph = ip_hdr(skb);
        if (iph->protocol == IPPROTO_TCP) {
            struct tcphdr *tcph = tcp_hdr(skb);
            
            if (tcph->syn) {
                if (conn_count >= MAX_TCP_CONNECTIONS) {
                    printk(KERN_INFO "Dropping SYN packet. Maximum TCP connections reached.");
                    return NF_DROP;
                }
                conn_count++;
            }
            
            if (tcph->fin) {
                conn_count--;
            }
            
            printk(KERN_INFO "conn_count: %u", conn_count);
        }
    }
    
    return NF_ACCEPT;
}

static struct nf_hook_ops hook_ops = {
    .hook     = nf_hook_func,
    .pf       = PF_INET,
    .hooknum  = NF_INET_PRE_ROUTING,
    .priority = NF_IP_PRI_FIRST,
};

static int __init nf_conn_init(void) 
{
    int ret = nf_register_net_hook(&init_net, &hook_ops);
    if (ret < 0) {
        printk(KERN_ERR "Failed to register netfilter hook\n");
        return ret;
    }
    
    printk(KERN_INFO "Registered IPv4 pre-routing hook\n");
    return 0;
}

static void __exit nf_conn_exit(void) 
{
    nf_unregister_net_hook(&init_net, &hook_ops);
    printk(KERN_INFO "Unregistered IPv4 pre-routing hook\n");
}

module_init(nf_conn_init);
module_exit(nf_conn_exit);

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Netfilter TCP connection limit");
0

There are 0 best solutions below