0

我对 BPF/XDP 验证程序有疑问。我尝试过滤 UDP 数据包并在数据包末尾写入时间戳(使用udh->len)。因为udh->len是网络字节顺序,我首先必须将其转换为“主机”字节顺序。所以我这样尝试:

SEC("xdp_sock")
int xdp_sock_prog(struct xdp_md *ctx) {

    const void *data = (void*)(unsigned long)ctx->data;
    const void *data_end = (void*)(unsigned long)ctx->data_end;

    const struct ethhdr *eth = (struct ethhdr*)(data);

    if((void*)eth + sizeof(struct ethhdr) <= data_end) {

        if(bpf_ntohs(eth->h_proto) == ETH_P_IP) {
            const struct iphdr *iph = (struct iphdr*)(data + sizeof(struct ethhdr));

            if((void*)iph + sizeof(struct iphdr) <= data_end) {

                if(iph->protocol == IPPROTO_UDP) {
                    const __u16 iph_sz_in_bytes = iph->ihl * IP_HDR_MULT_IHL;

                    if((void*)iph + iph_sz_in_bytes <= data_end) {

                        const struct udphdr *udh = (struct udphdr*)(data + sizeof(struct ethhdr) + iph_sz_in_bytes);

                        if((void*)udh + sizeof(struct udphdr) <= data_end) {
                            const __u16 udh_sz_in_bytes = bpf_ntohs(udh->len);

                            if((void*)udh + udh_sz_in_bytes <= data_end) {
                                bpf_printk("HELLO!\n");
                                /* Usually I would start to write the timestamp here */
                            }

但我明白了math between pkt pointer and register with unbounded min value is not allowed

因为我想不出这种方法会失败,所以我试图删除bpf_ntohs只是为了测试目的(我知道它不会那样工作):

SEC("xdp_sock")
int xdp_sock_prog(struct xdp_md *ctx) {

    const void *data = (void*)(unsigned long)ctx->data;
    const void *data_end = (void*)(unsigned long)ctx->data_end;

    const struct ethhdr *eth = (struct ethhdr*)(data);

    if((void*)eth + sizeof(struct ethhdr) <= data_end) {

        if(bpf_ntohs(eth->h_proto) == ETH_P_IP) {
            const struct iphdr *iph = (struct iphdr*)(data + sizeof(struct ethhdr));

            if((void*)iph + sizeof(struct iphdr) <= data_end) {

                if(iph->protocol == IPPROTO_UDP) {
                    const __u16 iph_sz_in_bytes = iph->ihl * IP_HDR_MULT_IHL;

                    if((void*)iph + iph_sz_in_bytes <= data_end) {

                        const struct udphdr *udh = (struct udphdr*)(data + sizeof(struct ethhdr) + iph_sz_in_bytes);

                        if((void*)udh + sizeof(struct udphdr) <= data_end) {
                            const __u16 udh_sz_in_bytes = udh->len;

                            if((void*)udh + udh_sz_in_bytes <= data_end) {
                                bpf_printk("HELLO!\n");
                            }

但我实际上能够以这种方式运行我的程序 - 任何想法为什么bpf_ntohs会产生验证程序错误?

4

0 回答 0