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

비밀번호

댓글 작성자
 




... 91  92  93  94  95  96  97  98  99  100  101  102  103  104  [105]  ...
NoWriterDateCnt.TitleFile(s)
11367정성태11/25/201729932개발 환경 구성: 337. 윈도우 운영체제의 route 명령어 사용법
11366정성태11/25/201722001오류 유형: 430. 이벤트 로그 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.
11365정성태11/25/201722910오류 유형: 429. 이벤트 로그 - User Policy could not be updated successfully
11364정성태11/24/201726436사물인터넷: 11. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 (절대 좌표) [2]
11363정성태11/23/201726342사물인터넷: 10. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 (두 번째 이야기)
11362정성태11/22/201721036오류 유형: 428. 윈도우 업데이트 KB4048953 - 0x800705b4 [2]
11361정성태11/22/201724315오류 유형: 427. 이벤트 로그 - Filter Manager failed to attach to volume '\Device\HarddiskVolume??' 0xC03A001C
11360정성태11/22/201725288오류 유형: 426. 이벤트 로그 - The kernel power manager has initiated a shutdown transition.
11359정성태11/16/201724218오류 유형: 425. 윈도우 10 Version 1709 (OS Build 16299.64) 업그레이드 시 발생한 문제 2가지
11358정성태11/15/201729518사물인터넷: 9. Visual Studio 2017에서 Raspberry Pi C++ 응용 프로그램 제작 [1]
11357정성태11/15/201729956개발 환경 구성: 336. 윈도우 10 Bash 쉘에서 C++ 컴파일하는 방법
11356정성태11/15/201731532사물인터넷: 8. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스 + 키보드로 쓰는 방법 [4]
11355정성태11/15/201726118사물인터넷: 7. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 마우스로 쓰는 방법 [2]파일 다운로드2
11354정성태11/14/201731437사물인터넷: 6. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 키보드로 쓰는 방법 [8]
11353정성태11/14/201728320사물인터넷: 5. Raspberry Pi Zero(OTG)를 다른 컴퓨터에 연결해 가상 이더넷 카드로 쓰는 방법 [1]
11352정성태11/14/201725094사물인터넷: 4. Samba를 이용해 윈도우와 Raspberry Pi간의 파일 교환 [1]
11351정성태11/7/201727418.NET Framework: 698. C# 컴파일러 대신 직접 구현하는 비동기(async/await) 코드 [6]파일 다운로드1
11350정성태11/1/201723444디버깅 기술: 108. windbg 분석 사례 - Redis 서버로의 호출을 기다리면서 hang 현상 발생
11349정성태10/31/201724689디버깅 기술: 107. windbg - x64 SOS 확장의 !clrstack 명령어가 출력하는 Child SP 값의 의미 [1]파일 다운로드1
11348정성태10/31/201720408디버깅 기술: 106. windbg - x64 역어셈블 코드에서 닷넷 메서드 호출의 인자를 확인하는 방법
11347정성태10/28/201724327오류 유형: 424. Visual Studio - "클래스 다이어그램 보기" 시 "작업을 완료할 수 없습니다. 해당 인터페이스를 지원하지 않습니다." 오류 발생
11346정성태10/25/201721122오류 유형: 423. Windows Server 2003 - The client-side extension could not remove user policy settings for 'Default Domain Policy {...}' (0x8007000d)
11338정성태10/25/201717804.NET Framework: 697. windbg - SOS DumpMT의 "BaseSize", "ComponentSize" 값에 대한 의미파일 다운로드1
11337정성태10/24/201720817.NET Framework: 696. windbg - SOS DumpClass/DumpMT의 "Vtable Slots", "Total Method Slots", "Slots in VTable" 값에 대한 의미파일 다운로드1
11336정성태10/20/201722500.NET Framework: 695. windbg - .NET string의 x86/x64 메모리 할당 구조
11335정성태10/18/201721102.NET Framework: 694. 닷넷 - <Module> 클래스의 용도
... 91  92  93  94  95  96  97  98  99  100  101  102  103  104  [105]  ...