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

비밀번호

댓글 작성자
 




1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...
NoWriterDateCnt.TitleFile(s)
13629정성태5/18/202410815개발 환경 구성: 710. Android - adb.exe를 이용한 파일 전송
13628정성태5/17/202410079개발 환경 구성: 709. Windows - WHPX(Windows Hypervisor Platform)를 이용한 Android Emulator 가속
13627정성태5/17/202410246오류 유형: 904. 파이썬 - UnicodeEncodeError: 'ascii' codec can't encode character '...' in position ...: ordinal not in range(128)
13626정성태5/15/202412009Phone: 15. C# MAUI - MediaElement Source 경로 지정 방법파일 다운로드1
13625정성태5/14/202410664닷넷: 2262. C# - Exception Filter 조건(when)을 갖는 catch 절의 IL 구조
13624정성태5/12/202410466Phone: 14. C# - MAUI에서 MediaElement 사용파일 다운로드1
13623정성태5/11/20249928닷넷: 2261. C# - 구글 OAuth의 JWT (JSON Web Tokens) 해석파일 다운로드1
13622정성태5/10/202412395닷넷: 2260. C# - Google 로그인 연동 (ASP.NET 예제)파일 다운로드1
13621정성태5/10/202411575오류 유형: 903. IISExpress - Failed to register URL "..." for site "..." application "/". Error description: Cannot create a file when that file already exists. (0x800700b7)
13620정성태5/9/202410606VS.NET IDE: 190. Visual Studio가 node.exe를 경유해 Edge.exe를 띄우는 경우
13619정성태5/7/202411391닷넷: 2259. C# - decimal 저장소의 비트 구조 [1]파일 다운로드1
13618정성태5/6/202410082닷넷: 2258. C# - double (배정도 실수) 저장소의 비트 구조파일 다운로드1
13617정성태5/5/202412351닷넷: 2257. C# - float (단정도 실수) 저장소의 비트 구조파일 다운로드1
13616정성태5/3/202410057닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
13615정성태5/3/202412358닷넷: 2255. C# 배열을 Numpy ndarray 배열과 상호 변환
13614정성태5/2/202412091닷넷: 2254. C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언
13613정성태5/1/202410247닷넷: 2253. C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회파일 다운로드1
13612정성태4/30/202411715오류 유형: 902. Visual Studio - error MSB3021: Unable to copy file
13611정성태4/29/202410441닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/202411728닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/202411553닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/202412194닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/202412169닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/202412114닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/202413694닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/202410101오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
1  2  3  4  5  6  7  8  9  10  11  12  13  14  [15]  ...