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

비밀번호

댓글 작성자
 




... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12425정성태11/24/202020647VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/202020713VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202020383.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/202017804.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/202016847.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/202017854오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/202017733VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202019791오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/202018711오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/202019913오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202018973.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202022693VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202020769.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202022806.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
12411정성태11/12/202019129오류 유형: 680. C# 9.0 - Error CS8889 The target runtime doesn't support extensible or runtime-environment default calling conventions.
12410정성태11/12/202020768디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202021921.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202036900도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202021965.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202022770.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202022177.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202022862.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202019872.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202023278.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202022073VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202017951오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
... 61  62  [63]  64  65  66  67  68  69  70  71  72  73  74  75  ...