Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)

eBPF - BPF_PROG_TYPE_CGROUP_SOCK 유형에서 정상 동작하지 않는 BPF_CORE_READ

아래의 문서에 실린,

Program type BPF_PROG_TYPE_CGROUP_SOCK
; https://docs.ebpf.io/linux/program-type/BPF_PROG_TYPE_CGROUP_SOCK/#context

예제를 잠시 실습해 봤는데요, 해당 예제를 참고해 bpf_sock 구조체의,

// https://codebrowser.dev/linux/include/linux/bpf.h.html#bpf_sock
// cat /usr/include/linux/bpf.h | grep -A 17 "struct bpf_sock {"
// cat vmlinux.h | grep -A 15 "struct bpf_sock {"

struct bpf_sock {
    __u32 bound_dev_if;
    __u32 family;
    __u32 type;
    __u32 protocol;
    __u32 mark;
    __u32 priority;
    /* IP address also allows 1 and 2 bytes access */
    __u32 src_ip4;
    __u32 src_ip6[4];
    __u32 src_port;     /* host byte order */
    __be16 dst_port;    /* network byte order */
    __u16 :16;      /* zero padding */
    __u32 dst_ip4;
    __u32 dst_ip6[4];
    __u32 state;
    __s32 rx_queue_mapping;
};

필드를 BPF_CORE_READ 매크로 또는 bpf_core_read 함수를 사용해 접근해 봤습니다. 그런데, 여기서 재미있는 현상이 발생하는데요, 예를 들어, family 필드를 직접 접근하면 정상적으로 값이 나오는데,

SEC("cgroup/sock_create")
int sock(struct bpf_sock *ctx)
{
    __u32 family = ctx->family; // AF_INET == 2, AF_INET6 == 10

   return 1;
}

반면, BPF_CORE_READ 또는 bpf_core_read로 바꿨더니 0이 반환됩니다.

// BPF_CORE_READ 매크로를 사용한 경우
__u64 family = BPF_CORE_READ(ctx, family); // family == 0

// 또는, bpf_core_read를 직접 사용
__u64 family;
bpf_core_read(&family3, sizeof(family3), &ctx->family); // family == 0

검색해 보면 이와 유사한 문제를 겪는 글이 나오는데요,

eBPF `bpf_core_read` returns incorrect value
; https://unix.stackexchange.com/questions/787851/ebpf-bpf-core-read-returns-incorrect-value

혹시나 싶어 저도 코드를 간단하게 바꾼 후 ELF 바이너리를 덤프했더니 이런 결과가 나왔습니다.

/*
SEC("cgroup/sock_create")
int sock(struct bpf_sock *ctx)
{
    __u32 family = ctx->family;
    return family; // 원래는 1 또는 0을 반환하지만, 최적화 과정에서 사용하지 않는 family 관련 코드를 제거하지 못하도록 일부러 사용
}
*/

$ llvm-objdump -d test_x86_bpfel.o
0000000000000000 <socket_create>:
       0:       61 10 04 00 00 00 00 00 r0 = *(u32 *)(r1 + 0x4) // 0x4 == family 필드의 offset
       1:       95 00 00 00 00 00 00 00 exit

/*
// https://github.com/iovisor/bpf-docs/blob/master/eBPF.md

0x61 == ldxw dst, [src+off] == dst = *(uint32_t *) (src + off)
0x95 == exit                == return r0
*/

일단, 직접 접근한 경우에 r1은 socket_create 함수의 첫 번째 인자인 ctx를 가리키고 그것의 0x4 위치에 있는 값을 가져오고 있는데요, struct bpf_sock 구조체의 family 필드가 0x4 offset에 있기 때문에 올바른 접근입니다.

이제 이것을 bpf_core_read로 바꾸면,

/*
__u32 family;
bpf_core_read(&family, sizeof(family), &ctx->family);
return family;
*/

$ llvm-objdump -d test_x86_bpfel.o
0000000000000000 <socket_create>:
       0:       bf 13 00 00 00 00 00 00 r3 = r1
       1:       b7 01 00 00 04 00 00 00 r1 = 0x4
       2:       0f 13 00 00 00 00 00 00 r3 += r1 // r3 == family 필드의 pointer
       3:       bf a1 00 00 00 00 00 00 r1 = r10
       4:       07 01 00 00 fc ff ff ff r1 += -0x4 // family 지역 변수의 pointer
       5:       b7 02 00 00 04 00 00 00 r2 = 0x4   // sizeof(...) == 4
       6:       85 00 00 00 71 00 00 00 call 0x71  (r1 == family 변수 위치, r2 == size, r3 == pointer
       7:       61 a0 fc ff 00 00 00 00 r0 = *(u32 *)(r10 - 0x4)
       8:       95 00 00 00 00 00 00 00 exit

/*
Register r10 is the only register which is read-only and contains the frame pointer address in order to access the BPF stack space.

0xbf == mov dst, src        == dst = src
0xb7 == mov dst, imm        == dst = imm
0x0f == add dst, src        == dst += src
0xbf ...
0x07 == add dst, imm        == dst += imm
0xb7 ...
0x85 == call imm            == Function call (0x71 == bpf_probe_read_kernel)
0x61 == ldxw dst, [src+off] == dst = *(uint32_t *) (src + off)
0x95 ...
*/

그러니까, r1, r2, r3 레지스터가 bpf_probe_read_kernel 함수 호출의 인자로 사용되는데, 모두 올바르게 값이 설정된 것을 볼 수 있습니다. 즉, ebpf 바이너리 역시 정상적으로 생성된 것입니다.




그럼 bpf_probe_read_kernel 호출도 풀어볼까요?

const void* ptr1 = &ctx->family;
family = *(__u32*)ptr1;
bpf_printk("%d, %p\n", family, ptr1); // 출력 결과: 2, 0000000077255097

const void* ptr2 = __builtin_preserve_access_index(&ctx->family);
__u32 family2 = 0;
long result = bpf_probe_read_kernel(&family2, sizeof(family2), ptr2);
bpf_printk("%d, %d, %p\n", result, family2, ptr2); // 출력 결과: 0, 0, 0000000077255097

보는 바와 같이 ctx->family의 주소와 __builtin_preserve_access_index로 구한 주소가 같습니다. 동일한 주소에 대해 직접 접근하면 정상적인 값을 가져오고, bpf_probe_read_kernel로 접근하면 함수가 성공(반환값 == 0)은 하지만 읽어온 값은 0이 됩니다.

음... 더 이상 파고들 것이 없군요, ^^ 혹시 BPF_CORE_READ가 왜 저렇게 이상한 값을 반환하는지 아시는 분 계시나요? ^^




그건 그렇고 ctx로 넘어온 포인터의 주소가 유효한 가상 메모리 주소일까요?

64비트 리눅스의 경우 유저/커널의 가상 주소 범위가 128TB를 경계로 나뉜다고 알고 있는데, 그렇다면 0x0000000077255097 주소는 유저 영역에 속하는 주소입니다. 그렇다고 해서 bpf_probe_read_user 함수를 사용하면 아예 함수 실행 결과가 (0이 아닌) -14(EFAULT)를 반환하는데, 잘못된 주소를 접근하려고 했다는 뜻입니다.

$ cat /usr/include/asm-generic/errno-base.h | grep EFAULT
#define EFAULT          14      /* Bad address */

그런 면에서 커널 주소는 맞는 듯한데... 해석이 안 되는군요. ^^




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/30/2025]

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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...
NoWriterDateCnt.TitleFile(s)
13301정성태3/29/202315511Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션 [1]파일 다운로드1
13300정성태3/28/202314690Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/202314708Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/202313930Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/202316128Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/202315265Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/202315012Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/202315020.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/202314101오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/202314799Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/202314848.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/202315561.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/202314088Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/202314668Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/202314667Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/202314968Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/202314222Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법 [2]파일 다운로드1
13284정성태3/13/202313625Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/202311442오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/202312021Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/202313404Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/202315817개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
13279정성태3/9/202314997오류 유형: 851. 파이썬 ModuleNotFoundError: No module named '_cffi_backend'
13278정성태3/8/202314823개발 환경 구성: 669. WSL 2의 (init이 아닌) systemd 지원 [1]
13277정성태3/6/202315163개발 환경 구성: 668. 코드 사인용 인증서 신청 및 적용 방법(예: Digicert)
13276정성태3/5/202315482.NET Framework: 2102. C# 11 - ref struct/ref field를 위해 새롭게 도입된 scoped 예약어 [1]
... 16  17  18  19  20  21  22  23  24  25  26  27  [28]  29  30  ...