Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (seongtaejeong at gmail.com)
홈페이지
첨부 파일
 

(시리즈 글이 19개 있습니다.)
Linux: 86. Golang + bpf2go를 사용한 eBPF 기본 예제
; https://www.sysnet.pe.kr/2/0/13769

Linux: 94. eBPF - vmlinux.h 헤더 포함하는 방법 (bpf2go에서 사용)
; https://www.sysnet.pe.kr/2/0/13783

Linux: 95. eBPF - kprobe를 이용한 트레이스
; https://www.sysnet.pe.kr/2/0/13784

Linux: 96. eBPF (bpf2go) - fentry, fexit를 이용한 트레이스
; https://www.sysnet.pe.kr/2/0/13788

Linux: 100.  eBPF의 2가지 방식 - libbcc와 libbpf(CO-RE)
; https://www.sysnet.pe.kr/2/0/13801

Linux: 103. eBPF (bpf2go) - Tracepoint를 이용한 트레이스 (BPF_PROG_TYPE_TRACEPOINT)
; https://www.sysnet.pe.kr/2/0/13810

Linux: 105. eBPF - bpf2go에서 전역 변수 설정 방법
; https://www.sysnet.pe.kr/2/0/13815

Linux: 106. eBPF (bpf2go) - (BPF_MAP_TYPE_HASH) Map을 이용한 전역 변수 구현
; https://www.sysnet.pe.kr/2/0/13817

Linux: 107. eBPF - libbpf CO-RE의 CONFIG_DEBUG_INFO_BTF 빌드 여부에 대한 의존성
; https://www.sysnet.pe.kr/2/0/13819

Linux: 109. eBPF (bpf2go) - BPF_PERF_OUTPUT / BPF_MAP_TYPE_PERF_EVENT_ARRAY 사용법
; https://www.sysnet.pe.kr/2/0/13824

Linux: 110. eBPF (bpf2go) - BPF_RINGBUF_OUTPUT / BPF_MAP_TYPE_RINGBUF 사용법
; https://www.sysnet.pe.kr/2/0/13825

Linux: 115. eBPF (bpf2go) - ARRAY / HASH map 기본 사용법
; https://www.sysnet.pe.kr/2/0/13893

Linux: 116. eBPF (bpf2go) - BTF Style Maps 정의 구문과 데이터 정렬 문제
; https://www.sysnet.pe.kr/2/0/13894

Linux: 117. eBPF (bpf2go) - Map에 추가된 요소의 개수를 확인하는 방법
; https://www.sysnet.pe.kr/2/0/13895

Linux: 122. eBPF - __attribute__((preserve_access_index)) 사용법
; https://www.sysnet.pe.kr/2/0/14016

Linux: 123. eBPF (bpf2go) - BPF_PROG_TYPE_SOCKET_FILTER 예제 - SEC("socket")
; https://www.sysnet.pe.kr/2/0/14017

Linux: 125. eBPF - __attribute__((preserve_access_index)) 활용 사례
; https://www.sysnet.pe.kr/2/0/14020

Linux: 126. eBPF (bpf2go) - tcp_sendmsg 예제
; https://www.sysnet.pe.kr/2/0/14025

Linux: 129. eBPF (bpf2go) - BPF_PROG_TYPE_SOCKET_FILTER 예제 - "cgroup_skb/egress", "cgroup_skb/egress"
; https://www.sysnet.pe.kr/2/0/14037




eBPF (bpf2go) - BPF_PROG_TYPE_SOCKET_FILTER 예제 - "cgroup_skb/egress", "cgroup_skb/egress"

지난 글의 BPF_PROG_TYPE_SOCKET_FILTER 예제에 이어,

eBPF (bpf2go) - BPF_PROG_TYPE_SOCKET_FILTER 예제 - SEC("socket")
; https://www.sysnet.pe.kr/2/0/14017

이번에는 동일하게 패킷 필터링 용도이긴 하지만 접점이 다른 BPF_PROG_TYPE_CGROUP_SKB 예제를 다뤄보겠습니다.

BPF_PROG_TYPE_CGROUP_SKB
; https://docs.ebpf.io/linux/program-type/BPF_PROG_TYPE_CGROUP_SKB/

.\pkg\mod\github.com\cilium\ebpf@v0.16.0\examples\cgroup_skb
; https://github.com/cilium/ebpf/blob/main/examples/cgroup_skb/cgroup_skb.c

재미있게도 BPF_PROG_TYPE_SOCKET_FILTER와는 완전히 상반된 특징을 갖는데요, 1) 전역 소켓 모니터링이 가능하고, 2) in/out 패킷에 대해 다룰 수 있습니다. 예를 들어, 아래와 같이 eBPF 코드를 작성해 보면,

SEC("cgroup_skb/ingress")
int cgroup_ingress_packets(struct __sk_buff *skb) {
    struct bpf_sock *bpf_sock = skb->sk;
    bpf_printk("[ingress] bpf_sock = %p", bpf_sock);

    return 1;
}

SEC("cgroup_skb/egress")
int cgroup_egress_packets(struct __sk_buff *skb) {
    struct bpf_sock *bpf_sock = skb->sk;
    bpf_printk("[egress] bpf_sock = %p", bpf_sock);

    return 1;
}

이와 함께 (어차피 cgroup에 속한 유형이므로) BPF_PROG_TYPE_CGROUP_SOCK_ADDR에 속한 connect4도 함께 작성해,

#define SYS_REJECT  0
#define SYS_PROCEED 1

SEC("cgroup/connect4")
int socket_connect4(struct bpf_sock_addr *ctx)
{
    struct bpf_sock* bpf_sk = ctx->sk;
    bpf_printk("[socket_connect4] bpf_sk == %p", bpf_sk);

    return SYS_PROCEED;
}

bpf2go로 로딩한 다음,

// ...[생략]...

func main() {
    // ...[생략]...

    // Get the first-mounted cgroupv2 path.
    cgroupPath, err := detectCgroupPath() // 예를 들어, cgroupPath == "/sys/fs/cgroup"
    if err != nil {
        log.Fatal(err)
    }

    cgroupEgressFunc, err := linkAttachCgroup(cgroupPath, ebpf.AttachCGroupInetEgress, bpfObj.CgroupEgressPackets)
    defer func(link link.Link) {
        fmt.Printf("cgroupEgressFunc\n")
        _ = link.Close()
    }(cgroupEgressFunc)

    cgroupIngressFunc, err := linkAttachCgroup(cgroupPath, ebpf.AttachCGroupInetIngress, bpfObj.CgroupIngressPackets)
    defer func(link.Link) {
        fmt.Printf("cgroupIngressFunc\n")
        _ = link.Close()
    }(cgroupIngressFunc)

    cgroupSocketConnect4, err := linkAttachCgroup(cgroupPath, ebpf.AttachCGroupInet4Connect, bpfObj.SocketConnect4)
    defer func(link link.Link) {
        _ = link.Close()
    }(cgroupSocketConnect4)

    // ...[생략]...
}

func detectCgroupPath() (string, error) {
	f, err := os.Open("/proc/mounts")
	if err != nil {
		return "", err
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)
	for scanner.Scan() {
		// example fields: cgroup2 /sys/fs/cgroup/unified cgroup2 rw,nosuid,nodev,noexec,relatime 0 0
		fields := strings.Split(scanner.Text(), " ")
		if len(fields) >= 3 && fields[2] == "cgroup2" {
			return fields[1], nil
		}
	}

	return "", errors.New("cgroup2 not mounted")
}

func linkAttachCgroup(cgroupPath string, attachType ebpf.AttachType, program *ebpf.Program) (link.Link, error) {
	opt := link.CgroupOptions{ // https://github.com/cilium/ebpf/blob/main/examples/cgroup_skb/main.go
		Path:    cgroupPath,
		Attach:  attachType,
		Program: program,
	}

	attached, err := link.AttachCgroup(opt)
	if err != nil {
		log.Printf("link.Tracepoint(%v): %v\n", attachType, err)
		return nil, err
	}

	return attached, err
}

실행해 HTTP 호출을 해보면 이런 결과를 얻게 됩니다.

// 이 부분은 아마도 HTTP 요청 중 DNS lookup에 대한 요청으로 보이고,
bpf_trace_printk: [socket_connect4] bpf_sk == 00000000417b902c
bpf_trace_printk: [egress] bpf_sock = 00000000417b902c
bpf_trace_printk: [ingress] bpf_sock = 0000000063b0daeb
bpf_trace_printk: [egress] bpf_sock = 00000000417b902c
bpf_trace_printk: [ingress] bpf_sock = 0000000063b0daeb

// 여기서부터 HTTP 요청
bpf_trace_printk: [socket_connect4] bpf_sk == 000000001a9c864d
bpf_trace_printk: [egress] bpf_sock = 000000001a9c864d
bpf_trace_printk: [egress] bpf_sock = 000000001a9c864d
bpf_trace_printk: [egress] bpf_sock = 000000001a9c864d

간단하죠? ^^ 참고로 "cgroup_skb/ingress", "cgroup_skb/egress" 모두 1을 반환하면 PASS, 0을 반환하면 DROP 동작을 하므로 원한다면 간단한 방화벽 프로그램을 eBPF를 이용해 제작하는 것이 가능합니다.




하지만, 테스트 결과에서 한 가지 의문이 남는데요, 마지막 4개의 출력을 보면,

bpf_trace_printk: [socket_connect4] bpf_sk == 000000001a9c864d
bpf_trace_printk: [egress] bpf_sock = 000000001a9c864d
bpf_trace_printk: [egress] bpf_sock = 000000001a9c864d
bpf_trace_printk: [egress] bpf_sock = 000000001a9c864d

HTTP 호출이므로 당연히 응답이 왔을 것이고, 따라서 ingress 로그가 찍혀야 하는데 그 부분의 출력이 없습니다. 이것도 분명 무슨 이유가 있겠지만.. (리알못이라) 일단 여기까지만 실습한 걸로 만족하고 넘어가겠습니다. ^^;




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







[최초 등록일: ]
[최종 수정일: 11/3/2025]

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

비밀번호

댓글 작성자
 




... 121  122  123  [124]  125  126  127  128  129  130  131  132  133  134  135  ...
NoWriterDateCnt.TitleFile(s)
10939정성태4/18/201630354.NET Framework: 572. .NET APM 비동기 호출의 Begin...과 End... 조합 [3]파일 다운로드1
10938정성태4/13/201627537오류 유형: 325. 파일 삭제 시 오류 - Error 0x80070091: The directory is not empty.
10937정성태4/13/201636286Windows: 115. UEFI 모드로 윈도우 10 설치 가능한 USB 디스크 만드는 방법
10936정성태4/8/201651037Windows: 114. 삼성 센스 크로노스 7 노트북의 운영체제를 USB 디스크로 새로 설치하는 방법 [3]
10935정성태4/7/201633300웹: 32. Edge에서 Google Docs 문서 편집 시 한영 전환키가 동작 안하는 문제
10934정성태4/5/201630290디버깅 기술: 77. windbg의 콜스택 함수 인자를 쉽게 확인하는 방법 [1]
10933정성태4/5/201636628.NET Framework: 571. C# - 스레드 선호도(Thread Affinity) 지정하는 방법 [8]파일 다운로드1
10932정성태4/4/201633295VC++: 96. C/C++ 식 평가 - printf("%d %d %d\n", a, a++, a); [1]
10931정성태3/31/201629643개발 환경 구성: 283. Hyper-V 내에 구성한 Active Directory 환경의 시간 구성 방법 [3]
10930정성태3/30/201626550.NET Framework: 570. .NET 4.5부터 추가된 CLR Profiler의 실행 시 Rejit 기능
10929정성태3/29/201638164.NET Framework: 569. ServicePointManager.DefaultConnectionLimit의 역할파일 다운로드1
10928정성태3/28/201644064.NET Framework: 568. ODP.NET의 완전한 닷넷 버전 Oracle ODP.NET, Managed Driver [2]파일 다운로드1
10927정성태3/25/201631403.NET Framework: 567. System.Net.ServicePointManager의 DefaultConnectionLimit 속성 설명
10926정성태3/24/201632206.NET Framework: 566. openssl의 PKCS#1 PEM 개인키 파일을 .NET RSACryptoServiceProvider에서 사용하는 방법 [10]파일 다운로드1
10925정성태3/24/201624514.NET Framework: 565. C# - Rabin-Miller 소수 생성 방법을 이용하여 RSACryptoServiceProvider의 개인키를 직접 채워보자 - 두 번째 이야기파일 다운로드1
10924정성태3/22/201627538오류 유형: 324. Visual Studio에서 Azure 클라우드 서비스 생성 시 Failed to initialize the PowerShell host 에러 발생
10923정성태3/21/201626375.NET Framework: 564. C# - DGML로 바이너리 트리 출력하는 방법 [1]파일 다운로드1
10922정성태3/21/201628547.NET Framework: 563. 디버깅 용도로 이진 트리의 내용을 출력하는 방법파일 다운로드1
10921정성태3/17/201633649.NET Framework: 562. BBI 인터프리터 C/C++ 코드를 C#으로 변환 [3]파일 다운로드2
10920정성태3/15/201632082.NET Framework: 561. null 처리된 객체가 왜 GC에 의해 수집되지 않을까요? [6]파일 다운로드1
10919정성태3/12/201627623.NET Framework: 560. C#에서 return할 때 명시적으로 casting한 것과 안한 것의 차이 [2]파일 다운로드1
10918정성태3/10/201626090.NET Framework: 559. WPF - ICommand.CanExecuteChanged가 해제되지 않는 문제 [2]파일 다운로드1
10917정성태3/10/201645153.NET Framework: 558. WPF - ICommand 동작 방식 [9]파일 다운로드1
10916정성태3/9/201633865.NET Framework: 557. 머신 바이트 배열로부터 역어셈블해주는 라이브러리 - Udis86 Assembler파일 다운로드2
10915정성태3/9/201627799오류 유형: 323. FatalExecutionEngineError was detected
10914정성태3/8/201630708오류 유형: 322. 정적 라이브러리 참조 시 "LNK2019 unresolved external symbol '...' referenced in function" 오류 발생파일 다운로드1
... 121  122  123  [124]  125  126  127  128  129  130  131  132  133  134  135  ...