Files
xdp/simple_xdp_filter.c
T
2025-02-26 19:08:28 -03:00

94 lines
2.4 KiB
C

#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <linux/udp.h>
#include <linux/in.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>
// Definir arquitetura ARM64 explicitamente
#ifndef __TARGET_ARCH_arm64
#define __TARGET_ARCH_arm64
#endif
// Mapa para redes internas (para SNAT)
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 16);
__type(key, __u32); // Prefixo de rede (/16)
__type(value, __u8); // Flag (1=ativo)
} snat_networks SEC(".maps");
// Mapa para regras DNAT
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 64);
__type(key, __u16); // Porta destino
__type(value, __u32); // IP interno
} dnat_rules SEC(".maps");
// Estatísticas
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 4);
__type(key, __u32);
__type(value, __u64);
} stats_map SEC(".maps");
// Incrementar contador de estatísticas
static __always_inline void increment_counter(__u32 index) {
__u64 *counter;
counter = bpf_map_lookup_elem(&stats_map, &index);
if (counter)
(*counter)++;
}
// Programa XDP simplificado para inspeção de tráfego
SEC("xdp")
int simple_xdp_filter(struct xdp_md *ctx) {
void *data = (void *)(long)ctx->data;
void *data_end = (void *)(long)ctx->data_end;
struct ethhdr *eth = data;
// Verificação básica de limites
if (data + sizeof(struct ethhdr) > data_end)
return XDP_PASS;
// Verificar se é um pacote IPv4
if (eth->h_proto != bpf_htons(ETH_P_IP))
return XDP_PASS;
struct iphdr *ip = (void *)(eth + 1);
if ((void *)(ip + 1) > data_end)
return XDP_PASS;
// Incrementar contador de pacotes processados
increment_counter(0);
// Verificar se é um pacote TCP ou UDP
if (ip->protocol == IPPROTO_TCP) {
struct tcphdr *tcp = (void *)(ip + 1);
if ((void *)(tcp + 1) > data_end)
return XDP_PASS;
// Contar pacotes TCP
increment_counter(1);
// Verificar se é tráfego HTTPS (porta 443)
__u16 dport = bpf_ntohs(tcp->dest);
if (dport == 443) {
increment_counter(3); // Contar pacotes HTTPS
}
} else if (ip->protocol == IPPROTO_UDP) {
// Contar pacotes UDP
increment_counter(2);
}
// Permitir que todos os pacotes passem
return XDP_PASS;
}
char _license[] SEC("license") = "GPL";