Microsoft MVP성태의 닷넷 이야기
Linux: 124. eBPF - __sk_buff / sk_buff 구조체 [링크 복사], [링크+제목 복사],
조회: 587
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

eBPF - __sk_buff / sk_buff 구조체

지난 글에서 설명한,

eBPF (bpf2go) - BPF_PROG_TYPE_SOCKET_FILTER 예제 - SEC("socket")
; https://www.sysnet.pe.kr/2/0/14017

BPF_PROG_TYPE_SOCKET_FILTER 프로그램에서 __sk_buff 구조체를 사용했었는데요,

SEC("socket")
int socket_handler(struct __sk_buff *skb)
{
    // Your eBPF program logic here
    return skb->len;
}

이에 대한 자료를 찾아보면,

Understanding struct __sk_buff
; https://wangcong.org/2021-08-15-understanding-struct-__sk_buff.html

Program context __sk_buff
; https://docs.ebpf.io/linux/program-context/__sk_buff/

원래의 커널 구조체는 sk_buff이고, eBPF 로더가 런타임 시에 __sk_buff의 필드에 대한 접근을 sk_buff로 변환해 준다고 합니다. 이에 대한 변환 코드를 bpf_convert_ctx_access 함수에서 확인할 수 있는데,

// https://elixir.bootlin.com/linux/v5.13.10/source/net/core/filter.c#L8411

static u32 bpf_convert_ctx_access(enum bpf_access_type type,
                  const struct bpf_insn *si,
                  struct bpf_insn *insn_buf,
                  struct bpf_prog *prog, u32 *target_size)
{
    struct bpf_insn *insn = insn_buf;
    int off;

    switch (si->off) {
    case offsetof(struct __sk_buff, len):
        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
                      bpf_target_off(struct sk_buff, len, 4,
                             target_size));
        break;

    case offsetof(struct __sk_buff, protocol):
        *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
                      bpf_target_off(struct sk_buff, protocol, 2,
                             target_size));
        break;

    case offsetof(struct __sk_buff, vlan_proto):
        *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
                      bpf_target_off(struct sk_buff, vlan_proto, 2,
                             target_size));
        break;

    case offsetof(struct __sk_buff, priority):
        if (type == BPF_WRITE)
            *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
                          bpf_target_off(struct sk_buff, priority, 4,
                                 target_size));
        else
            *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
                          bpf_target_off(struct sk_buff, priority, 4,
                                 target_size));
        break;

    case offsetof(struct __sk_buff, ingress_ifindex):
        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
                      bpf_target_off(struct sk_buff, skb_iif, 4,
                             target_size));
        break;

    case offsetof(struct __sk_buff, ifindex):
        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, dev),
                      si->dst_reg, si->src_reg,
                      offsetof(struct sk_buff, dev));
        *insn++ = BPF_JMP_IMM(BPF_JEQ, si->dst_reg, 0, 1);
        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
                      bpf_target_off(struct net_device, ifindex, 4,
                             target_size));
        break;

    case offsetof(struct __sk_buff, hash):
        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
                      bpf_target_off(struct sk_buff, hash, 4,
                             target_size));
        break;

    case offsetof(struct __sk_buff, mark):
        if (type == BPF_WRITE)
            *insn++ = BPF_STX_MEM(BPF_W, si->dst_reg, si->src_reg,
                          bpf_target_off(struct sk_buff, mark, 4,
                                 target_size));
        else
            *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
                          bpf_target_off(struct sk_buff, mark, 4,
                                 target_size));
        break;

    case offsetof(struct __sk_buff, pkt_type):
        *target_size = 1;
        *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
                      PKT_TYPE_OFFSET());
        *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, PKT_TYPE_MAX);
#ifdef __BIG_ENDIAN_BITFIELD
        *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, 5);
#endif
        break;

    case offsetof(struct __sk_buff, queue_mapping):
        if (type == BPF_WRITE) {
            *insn++ = BPF_JMP_IMM(BPF_JGE, si->src_reg, NO_QUEUE_MAPPING, 1);
            *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
                          bpf_target_off(struct sk_buff,
                                 queue_mapping,
                                 2, target_size));
        } else {
            *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
                          bpf_target_off(struct sk_buff,
                                 queue_mapping,
                                 2, target_size));
        }
        break;

    case offsetof(struct __sk_buff, vlan_present):
        *target_size = 1;
        *insn++ = BPF_LDX_MEM(BPF_B, si->dst_reg, si->src_reg,
                      PKT_VLAN_PRESENT_OFFSET());
        if (PKT_VLAN_PRESENT_BIT)
            *insn++ = BPF_ALU32_IMM(BPF_RSH, si->dst_reg, PKT_VLAN_PRESENT_BIT);
        if (PKT_VLAN_PRESENT_BIT < 7)
            *insn++ = BPF_ALU32_IMM(BPF_AND, si->dst_reg, 1);
        break;

    case offsetof(struct __sk_buff, vlan_tci):
        *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
                      bpf_target_off(struct sk_buff, vlan_tci, 2,
                             target_size));
        break;

    case offsetof(struct __sk_buff, cb[0]) ...
         offsetofend(struct __sk_buff, cb[4]) - 1:
        BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, data) < 20);
        BUILD_BUG_ON((offsetof(struct sk_buff, cb) +
                  offsetof(struct qdisc_skb_cb, data)) %
                 sizeof(__u64));

        prog->cb_access = 1;
        off  = si->off;
        off -= offsetof(struct __sk_buff, cb[0]);
        off += offsetof(struct sk_buff, cb);
        off += offsetof(struct qdisc_skb_cb, data);
        if (type == BPF_WRITE)
            *insn++ = BPF_STX_MEM(BPF_SIZE(si->code), si->dst_reg,
                          si->src_reg, off);
        else
            *insn++ = BPF_LDX_MEM(BPF_SIZE(si->code), si->dst_reg,
                          si->src_reg, off);
        break;

    case offsetof(struct __sk_buff, tc_classid):
        BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, tc_classid) != 2);

        off  = si->off;
        off -= offsetof(struct __sk_buff, tc_classid);
        off += offsetof(struct sk_buff, cb);
        off += offsetof(struct qdisc_skb_cb, tc_classid);
        *target_size = 2;
        if (type == BPF_WRITE)
            *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg,
                          si->src_reg, off);
        else
            *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg,
                          si->src_reg, off);
        break;

    case offsetof(struct __sk_buff, data):
        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, data),
                      si->dst_reg, si->src_reg,
                      offsetof(struct sk_buff, data));
        break;

    case offsetof(struct __sk_buff, data_meta):
        off  = si->off;
        off -= offsetof(struct __sk_buff, data_meta);
        off += offsetof(struct sk_buff, cb);
        off += offsetof(struct bpf_skb_data_end, data_meta);
        *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
                      si->src_reg, off);
        break;

    case offsetof(struct __sk_buff, data_end):
        off  = si->off;
        off -= offsetof(struct __sk_buff, data_end);
        off += offsetof(struct sk_buff, cb);
        off += offsetof(struct bpf_skb_data_end, data_end);
        *insn++ = BPF_LDX_MEM(BPF_SIZEOF(void *), si->dst_reg,
                      si->src_reg, off);
        break;

    case offsetof(struct __sk_buff, tc_index):
#ifdef CONFIG_NET_SCHED
        if (type == BPF_WRITE)
            *insn++ = BPF_STX_MEM(BPF_H, si->dst_reg, si->src_reg,
                          bpf_target_off(struct sk_buff, tc_index, 2,
                                 target_size));
        else
            *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->src_reg,
                          bpf_target_off(struct sk_buff, tc_index, 2,
                                 target_size));
#else
        *target_size = 2;
        if (type == BPF_WRITE)
            *insn++ = BPF_MOV64_REG(si->dst_reg, si->dst_reg);
        else
            *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
#endif
        break;

    case offsetof(struct __sk_buff, napi_id):
#if defined(CONFIG_NET_RX_BUSY_POLL)
        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg,
                      bpf_target_off(struct sk_buff, napi_id, 4,
                             target_size));
        *insn++ = BPF_JMP_IMM(BPF_JGE, si->dst_reg, MIN_NAPI_ID, 1);
        *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
#else
        *target_size = 4;
        *insn++ = BPF_MOV64_IMM(si->dst_reg, 0);
#endif
        break;
    case offsetof(struct __sk_buff, family):
        BUILD_BUG_ON(sizeof_field(struct sock_common, skc_family) != 2);

        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
                      si->dst_reg, si->src_reg,
                      offsetof(struct sk_buff, sk));
        *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
                      bpf_target_off(struct sock_common,
                             skc_family,
                             2, target_size));
        break;
    case offsetof(struct __sk_buff, remote_ip4):
        BUILD_BUG_ON(sizeof_field(struct sock_common, skc_daddr) != 4);

        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
                      si->dst_reg, si->src_reg,
                      offsetof(struct sk_buff, sk));
        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
                      bpf_target_off(struct sock_common,
                             skc_daddr,
                             4, target_size));
        break;
    case offsetof(struct __sk_buff, local_ip4):
        BUILD_BUG_ON(sizeof_field(struct sock_common,
                      skc_rcv_saddr) != 4);

        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
                      si->dst_reg, si->src_reg,
                      offsetof(struct sk_buff, sk));
        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
                      bpf_target_off(struct sock_common,
                             skc_rcv_saddr,
                             4, target_size));
        break;
    case offsetof(struct __sk_buff, remote_ip6[0]) ...
         offsetof(struct __sk_buff, remote_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
        BUILD_BUG_ON(sizeof_field(struct sock_common,
                      skc_v6_daddr.s6_addr32[0]) != 4);

        off = si->off;
        off -= offsetof(struct __sk_buff, remote_ip6[0]);

        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
                      si->dst_reg, si->src_reg,
                      offsetof(struct sk_buff, sk));
        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
                      offsetof(struct sock_common,
                           skc_v6_daddr.s6_addr32[0]) +
                      off);
#else
        *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
        break;
    case offsetof(struct __sk_buff, local_ip6[0]) ...
         offsetof(struct __sk_buff, local_ip6[3]):
#if IS_ENABLED(CONFIG_IPV6)
        BUILD_BUG_ON(sizeof_field(struct sock_common,
                      skc_v6_rcv_saddr.s6_addr32[0]) != 4);

        off = si->off;
        off -= offsetof(struct __sk_buff, local_ip6[0]);

        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
                      si->dst_reg, si->src_reg,
                      offsetof(struct sk_buff, sk));
        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->dst_reg,
                      offsetof(struct sock_common,
                           skc_v6_rcv_saddr.s6_addr32[0]) +
                      off);
#else
        *insn++ = BPF_MOV32_IMM(si->dst_reg, 0);
#endif
        break;

    case offsetof(struct __sk_buff, remote_port):
        BUILD_BUG_ON(sizeof_field(struct sock_common, skc_dport) != 2);

        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
                      si->dst_reg, si->src_reg,
                      offsetof(struct sk_buff, sk));
        *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
                      bpf_target_off(struct sock_common,
                             skc_dport,
                             2, target_size));
#ifndef __BIG_ENDIAN_BITFIELD
        *insn++ = BPF_ALU32_IMM(BPF_LSH, si->dst_reg, 16);
#endif
        break;

    case offsetof(struct __sk_buff, local_port):
        BUILD_BUG_ON(sizeof_field(struct sock_common, skc_num) != 2);

        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
                      si->dst_reg, si->src_reg,
                      offsetof(struct sk_buff, sk));
        *insn++ = BPF_LDX_MEM(BPF_H, si->dst_reg, si->dst_reg,
                      bpf_target_off(struct sock_common,
                             skc_num, 2, target_size));
        break;

    case offsetof(struct __sk_buff, tstamp):
        BUILD_BUG_ON(sizeof_field(struct sk_buff, tstamp) != 8);

        if (type == BPF_WRITE)
            *insn++ = BPF_STX_MEM(BPF_DW,
                          si->dst_reg, si->src_reg,
                          bpf_target_off(struct sk_buff,
                                 tstamp, 8,
                                 target_size));
        else
            *insn++ = BPF_LDX_MEM(BPF_DW,
                          si->dst_reg, si->src_reg,
                          bpf_target_off(struct sk_buff,
                                 tstamp, 8,
                                 target_size));
        break;

    case offsetof(struct __sk_buff, gso_segs):
        insn = bpf_convert_shinfo_access(si, insn);
        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_segs),
                      si->dst_reg, si->dst_reg,
                      bpf_target_off(struct skb_shared_info,
                             gso_segs, 2,
                             target_size));
        break;
    case offsetof(struct __sk_buff, gso_size):
        insn = bpf_convert_shinfo_access(si, insn);
        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct skb_shared_info, gso_size),
                      si->dst_reg, si->dst_reg,
                      bpf_target_off(struct skb_shared_info,
                             gso_size, 2,
                             target_size));
        break;
    case offsetof(struct __sk_buff, wire_len):
        BUILD_BUG_ON(sizeof_field(struct qdisc_skb_cb, pkt_len) != 4);

        off = si->off;
        off -= offsetof(struct __sk_buff, wire_len);
        off += offsetof(struct sk_buff, cb);
        off += offsetof(struct qdisc_skb_cb, pkt_len);
        *target_size = 4;
        *insn++ = BPF_LDX_MEM(BPF_W, si->dst_reg, si->src_reg, off);
        break;

    case offsetof(struct __sk_buff, sk):
        *insn++ = BPF_LDX_MEM(BPF_FIELD_SIZEOF(struct sk_buff, sk),
                      si->dst_reg, si->src_reg,
                      offsetof(struct sk_buff, sk));
        break;
    }

    return insn - insn_buf;
}

예를 들어, __sk_buff.gso_size 필드는 sk_buff 구조체의 skb_shared_info.gso_size 필드로 변환되는 식입니다.




그런데, 좀 모호한 면도 있습니다. 가령, __sk_buff.data 필드는 "__u32" 타입이지만 그것의 대응이 되는 sk_buff.data 필드는 포인터에 해당하는 "unsigned char *" 타입입니다. 그래서인지 모르겠지만 __sk_buff.data 필드를 직접 접근하면,

SEC("socket")
int socket_handler(struct __sk_buff *ctx)
{
    bpf_printk("[__sk_buff] data == %d\n", ctx->data);
    // ...[생략]...
}

eBPF 로딩 시 이런 오류가 발생합니다. (이에 대해서는 아래에서 더 다룰 것입니다.)

// 테스트 환경: Ubuntu 24.04 LTS

load program: permission denied: 0: (61) r3 = *(u32 *)(r1 +76): invalid bpf_context access off=76 size=4 (3 line(s) omitted)

// 76 오프셋은 struct __sk_buff.data 필드 위치

참고로, data 필드는 패킷의 시작 위치를 가리킨다고 합니다.

// struct sk_buff
// ; https://docs.kernel.org/networking/skbuff.html
//
// Measuring TCP Latency Using eBPF: Part 2 - Kernel Space - struct __sk_buff
// ; https://fiwippi.net/tcplat-p2
//
// struct sk_buff 관련 함수
// ; https://hand-over.tistory.com/2

    sk_buff.data --> +-----------------+
                     | Ethernet Header |
                     +-----------------+
                     |    IP Header    |
sk_buff.data_end --> +-----------------+
                     |   TCP Header    |
                     +-----------------+
                     |     Payload     |
                     +-----------------+

다행히 eBPF에서는 저 영역을 접근할 수 있는 도우미 함수를 제공하는데요,

Helper function bpf_skb_load_bytes (커널 버전 4.5)
; https://docs.ebpf.io/linux/helper-function/bpf_skb_load_bytes/

관련해서 검색해 보면 "L7 Tracing with eBPF: HTTP and Beyond via Socket Filters and Syscall Tracepoints" 글에 bpf_skb_load_bytes 함수를 사용한 예제가 나옵니다.

SEC("socket")
int socket_handler(struct __sk_buff *skb)
{
    __u16 proto;

    bpf_skb_load_bytes(skb, 12, &proto, 2);
    proto = __bpf_ntohs(proto);

    return skb->len;

/* proto 값의 예:
0x0800 for IPv4
0x0806 for ARP
0x86DD for IPv6
*/
}

위의 코드를 해석해 보면, skb->data 필드가 가리키는 위치가 ethernet 헤더의 시작 위치이므로,

// cat vmlinux.h | grep -A 18 "struct ethhdr {"

struct ethhdr {
        unsigned char h_dest[6];  // offset 0
        unsigned char h_source[6]; // offset 6
        __be16 h_proto; // offset 12
};

0 1 2 3 4 5 6 7 8 9 0 1 2 3 4
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|h_dest     | h_source  |** |  // (** h_proto)
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ 

결과적으로, 12 위치는 h_proto 필드의 offset 값이 됩니다. 즉, protocol 값을 가져오는 것인데요, 그런데 제 실습 환경에서 실행해 보면 엉뚱한 값이 나왔습니다.

// TCP 소켓 예제에서 출력된 h_proto 값들

bpf_trace_printk: __sk_buff.h_proto == 8019
bpf_trace_printk: __sk_buff.h_proto == b010
bpf_trace_printk: __sk_buff.h_proto == 5014
bpf_trace_printk: __sk_buff.h_proto == 5004

반면 ctx->protocol 필드를 직접 읽어오면, (TCP 소켓 예제이므로) 항상 정확하게 ETH_P_IP에 해당하는 8(BE 표현으로는 0x0800) 값이 나옵니다. 이해할 수 없군요, ^^ 분명히 "L7 Tracing with eBPF: HTTP and Beyond via Socket Filters and Syscall Tracepoints" 글에서의 코드와 같은데... 이유를 모르겠습니다. (혹시 아시는 분은 덧글 부탁드립니다. ^^;)

이와 관련해 좀 더 검색했더니 SEC("tc") 프로그램 예제가 나오는데요,

hello-libbpfgo/25-tc-parse-packet-with-direct-memory-access/main.bpf.c
; https://github.com/mozillazg/hello-libbpfgo/blob/master/25-tc-parse-packet-with-direct-memory-access/main.bpf.c#L24

Measuring TCP Latency Using eBPF: Part 2 - Kernel Space
; https://fiwippi.net/tcplat-p2

SEC("tc")
int handle_ingress(struct __sk_buff *skb) {
    bpf_skb_pull_data(skb, 0);

    void *data_end = (void *)(long)skb->data_end;
    void *data = (void *)(long)skb->data;

    struct iphdr *ip_hdr = data + ETH_HLEN;
    if ((void *)ip_hdr + sizeof(struct iphdr) > data_end) {
        return TC_ACT_OK;
    }

    // ...[생략]...
}

오호~~~ 32비트 값을 포인터로 변환해 사용하고 있습니다. 리눅스 커널은 저런 구조체를 4GB 하위에 할당하는 걸까요? (그러고 보니 전에도 한 번 이와 관련한 의문을 남긴 적이 있습니다.) 과연 이것을 올바른 예제라고 봐야 할지 모르겠지만... 어쨌든 동작했으니까 ^^ 저렇게 github에 올렸을 것입니다. 그리고 위의 예제에서 특이한 점은 bpf_skb_pull_data 함수를 사용했다는 점인데,

Helper function bpf_skb_pull_data (커널 버전 4.9)
; https://docs.ebpf.io/linux/helper-function/bpf_skb_pull_data/

문서에 보면, skb.data 영역을 접근할 수 있는 용도로 제공한 첫 번째 함수가 bpf_skb_load_bytes였고, 두 번째로 나온 것이 "direct packet access"를 가능하게 만든 bpf_skb_pull_data였다고 합니다. (이후 Linux 4.7부터는 bpf_skb_load_bytes 함수도 "direct packet access"를 지원하게 돼 이제는 그런 차이는 없어졌습니다.)

참고로, bpf_skb_pull_data는 SEC("socket")에 해당하는 BPF_PROG_TYPE_SOCKET_FILTER 프로그램에서는 사용할 수 없습니다.

SEC("socket") // SEC("tc")에서는, 즉 BPF_PROG_TYPE_SCHED_CLS 유형의 프로그램에서는 bpf_skb_pull_data 사용 불가능
int socket_handler(struct __sk_buff *ctx)
{
    bpf_skb_pull_data(ctx, 0); // eBPF 프로그램 로딩 시 오류 발생: invalid argument: program of this type cannot use helper bpf_skb_pull_data#39 (7 line(s) omitted)

    return ctx->len;
}




github에 있는 다른 예제를 하나 더 테스트해 봤는데요,

// https://github.com/mozillazg/hello-libbpfgo/blob/master/19-socket-filter-capture-icmp-traffic-userspace-parse/main.bpf.c

#include "vmlinux.h"

#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#include <bpf/bpf_endian.h>

unsigned long long load_half(void *skb, unsigned long long off) asm("llvm.bpf.load.half");

SEC("socket")
int socket_handler(struct __sk_buff *ctx)
{
    // load_half 함수는 data 포인터가 가리키는 영역으로부터 offset 위치의 16비트 값을 읽어오는 도우미 함수
    __u16 proto = load_half(ctx, offsetof(struct ethhdr, h_proto));
    bpf_printk("ethhdr.h_proto == %04x, protocol == %04x\n", proto, __bpf_htons(ctx->protocol));

    return ctx->len;
}

// ETH_P_IP == 0x0800

이것 역시 ETH_P_IP 값이 나오는 것으로 사용하고 있지만, 제가 테스트한 Ubuntu 24.04 환경에서는 다른 결과가 나옵니다.

bpf_trace_printk: ethhdr.h_proto == 8019, protocol == 0800
bpf_trace_printk: ethhdr.h_proto == 8010, protocol == 0800
bpf_trace_printk: ethhdr.h_proto == 5014, protocol == 0800

원래 의도했던 값은 h_proto와 protocol 값이 같아야 할 텐데, 이번에도 protocol은 정상인 반면 h_proto는 (if_ether.h에는 없는) 이상한 값이 나옵니다.




마지막으로 "Understanding struct __sk_buff" 글에 보면, "Notice that the base address is same for both sk_buff and __sk_buff."라는 설명도 나옵니다. 그렇다면 struct sk_buff *skb로 대체해도 되는 걸까요?

하지만, 이것 역시 실제로 해보면,

SEC("socket")
int socket_handler(struct sk_buff *ctx)
{
    return ctx->len;
}

eBPF 로더에서 오류가 발생합니다.

load program: permission denied: 0: (79) r3 = *(u64 *)(r1 +112): invalid bpf_context access off=112 size=8 (3 line(s) omitted)

// 112 오프셋은 struct sk_buff.len 필드 위치

따라서 eBPF 프로그램에 따라 struct __sk_buff와 struct __sk_buff 타입은 정해진 대로 구별해서 사용해야 하는 것이 맞습니다. 찾아보면, StackOverflow 글에서도 이에 대한 언급이 있군요. ^^

Cannot access __skb_buff in eBPF
; https://stackoverflow.com/questions/72717564/cannot-access-skb-buff-in-ebpf

First is that the argument to the tracepoint is of type struct sk_buff, not struct __sk_buff.





암튼, eBPF를 무작위로 공부하고는 있지만 실습도 잘 안되는 예제들이 있어 답답한 면이 좀 있습니다. ^^ 그나마 다행인 것은 리눅스 커널 소스 코드가 공개인 덕분에 많은 Q&A에서 소스 코드를 함께 언급하며 설명하고 있어 이해하는 데 도움은 되고 있다는 점입니다.




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 10/1/2025]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13770정성태10/17/202410223Linux: 87. ps + grep 조합에서 grep 명령어를 사용한 프로세스를 출력에서 제거하는 방법
13769정성태10/15/202411483Linux: 86. Golang + bpf2go를 사용한 eBPF 기본 예제파일 다운로드1
13768정성태10/15/202410112C/C++: 179. C++ - _O_WTEXT, _O_U16TEXT, _O_U8TEXT의 Unicode stream 모드파일 다운로드2
13767정성태10/14/20248304오류 유형: 929. bpftrace 수행 시 "ERROR: Could not resolve symbol: /proc/self/exe:BEGIN_trigger"
13766정성태10/14/20247461C/C++: 178. C++ - 파일에 대한 Text 모드의 "translated" 동작파일 다운로드1
13765정성태10/12/202410080오류 유형: 928. go build 시 "package maps is not in GOROOT" 오류
13764정성태10/11/202411449Linux: 85. Ubuntu - 원하는 golang 버전 설치
13763정성태10/11/20248792Linux: 84. WSL / Ubuntu 20.04 - bpftool 설치
13762정성태10/11/20249208Linux: 83. WSL / Ubuntu 22.04 - bpftool 설치
13761정성태10/11/20248523오류 유형: 927. WSL / Ubuntu - /usr/include/linux/types.h:5:10: fatal error: 'asm/types.h' file not found
13760정성태10/11/202410335Linux: 82. Ubuntu - clang 최신(stable) 버전 설치
13759정성태10/10/202411268C/C++: 177. C++ - 자유 함수(free function) 및 주소 지정 가능한 함수(addressable function) [6]
13758정성태10/8/20249992오류 유형: 926. dotnet tools를 sudo로 실행하는 경우 command not found
13757정성태10/8/202410431닷넷: 2306. Linux - dotnet tool의 설치 디렉터리가 PATH 환경변수에 자동 등록이 되는 이유
13756정성태10/8/202410496오류 유형: 925. ssh로 docker 접근을 할 때 "... malformed HTTP status code ..." 오류 발생
13755정성태10/7/202411012닷넷: 2305. C# 13 - (9) 메서드 바인딩의 우선순위를 지정하는 OverloadResolutionPriority 특성 도입 (Overload resolution priority)파일 다운로드1
13754정성태10/4/20249908닷넷: 2304. C# 13 - (8) 부분 메서드 정의를 속성 및 인덱서에도 확대파일 다운로드1
13753정성태10/4/20249286Linux: 81. Linux - PATH 환경변수의 적용 규칙
13752정성태10/2/202410854닷넷: 2303. C# 13 - (7) ref struct의 interface 상속 및 제네릭 제약으로 사용 가능 [6]파일 다운로드1
13751정성태10/2/20248518C/C++: 176. C/C++ - ARM64로 포팅할 때 유의할 점
13750정성태10/1/20248319C/C++: 175. C++ - WinMain/wWinMain 호출 전의 CRT 초기화 단계
13749정성태9/30/20249049닷넷: 2302. C# - ssh-keygen으로 생성한 Private Key와 Public Key 연동파일 다운로드1
13748정성태9/29/20249333닷넷: 2301. C# - BigInteger 타입이 byte 배열로 직렬화하는 방식
13747정성태9/28/202410783닷넷: 2300. C# - OpenSSH의 공개키 파일에 대한 "BEGIN OPENSSH PUBLIC KEY" / "END OPENSSH PUBLIC KEY" PEM 포맷파일 다운로드1
13746정성태9/28/20248970오류 유형: 924. Python - LocalProtocolError("Illegal header value ...")
13745정성태9/28/20248752Linux: 80. 리눅스 - 실행 중인 프로세스 내부의 환경변수 설정을 구하는 방법 (lldb)
1  2  3  4  5  6  7  8  9  10  [11]  12  13  14  15  ...