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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  115  116  117  [118]  119  120  ...
NoWriterDateCnt.TitleFile(s)
11034정성태8/25/201626566개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201624618오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201623790개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201619632오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201623229VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201630634.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201623070오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201625226.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201626423Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201625730개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201624444오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
11023정성태8/10/201625972개발 환경 구성: 293. Azure 구독 후 PaaS 서비스 만들어 보기
11022정성태8/10/201626781개발 환경 구성: 292. Azure Cloud Service 배포시 사용자 정의 작업을 추가하는 방법
11021정성태8/10/201623997오류 유형: 349. System.Runtime.Remoting.RemotingException - Type '..., ..., Version=..., Culture=neutral, PublicKeyToken=null' is not registered for activation [2]
11020정성태8/10/201626782VC++: 98. 원본과 대상 버퍼가 같은 경우 memcpy, wmemcpy 주의점
11019정성태8/10/201643509기타: 60. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 (2쇄 정오표)
11018정성태8/9/201627491.NET Framework: 600. 단일 메서드 내에서의 할당으로 알아보는 자바와 닷넷의 GC 차이점 [1]
11017정성태8/9/201628299웹: 33. HTTP 쿠키에 한글 값을 설정하는 방법
11016정성태8/7/201626882개발 환경 구성: 291. Windows Server Containers 소개
11015정성태8/7/201625333오류 유형: 348. Windows Server 2016 TP5에서 Windows Containers의 docker run 실행 시 encountered an error during Start failed in Win32
11014정성태8/6/201625843오류 유형: 347. Hyper-V Virtual Machine Management service Account does not have permission to open attachment
11013정성태8/6/201636725개발 환경 구성: 290. Windows 10에서 경험해 보는 Windows Containers와 docker [4]
11012정성태8/6/201626921오류 유형: 346. Windows 10에서 Windows Containers의 docker run 실행 시 encountered an error during CreateContainer failed in Win32 발생
11011정성태8/6/201628133기타: 59. outlook.live.com 메일 서비스의 아웃룩 POP3 설정하는 방법
11010정성태8/6/201624849기타: 58. Outlook에 설정한 SMTP/POP3(예:천리안 메일) 계정 암호를 잊어버린 경우
11009정성태8/3/201630100개발 환경 구성: 289. 2016-08-02부터 시작된 윈도우 10 1주년 업데이트에서 Bash Shell 사용 [8]
... 106  107  108  109  110  111  112  113  114  115  116  117  [118]  119  120  ...