Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

(시리즈 글이 2개 있습니다.)
Linux: 124. eBPF - __sk_buff / sk_buff 구조체
; https://www.sysnet.pe.kr/2/0/14019

Linux: 130. eBPF - bpf_skb_load_bytes를 이용한 __sk_buff.data 영역의 IP/TCP 헤더 해석
; https://www.sysnet.pe.kr/2/0/14038




eBPF - bpf_skb_load_bytes를 이용한 __sk_buff.data 영역의 IP/TCP 헤더 해석

지난 글에서,

eBPF - __sk_buff / sk_buff 구조체
; https://www.sysnet.pe.kr/2/0/14019

__sk_buff 구조체에 대한 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); // 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

    return skb->len;

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

그래도 뭔가, 값이 고정적으로 나오는 것 같아서 한 번 더 확인해 봤습니다. 가만 보니까, bpf_skb_load_bytes 말고 또 다른 함수가 있는데요,

bpf_skb_load_bytes_relative
; https://docs.ebpf.io/linux/helper-function/bpf_skb_load_bytes_relative/

그러니까, __sk_buff.data의 BPF_HDR_START_MAC과 BPF_HDR_START_NET 헤더를 상대적으로 접근할 수 있게 해주는데, 실제로 이걸로 했더니 값이 제대로 나왔습니다.

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

   // 기존 코드를 주석 처리
   // bpf_skb_load_bytes(skb, 12, &proto, 2);

   // 새롭게 bpf_skb_load_bytes_relative를 이용해 MAC 헤더 기준으로 protocol offset 지정
   bpf_skb_load_bytes_relative(skb, 12, &proto, 2, BPF_HDR_START_MAC);
   proto = __bpf_ntohs(proto);
  
   bpf_printk("__sk_buff.h_proto == %04x, protocol == %04x\n", proto, __bpf_htons(skb->protocol));

   return skb->len;
}

/* 출력 결과:
__sk_buff.h_proto == 0800, protocol == 0800
*/




그렇다면 bpf_skb_load_bytes와 어떤 차이가 있는 걸까요? 이를 알아보기 위해 2개의 함수 모두 offset 0부터 48바이트를 읽어 출력해 비교했는데,

char buff_org[48];
bpf_skb_load_bytes(skb, 0, buff_org, 48);

char buff_rel[48];
bpf_skb_load_bytes_relative(skb, 0, buff_rel, 48, BPF_HDR_START_MAC);

다음과 같이 정리됩니다.

// buff_org
00,50,ec,04,d4,0c,15,af,15,ee,4d,ec,80,19,08,21,44,a9,00,00,01,01,08,0a,8d,82,2d,27,5c,51,00,cf,48,54,54,50,2f,31,2e,31,20,32,30,30,20,4f,4b,0d

// buff_rel
00,15,5d,28,cf,04,00,15,5d,00,05,06,08,00,45,00,03,fe,0a,24,40,00,80,06,6b,44,c0,a8,00,24,c0,a8,00,1d,00,50,ec,04,d4,0c,15,af,15,ee,4d,ec,80,19

그러니까, bpf_skb_load_bytes_relative는 MAC 헤더로부터 내용을 출력한 반면 bpf_skb_load_bytes는 그로부터 다소 떨어진 위치의 내용을 반환하고 있었던 것입니다. 그렇다면 정확히 어떤 위치인지 확인해 보기 위해 헤더에 따라 계산을 해보았습니다.

방법은, ethhdr, iphdr, tcphdr 구조체에 따라 buff_rel의 내용을 이렇게 분석해 나가면 됩니다.

struct ethhdr {
        unsigned char h_dest[6];    // 00,15,5d,28,cf,04
        unsigned char h_source[6];  // 00,15,5d,00,05,06
        __be16 h_proto;             // 08,00
};

struct iphdr {
                            // 0x45 == 0100 0101
        __u8 ihl: 4;        // == 0101 == 5 (헤더 길이, 5 * 4 = 20바이트)
        __u8 version: 4;    // == 0100 == 4 (IPv4 버전)

        __u8 tos;           // 00
        __be16 tot_len;     // 03,fe
        __be16 id;          // 0a,24
        __be16 frag_off;    // 40,00
        __u8 ttl;           // 80
        __u8 protocol;      // 06 (TCP)
        __sum16 check;      // 6b,44
        union {
                struct {
                        __be32 saddr; // c0,a8,00,24
                        __be32 daddr; // c0,a8,00,1d
                };
                struct {
                        __be32 saddr;
                        __be32 daddr;
                } addrs;
        };
};

struct tcphdr {
        __be16 source;  // 00,50
        __be16 dest;    // ec,04
        __be32 seq;     // d4,0c,15,af
        __be32 ack_seq; // 15,ee,4d,ec

                        // 0x80 == 1000 0000
        __u16 res1: 4;  // == 1000
        __u16 doff: 4;  // == 0000 (데이터 오프셋, 0 * 4 = 0바이트)
        __u16 fin: 1;
        __u16 syn: 1;
        __u16 rst: 1;
        __u16 psh: 1;
        __u16 ack: 1;
        __u16 urg: 1;
        __u16 ece: 1;
        __u16 cwr: 1;
        __be16 window;
        __sum16 check;
        __be16 urg_ptr;
};

아하~~~ bpf_skb_load_bytes가 반환한 위치는 TCP 헤더의 시작 부분이었던 것입니다. 이에 비춰 아래의 글에 나온 소스 코드를 다시 볼까요?

L7 Tracing with eBPF: HTTP and Beyond via Socket Filters and Syscall Tracepoints
; https://eunomia.dev/en/tutorials/23-http/

SEC("socket")
int socket_handler(struct __sk_buff *skb)
{
    struct so_event *e;
    __u8 verlen;
    __u16 proto;
    __u32 nhoff = ETH_HLEN;
    __u32 ip_proto = 0;
    __u32 tcp_hdr_len = 0;
    __u16 tlen;
    __u32 payload_offset = 0;
    __u32 payload_length = 0;
    __u8 hdr_len;

    bpf_skb_load_bytes(skb, 12, &proto, 2);
    proto = __bpf_ntohs(proto);
    if (proto != ETH_P_IP)
        return 0;

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

    return skb->len;
}

현재 기준으로 보면 저런 동작이 가능했던 것이 도저히 설명이 안 됩니다. 아마도 당시의 리눅스 커널은 저게 가능했었다고... 생각하고 지나가야 할 것 같습니다. (혹시 이에 관한 이력을 아시는 분은 덧글 부탁드립니다. ^^)

아무튼, 저 코드는 이제 다음과 같은 식으로 작성해야 동작합니다.

// TCP header, TCP header size, TCP checksum mechanism, TCP header structure, options, and format
// https://www.noction.com/blog/tcp-header

static void print_sk_buff(char* title, struct __sk_buff *skb) {
    struct iphdr iph;
    long result = bpf_skb_load_bytes_relative(skb, 0, &iph, sizeof(struct iphdr), BPF_HDR_START_NET);
    if (result != 0) {
        bpf_printk("[%s]: unexpected-packet = %d", title, result);
        return;
    }

    if (iph.protocol != IPPROTO_TCP) {
        bpf_printk("[%s]: !tcp_packet(protocol = %d)", title, iph.protocol);
        return;
    }

    __u8 ip_header_length = iph.ihl * 4; // IP Header 크기

    struct tcphdr tcph;
    result = bpf_skb_load_bytes_relative(skb, ip_header_length, &tcph, sizeof(struct tcphdr), BPF_HDR_START_NET);
    __u8 tcp_header_length = tcph.doff * 4; // TCP Header 크기

    __u32 ip_tcp_header_legnth = ip_header_length + tcp_header_length; // (IP Header + TCP Header) 크기

    __u32 total_packet_length = __bpf_ntohs(iph.tot_len); // 패킷의 전체 크기
    __u32 tcp_payload_length = total_packet_length - ip_tcp_header_legnth; // TCP Payload 크기

    bpf_printk("[%s]: len(IPHeader) = %d, len(TCPHeader) = %d, len(TCPPayload) = %d", title, ip_header_length, tcp_header_length, tcp_payload_length);
}

SEC("socket")
int socket_handler(struct __sk_buff *skb) {
    print_sk_buff("socket", skb);
    return skb->len;
}

정리해 보면, (과거에는 어땠는지 모르겠지만) 현재 __sk_buff.data 필드에 대한 데이터는 다음과 같은 기준으로 가져올 수 있습니다.

// BPF_PROG_TYPE_SOCKET_FILTER 유형

bpf_skb_load_bytes_relative(BPF_HDR_START_MAC) - MAC 헤더를 시작점으로 offset 지정
bpf_skb_load_bytes_relative(BPF_HDR_START_NET) - IP 헤더를 시작점으로 offset 지정
bpf_skb_load_bytes - TCP 헤더를 시작점으로 offset 지정




문제는, bpf_skb_load_bytes가 언제나 TCP 헤더를 시작점으로 잡지는 않는다는 것입니다. 테스트해 보면, 저렇게 나오는 경우는 BPF_PROG_TYPE_SOCKET_FILTER 유형의 SEC("socket") 프로그램에서 그런 것이고, 다른 유형, 예를 들어 BPF_PROG_TYPE_CGROUP_SKB 프로그램에서는 전혀 다른 위치가 나옵니다.

예를 들어 아래의 코드를 테스트하면,

SEC("cgroup_skb/egress")
int cgroup_egress_packets(struct __sk_buff *skb) {
    __u8 buff_rel[48];
    bpf_skb_load_bytes_relative(skb, 0, buff_rel, 48, BPF_HDR_START_MAC); // EFAULT 14 Bad address

    return 1;
}

bpf_skb_load_bytes_relative 함수가 -14를 반환했습니다. 반면 BPF_HDR_START_MAC이 아닌 BPF_HDR_START_NET을 옵션으로 줬더니 성공했습니다. 다시 말해, bpf_skb_load_bytes_relative 함수라고 해도 어떤 eBPF 프로그램 유형에서 불리느냐에 따라 성공/실패로 나뉠 수 있습니다.

또한, bpf_skb_load_bytes 함수가 반환한 데이터와 비교하면,

int cgroup_egress_packets(struct __sk_buff *skb) {
    __u8 buff_org[48];
    bpf_skb_load_bytes(skb, 0, buff_org, 48);

    __u8 buff_rel[48];
    bpf_skb_load_bytes_relative(skb, 0, buff_rel, 48, BPF_HDR_START_NET);

    return 1;
}

buff_org와 buff_rel 데이터가 완전히 동일합니다. 그러니까, BPF_PROG_TYPE_CGROUP_SKB 프로그램에서의 호출 결과는 다음과 같이 정리가 됩니다.

// BPF_PROG_TYPE_CGROUP_SKB 유형

bpf_skb_load_bytes_relative(BPF_HDR_START_MAC) - 오류 발생 (EFAULT 14 Bad address)
bpf_skb_load_bytes_relative(BPF_HDR_START_NET) - IP 헤더를 시작점으로 offset 지정
bpf_skb_load_bytes - IP 헤더를 시작점으로 offset 지정

이러한 차이점에 대해 Google AI 검색에서는 다음과 같은 설명을 하고 있습니다.

cgroup_skb programs: Attached to a cgroup, these programs operate higher in the stack, where packets have already been associated with a socket and the L2 header has often been stripped. The cgroup context is associated with a specific process or set of processes, and the BPF program inspects traffic from the perspective of that application, not the raw network interface.


기왕에 예제를 작성했으니 앞서 작성한 print_sk_buff 함수를 BPF_PROG_TYPE_CGROUP_SKB 프로그램에서도 사용해 볼까요?

SEC("cgroup_skb/ingress")
int test_ingress_packets(struct __sk_buff *skb) {
    print_sk_buff("ingress", skb);
    return 1;
}

SEC("cgroup_skb/egress")
int test_egress_packets(struct __sk_buff *skb) {
    print_sk_buff("egress", skb);
    return 1;
}

SEC("cgroup/connect4")
int socket_connect4(struct bpf_sock_addr *ctx)
{
    struct bpf_sock* bpf_sk = ctx->sk;
    bpf_printk("[socket_connect4] bpf_sk == %p\n", bpf_sk);

    return SYS_PROCEED;
}

동작을 테스트하기 위해 HTTP 요청을 직접 Socket을 사용해 다음과 같이 다루는 경우,

var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
int readCount = 0;

socket.Connect("www.sysnet.pe.kr", 80);

string request = "GET / HTTP/1.1\r\nHost: sysnet.pe.kr\r\nConnection: close\r\n\r\n";
byte[] requestBytes = Encoding.ASCII.GetBytes(request);
Console.WriteLine($"Socket payload size: {requestBytes.Length} bytes");

socket.Send(requestBytes);

var buffer = new byte[4096];
int bytesReceived;
var response = new StringBuilder();

do
{
    readCount++;
    bytesReceived = socket.Receive(buffer);
    response.Append(Encoding.ASCII.GetString(buffer, 0, bytesReceived));
                    
} while (bytesReceived > 0);

Console.WriteLine($"{socket.LocalEndPoint} <==> {socket.RemoteEndPoint}, # of reads: {readCount}");
socket.Close();

실행해 보면 이런 식의 로그를 얻게 됩니다.

bpf_trace_printk: [socket_connect4] bpf_sk == 00000000883b5933
bpf_trace_printk: [egress]: !tcp_packet(protocol = 17)
bpf_trace_printk: [ingress]: !tcp_packet(protocol = 17)
bpf_trace_printk: [egress]: !tcp_packet(protocol = 17)
bpf_trace_printk: [ingress]: !tcp_packet(protocol = 17)

bpf_trace_printk: [socket_connect4] bpf_sk == 000000001740e3bf
bpf_trace_printk: [egress]: len(IPHeader) = 20, len(TCPHeader) = 40, len(TCPPayload) = 0
bpf_trace_printk: [egress]: len(IPHeader) = 20, len(TCPHeader) = 32, len(TCPPayload) = 57
bpf_trace_printk: [egress]: len(IPHeader) = 20, len(TCPHeader) = 32, len(TCPPayload) = 0

첫 번째 socket_connect4의 경우 이후 protocol == 17(IPPROTO_UDP)인 걸로 봐서 아마도 DNS 조회인 듯하고, 두 번째 socket_connect4 이후부터 HTTP 요청을 위한 TCP 통신의 결과로 나온 것 같습니다. 그런데, 이상하게도 HTTP 응답을 위한 ingress 로그가 없습니다. 왜일까요? ^^; (혹시 이유를 아시는 분은 덧글 부탁드립니다.)

이번엔 대충 여기까지... 살펴본 것으로 만족해야겠습니다. ^^




위의 프로그램을 테스트하다가 겪은 오류인데요, 만약 다음과 같이 코드를 만들면,

void print_sk_buff(char* title, struct __sk_buff *skb) {
    // ...[생략]...
}

SEC("cgroup_skb/ingress")
int test_ingress_packets(struct __sk_buff *skb) {
    print_sk_buff("ingress", skb);
    return 1;
}

SEC("cgroup_skb/egress")
int test_egress_packets(struct __sk_buff *skb) {
    print_sk_buff("egress", skb);
    return 1;
}

eBPF 로딩 시 이런 오류가 발생합니다.

load program: invalid argument: Caller passes invalid args into func#1 ('print_sk_buff') (8 line(s) omitted)

저 오류를 피하려면 print_sk_buff 함수를 명시적으로 static으로 지정해야 하는데요,

static void print_sk_buff(char* title, struct __sk_buff *skb) {
    // ...[생략]...
}

공식 문서에 보면,

eBPF Docs - Functions
; https://docs.ebpf.io/linux/concepts/functions/

딱히 static 함수여야 한다는 제약은 없습니다. 또한, 관련해서 리눅스 소스 코드도 찾아보면,

linux/kernel/bpf/verifier.c
; https://github.com/torvalds/linux/blob/master/kernel/bpf/verifier.c#L10636

// ...[생략]...
err = btf_check_subprog_call(env, subprog, caller->regs);
if (err == -EFAULT)
    return err;
if (subprog_is_global(env, subprog)) {
    const char *sub_name = subprog_name(env, subprog);

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

    if (err) {
        verbose(env, "Caller passes invalid args into func#%d ('%s')\n",
            subprog, sub_name);
        return err;
    }

    // ...[생략]...
    return 0;
}

static 예약어가 없다면 해당 C 함수는 global로 취급하는데요, 그런 상황에서 btf_check_subprog_call 함수가 오류 코드를 반환했다는 의미가 됩니다. 그렇다면, 반대로 static 함수인 경우라면 btf_check_subprog_call 함수에서 오류를 반환해도 상관없다는 것인데... 좀 이해가 안 되는 코드입니다. ^^;




마지막으로, 위의 BPF_PROG_TYPE_CGROUP_SKB 예제에서도 지난 글에서와 동일한 문제가 발생했는데요, 예를 들어, 다음의 코드는,

SEC("cgroup_skb/egress")
int cgroup_egress_packets(struct __sk_buff *skb) {
    struct bpf_sock *read_bpf_sock = (struct bpf_sock*)BPF_CORE_READ(skb, sk); // NULL 반환
    // 또는 이렇게 호출해도,
    // struct bpf_sock *read_bpf_sock = NULL;
    // int err = bpf_core_read(&read_bpf_sock, sizeof(void *), &skb->sk); // NULL 반환
}

반환값이 NULL이 나오고, 오히려 직접 접근하는 경우에는,

struct bpf_sock *direct_bpf_sock = skb->sk; // 포인터 주소 반환

정상적으로 포인터 값이 나옵니다. 도대체 왜 ^^; 저런 차이가 있는 걸까요? 후자의 경우처럼 직접 접근하는 코드가 동작한다고 해도, 때로는 BPF_CORE_READ를 사용해야만 하는 경우도 있기 때문에 마냥 무시할 수만은 없는 문제입니다.

암튼... 근래에 리눅스 환경을 다루면서 (결국엔 이유가 있겠지만) 수박 겉 핡기 식의 제 지식만으로는 당최 이해가 안 되는 상황들을 겪게 됩니다. ^^;




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







[최초 등록일: ]
[최종 수정일: 11/6/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)
13914정성태4/11/20258350디버깅 기술: 220. windbg 분석 사례 - x86 ASP.NET 웹 응용 프로그램의 CPU 100% 현상 (4)
13913정성태4/10/20256574오류 유형: 950. Process Explorer - 64비트 윈도우에서 32비트 프로세스의 덤프를 뜰 때 "Error writing dump file: Access is denied." 오류
13912정성태4/9/20255969닷넷: 2330. C# - 실행 시에 메서드 가로채기 (.NET 5 ~ .NET 8)파일 다운로드1
13911정성태4/8/20257071오류 유형: 949. WinDbg - .NET Core/5+ 응용 프로그램 디버깅 시 sos 확장을 자동으로 로드하지 못하는 문제
13910정성태4/8/20256399디버깅 기술: 219. WinDbg - 명령어 내에서 환경 변수 사용법
13909정성태4/7/20258875닷넷: 2329. C# - 실행 시에 메서드 가로채기 (.NET Framework 4.8)파일 다운로드1
13908정성태4/2/20259315닷넷: 2328. C# - MailKit: SMTP, POP3, IMAP 지원 라이브러리
13907정성태3/29/20259637VS.NET IDE: 198. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C# 프로젝트의 출력 경로 변경하기
13906정성태3/27/20259057닷넷: 2327. C# - 초기화되지 않은 메모리에 접근하는 버그?파일 다운로드1
13905정성태3/26/20259280Windows: 281. C++ - Windows / Critical Section의 안정화를 위해 도입된 "Keyed Event"파일 다운로드1
13904정성태3/25/20258537디버깅 기술: 218. Windbg로 살펴보는 Win32 Critical Section파일 다운로드1
13903정성태3/24/20258526VS.NET IDE: 197. (OneDrive, Dropbox 등의 공유 디렉터리에 있는) C++ 프로젝트의 출력 경로 변경하기
13902정성태3/24/20258301개발 환경 구성: 742. Oracle - 테스트용 hr 계정 및 데이터 생성파일 다운로드1
13901정성태3/9/20258637Windows: 280. Hyper-V의 3가지 Thread Scheduler (Classic, Core, Root)
13900정성태3/8/202510768스크립트: 72. 파이썬 - SQLAlchemy + oracledb 연동
13899정성태3/7/20257253스크립트: 71. 파이썬 - asyncio의 ContextVar 전달
13898정성태3/5/20257810오류 유형: 948. Visual Studio - Proxy Authentication Required: dotnetfeed.blob.core.windows.net
13897정성태3/5/20259742닷넷: 2326. C# - PowerShell과 연동하는 방법 (두 번째 이야기)파일 다운로드1
13896정성태3/5/20259768Windows: 279. Hyper-V Manager - VM 목록의 CPU Usage 항목이 항상 0%로 나오는 문제
13895정성태3/4/20259463Linux: 117. eBPF (bpf2go) - Map에 추가된 요소의 개수를 확인하는 방법
13894정성태2/28/20258454Linux: 116. eBPF (bpf2go) - BTF Style Maps 정의 구문과 데이터 정렬 문제
13893정성태2/27/20257677Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
13892정성태2/24/202510961닷넷: 2325. C# - PowerShell과 연동하는 방법파일 다운로드1
13891정성태2/23/20258368닷넷: 2324. C# - 프로세스의 성능 카운터용 인스턴스 이름을 구하는 방법파일 다운로드1
13890정성태2/21/20259518닷넷: 2323. C# - 프로세스 메모리 중 Private Working Set 크기를 구하는 방법(Win32 API)파일 다운로드1
13889정성태2/20/202510442닷넷: 2322. C# - 프로세스 메모리 중 Private Working Set 크기를 구하는 방법(성능 카운터, WMI) [1]파일 다운로드1
1  2  3  4  5  [6]  7  8  9  10  11  12  13  14  15  ...