[英]Why I don't receive any packets using BPF with udp socket?
目標:編寫一個BPF過濾器,該過濾器僅允許來自特定src地址的UDP數據包並將其附加到UDP套接字。
問題:如果執行程序,並嘗試從具有正確src IP的VM發送udp數據包,我什么也不會收到
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <linux/filter.h>
/* udp and src 192.168.56.101 */
struct sock_filter bpfcode[] = {
{ 0x28, 0, 0, 0x0000000c },
{ 0x15, 6, 0, 0x000086dd },
{ 0x15, 0, 5, 0x00000800 },
{ 0x30, 0, 0, 0x00000017 },
{ 0x15, 0, 3, 0x00000011 },
{ 0x20, 0, 0, 0x0000001a },
{ 0x15, 0, 1, 0xc0a83865 },
{ 0x6, 0, 0, 0x00040000 },
{ 0x6, 0, 0, 0x00000000 },
};
int main(void)
{
struct sock_fprog bpf = {
sizeof(bpfcode) / sizeof(struct sock_filter),
bpfcode
};
struct sockaddr_in src = {
.sin_family = AF_INET,
.sin_addr.s_addr = INADDR_ANY,
.sin_port = htons(1025)
};
char buf[1024];
ssize_t res;
int fd, ret;
fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (fd < 0) {
printf("error: socket\n");
exit(EXIT_FAILURE);
}
ret = setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &bpf, sizeof(bpf));
if (ret < 0) {
perror("error: setsockopt\n");
close(fd);
exit(EXIT_FAILURE);
}
ret = bind(fd, (struct sockaddr *)&src, sizeof(src));
if (ret < 0) {
printf("error: bind\n");
close(fd);
exit(EXIT_FAILURE);
}
res = recvfrom(fd, buf, sizeof(buf), 0, NULL, 0);
printf("res = %zi\n", res);
close(fd);
return 0;
}
評論中討論的摘要:
首先,套接字的類型為SOCK_DGRAM
,因此您獲得的數據始於L4(UDP),而不是過濾器期望的L2。 請改用SOCK_RAW
。
然后,使用SOCK_RAW
將使您可以訪問L3,而不是L2(您需要為此更改套接字域)。 因此,您需要對過濾器進行一些調整:
{ 0x28, 0, 0, 0x0000000c }, // load Ethertype
{ 0x15, 6, 0, 0x000086dd }, // If IPv6 goto drop
{ 0x15, 0, 5, 0x00000800 }, // If not IPv4 (and not IPv6) goto drop
{ 0x30, 0, 0, 0x00000017 }, // Load IP protocol
{ 0x15, 0, 3, 0x00000011 }, // If not UDP goto drop
{ 0x20, 0, 0, 0x0000001a }, // Load src address
{ 0x15, 0, 1, 0xc0a83865 }, // If not 192.168.56.1.1 goto drop
{ 0x6, 0, 0, 0x00040000 }, // Pass packet
{ 0x6, 0, 0, 0x00000000 }, // Drop
應該成為(由OP自己修復的信用:)):
// UDP check is harmless but useless
// { 0x30, 0, 0, 0x00000009 }, // Note the offset update
// { 0x15, 0, 3, 0x00000011 },
{ 0x20, 0, 0, 0x0000000c }, // Note the offset update
{ 0x15, 0, 1, 0xc0a83865 },
{ 0x6, 0, 0, 0x00040000 },
{ 0x6, 0, 0, 0x00000000 },
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.