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

비밀번호

댓글 작성자
 




... 151  152  153  154  155  156  157  158  159  160  161  162  163  [164]  165  ...
NoWriterDateCnt.TitleFile(s)
1065정성태6/13/201139750개발 환경 구성: 125. Firebird - 유니코드 기본 문자셋 지정
1064정성태6/11/201133971웹: 22. Visual Studio 2010에서 CSS 3 인텔리센스(intellisense) 지원하는 방법 [1]
1063정성태6/10/201136043웹: 21. Sysnet 웹 사이트의 CSS 2.1 변환 기록 [1]
1062정성태6/9/201135756웹: 20. Sysnet 웹 사이트의 HTML5 변환 기록 [1]
1061정성태6/8/201134466오류 유형: 125. 인터넷 익스플로러 - 개발자 도구에서 정지점(BP: Breakpoint) 설정이 안 되는 경우 [1]
1060정성태6/8/201130982VC++: 51. PHP 모듈의 F5 디버깅
1059정성태6/6/201135957VC++: 50. PHP 모듈 - php_mysql 빌드하는 방법파일 다운로드1
1058정성태6/5/201139920개발 환경 구성: 124. .NET 개발자가 처음 해보는 PHP + MySQL 연동 [2]
1057정성태6/4/201137317VC++: 49. 소스 코드로부터 php5apache2_2.dll 생성하는 방법파일 다운로드1
1056정성태6/2/201135697VC++: 48. 윈도우에서 Apache Module - Content Handler 컴파일파일 다운로드1
1055정성태6/1/201132790오류 유형: 124. MVC 프로젝트의 Site.Master 관련 오류 정리
1054정성태5/31/201136084.NET Framework: 220. ASP.NET MVC Web Site 프로젝트 - 단위 테스트 작성파일 다운로드1
1053정성태5/31/201139134VC++: 47. Apache Module에 대한 'F5 디버그 (Start with debugging)' [2]
1052정성태5/30/201136527.NET Framework: 219. ASP.NET MVC Web Site 프로젝트 구성하기파일 다운로드1
1051정성태5/28/201145038VC++: 46. 윈도우에서 Apache Module 컴파일 (VC++)파일 다운로드1
1050정성태5/28/201130851오류 유형: 123. Firebird - Exception of type 'FirebirdSql.Data.Common.IscException' was thrown.
1049정성태5/28/201136635.NET Framework: 218. WCF REST 서비스 - 웹 브라우저 측 Ajax 호출 캐시 [1]
1048정성태5/27/201138920개발 환경 구성: 123. Apache 소스를 윈도우 환경에서 빌드하기
1047정성태5/27/201131888.NET Framework: 217. Firebird ALinq Provider - 날짜 필드에 대한 낙관적 동시성 쿼리 오류
1046정성태5/26/201137379.NET Framework: 216. 라이선스까지도 뛰어넘는 .NET Profiler [5]
1045정성태5/24/201137907.NET Framework: 215. 닷넷 System.ComponentModel.LicenseManager를 이용한 라이선스 적용 [1]파일 다운로드1
1044정성태5/24/201139059오류 유형: 122. zlib 빌드 오류 - inflate.obj : error LNK2001: unresolved external symbol _inflate_fast
1043정성태5/24/201138586.NET Framework: 214. 무료 Linq Provider - DbLinq를 이용한 Firebird 접근파일 다운로드1
1042정성태5/23/201144362개발 환경 구성: 122. PHP 소스를 윈도우 환경에서 빌드하기
1041정성태5/22/201135323.NET Framework: 213. Linq To SQL - ALinq Provider를 이용하여 Firebird 사용파일 다운로드1
1040정성태5/21/201145966개발 환경 구성: 121. .NET 개발자가 처음 설치해 본 Apache + PHP [2]
... 151  152  153  154  155  156  157  158  159  160  161  162  163  [164]  165  ...