netfilter hook을 이용해 특정 IP에 해당 장비로 ssh 패킷을 차단해볼 예정입니다.
차단할 IP와 포트 등등이 있으면 hook함수에서 return을 NF_DROP해주면 됩니다.
먼저 IP를 string으로 바꿔줘야한다 그러기 위해서 아래와같이 snprintf를 이용해 string으로 받아준다.
char src_ip_str[16];
char dst_ip_str[16];
snprintf(src_ip_str, 16, "%pI4", &ip_header->saddr);
snprintf(dst_ip_str, 16, "%pI4", &ip_header->daddr);
이렇게 해줬으면 이제 조건문으로 IP와 Port를 검사해주면 된다.
조건문에 아래와 같이 넣어주면 된다.
//츨발지 IP !strcmp(src_ip_str, "192.168.56.102")
//도착지 IP !strcmp(dst_ip_str, "192.168.56.101")
//Port (22 == ntohs(tcp_header->dest)
완성된 hook_function이다.
static unsigned int my_hook_function(void *priv, struct sk_buff *skb, const struct nf_hook_state *state) {
struct iphdr *ip_header;
struct tcphdr *tcp_header;
struct udphdr *udp_header;
if (!skb)
return NF_ACCEPT;
// IPv4 프로토콜인지 확인
char src_ip_str[16];
char dst_ip_str[16];
if (skb->protocol == htons(ETH_P_IP)) {
ip_header = (struct iphdr *)skb_network_header(skb);
snprintf(src_ip_str, 16, "%pI4", &ip_header->saddr);
snprintf(dst_ip_str, 16, "%pI4", &ip_header->daddr);
}
//TCP 프로토콜인지 UDP 프로토콜인지 확인
if (ip_header->protocol == IPPROTO_TCP) {
tcp_header = (struct tcphdr *)((__u32 *)ip_header + ip_header->ihl);
if(!strcmp(src_ip_str, "192.168.56.102")&&!strcmp(dst_ip_str, "192.168.56.101")&&(22 == ntohs(tcp_header->dest))){
printk(KERN_INFO "Detected rule");
return NF_DROP;
}
} else if (ip_header->protocol == IPPROTO_UDP) {
udp_header = (struct udphdr *)((__u32 *)ip_header + ip_header->ihl);
printk(KERN_INFO "UDP Packet - Source IP: %pI4, Source Port: %d, Dest IP: %pI4, Dest Port: %d\n",
&ip_header->saddr, ntohs(udp_header->source), &ip_header->daddr, ntohs(udp_header->dest));
}
return NF_ACCEPT;
}