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

비밀번호

댓글 작성자
 




... 136  137  138  139  140  141  142  143  144  145  [146]  147  148  149  150  ...
NoWriterDateCnt.TitleFile(s)
1521정성태11/1/201335507VS.NET IDE: 79. IIS 7.5 - Global.asax.cs처럼 초기에 실행되는 코드에 Breakpoint를 잡는 방법
1520정성태10/31/201330774오류 유형: 191. Visual Studio 2010 - 웹 애플리케이션 생성 시 "The project type is not supported by this installation." 오류 발생 해결
1519정성태10/31/201356675기타: 36. SYSTEM 또는 TrustedInstaller 소유로 되어 있는 폴더/파일을 삭제하는 방법 [5]
1518정성태10/30/201334073VS.NET IDE: 78. Visual Studio 확장으로 XmlCodeGenerator 제작하는 방법
1517정성태10/28/201333405디버깅 기술: 56. 덤프 파일에 핸들/스레드 정보를 포함하는 방법 [1]
1516정성태10/28/201338848.NET Framework: 390. FolderBrowserDialog보다 더 쓸만한 대화창이 필요하다면? [1]
1515정성태10/24/201341244VS.NET IDE: 77. Visual Studio 확장(VSIX) 만드는 방법 [5]
1514정성태10/24/201374849개발 환경 구성: 202. Internet Explorer 11을 7, 8, 9, 10 버전으로 인식시키는 방법 [9]파일 다운로드1
1513정성태10/23/201330290개발 환경 구성: 201. Azure Blob Storage의 DNS 경로를 사용자 DNS로 바꾸는 방법 [1]
1512정성태10/18/201334053개발 환경 구성: 200. IIS AppPool의 실행 계정을 변경하는 방법
1511정성태10/12/201332177.NET Framework: 389. The 3n + 1 problem의 C#/Java 버전 풀이 [2]
1510정성태10/8/201333175오류 유형: 190. 윈도우 서버 2012 R2 설치 후 인텔 NIC으로 인한 WMI 오류 발생
1509정성태10/8/201337856오류 유형: 189. Windows Server 8.1/2012 R2 - IME 비정상 종료 현상 [1]
1508정성태10/4/201332930.NET Framework: 388. 일반 닷넷 프로젝트에서 WinRT API를 호출하는 방법 [2]파일 다운로드1
1507정성태9/30/201330829오류 유형: 188. The key 'LocalizedPerfCounter' does not exist in the appSettings configuration section.
1506정성태9/30/201333449오류 유형: 187. Parameter "basePath" cannot be a relative path
1505정성태9/26/201382417기타: 35. Microsoft Office 2007 인증 생략하는 방법 [10]
1504정성태9/24/201335784.NET Framework: 387. UDP 브로드캐스팅을 이용해 서비스 측의 IP 주소를 구하는 방법 [1]파일 다운로드1
1503정성태9/21/201341324개발 환경 구성: 199. Visual Studio - github 연동 [7]
1502정성태9/21/201344712개발 환경 구성: 198. Visual Studio - git을 이용한 로컬 소스 컨트롤
1501정성태9/21/201354606개발 환경 구성: 197. Visual Studio를 위한 Git 환경 설정 [5]
1500정성태9/20/201352115.NET Framework: 386. C# 버전의 한글 형태소 분석기 [1]파일 다운로드1
1499정성태9/20/201327319개발 환경 구성: 196. Windows Azure - Cloud Service의 인스턴스 타입 변경하는 방법
1498정성태9/20/201334616Windows: 76. 윈도우 8.1 / 서버 2012 R2 마이그레이션 [5]
1497정성태9/20/201367112웹: 28. IE 11로 바꾼 후 발생하는 문제 정리
1496정성태9/20/201338343Windows: 75. 윈도우 8.1, 2012 R2 설치 후 원격 접속이 안 되는 문제
... 136  137  138  139  140  141  142  143  144  145  [146]  147  148  149  150  ...