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

(시리즈 글이 3개 있습니다.)
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

Linux: 131. eBPF - bpf_skb_load_bytes를 이용한 __sk_buff.data 영역의 TCP payload 접근
; https://www.sysnet.pe.kr/2/0/14039




eBPF - bpf_skb_load_bytes를 이용한 __sk_buff.data 영역의 TCP payload 접근

지난 글에서,

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

__sk_buff.data의 IP/TCP 헤더를 접근해 봤는데요, 이번엔 TCP Header를 넘어 사용자가 Socket에서 send/receive한 데이터를 접근해 보겠습니다. 이를 위해 기존의 print_sk_buff 소스 코드에 약간의 코드를 추가해 볼 수 있습니다.

// TCP header, TCP header size, TCP checksum mechanism, TCP header structure, options, and format
// https://www.noction.com/blog/tcp-header
//
// L7 Tracing with eBPF: HTTP and Beyond via Socket Filters and Syscall Tracepoints
// ; https://eunomia.dev/en/tutorials/23-http/

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;

    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;

    __u32 ip_tcp_header_legnth = ip_header_length + tcp_header_length;

    __u32 total_packet_length = __bpf_ntohs(iph.tot_len);
    __u32 tcp_payload_length = total_packet_length - ip_tcp_header_legnth;

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

    if (tcp_payload_length >= 4) {
        __u8 packet_data[4];
        result = bpf_skb_load_bytes_relative(skb, ip_tcp_header_legnth, &packet_data, 4, BPF_HDR_START_NET); // (EFAULT 14 Bad address)
        bpf_printk("[%s]: pakcet: result = %d, sk_buff = %p", title, result, skb);
        bpf_printk("First-4bytes: %c, %c, %c, %c", packet_data[0], packet_data[1], packet_data[2], packet_data[3]);
    }
}

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;
}

그런데 막상 실행해 보면 마지막 bpf_skb_load_bytes_relative에서 -14, 즉 "EFAULT(Bad address)" 오류가 발생하는 것을 볼 수 있습니다. 재미있는 것은, skb->len의 값을 조사해 보면, IP 헤더 + TCP 헤더 + TCP payload를 모두 더한 값과 일치합니다.

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

/* 출력 예
[egress]: len(IPHeader) = 20, len(TCPHeader) = 40, len(TCPPayload) = 0
[egress]: skb->len: 60

[egress]: len(IPHeader) = 20, len(TCPHeader) = 32, len(TCPPayload) = 57
[egress]: skb->len: 109

[egress]: len(IPHeader) = 20, len(TCPHeader) = 32, len(TCPPayload) = 0
[egress] skb->len: 52
*/

그렇다면 분명히 egress 문맥에서도 payload 데이터가 존재할 텐데도... 접근은 안 되는 것입니다.

다른 방법으로, 혹시나 싶어 bpf_skb_pull_data를 호출해 봤는데요,

// non-linear 대비: 필요한 부분을 head로 당겨오기
//                  (tcp_data_offset + 4) 바이트가 선형으로 보장되도록 요청
if (bpf_skb_pull_data(skb, ip_tcp_header_legnth + 4) < 0) {
    bpf_printk("failed to pull data len = %d, at = %d", want_bytes, ip_tcp_header_legnth);
    return 1;
}

아예 eBPF 프로그램 로딩 단계에서 오류가 발생해 실행조차 하지 못합니다.

load program: invalid argument: program of this type cannot use helper bpf_skb_pull_data#39 (73 line(s) omitted)

오류 메시지에서 알려 주듯이, bpf_skb_pull_data 함수의 지원 프로그램은,

  • BPF_PROG_TYPE_LWT_IN
  • BPF_PROG_TYPE_LWT_OUT
  • BPF_PROG_TYPE_LWT_SEG6LOCAL
  • BPF_PROG_TYPE_LWT_XMIT
  • BPF_PROG_TYPE_SCHED_ACT
  • BPF_PROG_TYPE_SCHED_CLS
  • BPF_PROG_TYPE_SK_SKB

유형에서만 사용할 수 있기 때문에 BPF_PROG_TYPE_CGROUP_SKB에서는 eBPF verifier가 저렇게 거부를 하는 것입니다.

다시 말해, (제가 아는 수준에서는) BPF_PROG_TYPE_CGROUP_SKB 프로그램의 경우 TCP payload를 읽어올 수 없습니다.




재미있게도, 동일한 소스 코드를 BPF_PROG_TYPE_SOCKET_FILTER 유형에서 실행하면 정상적으로 TCP payload 영역을 접근할 수 있습니다.

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

예제에서는 최초 4바이트를 출력하게 했는데요, BPF_PROG_TYPE_SOCKET_FILTER가 ingoing 패킷만 다루므로 외부로 요청한 HTTP 호출에 대해 응답에 해당하는 "H, T, T, P"가 찍히는 것을 확인할 수 있습니다.

결국, 동일하게 "struct __sk_buff *skb" 구조체를 인자로 받는 eBPF 함수라고 해도, 프로그램 문맥에 따라 1) bpf_skb_load_bytes/bpf_skb_load_bytes_relative의 반환값도 다르고, 2) payload 접근 유무도 다릅니다.




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







[최초 등록일: ]
[최종 수정일: 11/8/2025]

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

비밀번호

댓글 작성자
 




... 196  197  198  199  200  [201]  202 
NoWriterDateCnt.TitleFile(s)
33정성태7/17/200327167VS.NET IDE: 3. Win2000 NAT 서비스
32정성태7/17/200328473COM 개체 관련: 9. _bstr_t, CComBSTR, string 클래스 사용 [1]
31정성태7/17/200325374COM 개체 관련: 8. IDL 구문에서 구조체를 pack 하는 방법
30정성태7/17/200342936VC++: 7. [STL] vector 사용법 및 reference 사용예 [1]파일 다운로드1
28정성태7/17/200327103스크립트: 3. Programming Microsoft Internet Explorer 5 - CHM 파일
29정성태7/17/200326635    답변글 스크립트: 3.1. Programming Microsoft Internet Explorer 5 - 소스코드
27정성태7/17/200325540COM 개체 관련: 7. HTML Control에서 DELETE, 화살표 키 등이 안 먹는 문제
26정성태7/17/200326469COM 개체 관련: 6. WebBrowser 콘트롤에서 프레임을 구하는 소스
25정성태7/17/200324249COM 개체 관련: 5. C++ Attributes - Make COM Programming a Breeze with New Feature in Visual Studio .NET [2]파일 다운로드1
24정성태7/17/200328148.NET Framework: 5. (MHT 변환해서 가져온 글) .NET 의 COM+ 서비스 사용파일 다운로드1
23정성태7/17/200331625.NET Framework: 4. webservice.htc - HTML Script에서도 웹서비스 엑세스 [2]파일 다운로드1
22정성태7/17/200326064.NET Framework: 3. .NET Framework SDK 퀵 스타트 자습서
21정성태7/17/200325313.NET Framework: 2. 김현승님의 "ASP.NET & .NET EnterpriseServices & Remoting 코드 템플릿"
20정성태2/15/200532840VS.NET IDE: 2. Platform SDK 설치
19정성태7/17/200328496.NET Framework: 1. JScript.NET 강좌 사이트[영문]
18정성태7/17/200325700COM 개체 관련: 4. Exchanging Data Over the Internet Using XML [1]파일 다운로드1
17정성태7/17/200333426VC++: 6. Win32 API Hook - 소스는 "공개소스"에있습니다. [2]
16정성태7/17/200326091COM 개체 관련: 3. IE 툴밴드의 위치문제파일 다운로드1
15정성태7/17/200326925VC++: 5. 시행착오 - 클래스 포인터를 void * 로 대입후 delete 하는 경우.
14정성태7/17/200328674VC++: 4. MFC Message 처리 구조
13정성태7/17/200328386VC++: 3. template 활용의 최고 단계!
12정성태5/7/200626208VC++: 2. void func1( MYCLASS *&pBuildingElement ); 선언의 의미
10정성태7/17/200324373기타: 2. 데브피아 사이트의 클럽 서비스 내에 있는 Standard C++ Research
9정성태7/17/200330039기타: 1. Programming Applications for Microsoft Windows 4th Edition
8정성태7/17/200327449COM 개체 관련: 2. CWindowImpl 의 기본 윈도우 클래스 명을 바꾸려면?
7정성태7/17/200330085VS.NET IDE: 1. VC++ 프로파일링 사용법
... 196  197  198  199  200  [201]  202