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

비밀번호

댓글 작성자
 




... 106  107  108  109  110  111  112  113  114  115  116  117  118  119  [120]  ...
NoWriterDateCnt.TitleFile(s)
11039정성태9/9/201627263오류 유형: 355. Visual Studio 빌드 오류 - error CS0122: '__ComObject' is inaccessible due to its protection level
11038정성태9/9/201630987VC++: 99. 서로 다른 프로세스에서 WM_DROPFILES 메시지를 전송하는 방법파일 다운로드1
11037정성태9/8/201634219.NET Framework: 603. socket - shutdown 호출이 필요한 사례파일 다운로드1
11036정성태8/29/201629346개발 환경 구성: 297. 소스 코드가 없는 닷넷 어셈블리를 디버깅할 때 지역 변숫값을 확인하는 방법
11035정성태8/29/201624989오류 유형: 354. .NET Reflector - PDB 생성 화면에서 "Clear Store"를 하면 "Index and length must refer to a location within the string" 예외 발생
11034정성태8/25/201629128개발 환경 구성: 296. .NET Core 프로젝트를 NuGet Gallery에 배포하는 방법 [2]
11033정성태8/24/201627173오류 유형: 353. coreclr 빌드 시 error C3249: illegal statement or sub-expression for 'constexpr' function
11032정성태8/23/201626241개발 환경 구성: 295. 최신의 Visual C++ 컴파일러 도구를 사용하는 방법 [1]
11031정성태8/23/201622045오류 유형: 352. Error encountered while pushing to the remote repository: Response status code does not indicate success: 403 (Forbidden).
11030정성태8/23/201626556VS.NET IDE: 111. Team Explorer - 추가한 Git Remote 저장소가 Branch에 보이지 않는 경우
11029정성태8/18/201634220.NET Framework: 602. Process.Start의 cmd.exe에서 stdin만 redirect 하는 방법 [1]파일 다운로드1
11028정성태8/15/201625589오류 유형: 351. Octave 설치 시 JRE 경로 문제
11027정성태8/15/201628182.NET Framework: 601. ElementHost 컨트롤의 메모리 누수 현상
11026정성태8/13/201629193Math: 19. 행렬 연산으로 본 해밍코드
11025정성태8/12/201629549개발 환경 구성: 294. .NET Core 프로젝트에서 "Copy to Output Directory" 처리 [1]
11024정성태8/12/201627418오류 유형: 350. "nProtect GameMon" 실행 중에는 Visual Studio 디버깅이 안됩니다! [1]
11023정성태8/10/201629466개발 환경 구성: 293. Azure 구독 후 PaaS 서비스 만들어 보기
11022정성태8/10/201629353개발 환경 구성: 292. Azure Cloud Service 배포시 사용자 정의 작업을 추가하는 방법
11021정성태8/10/201627364오류 유형: 349. System.Runtime.Remoting.RemotingException - Type '..., ..., Version=..., Culture=neutral, PublicKeyToken=null' is not registered for activation [2]
11020정성태8/10/201630594VC++: 98. 원본과 대상 버퍼가 같은 경우 memcpy, wmemcpy 주의점
11019정성태8/10/201647120기타: 60. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 (2쇄 정오표)
11018정성태8/9/201631087.NET Framework: 600. 단일 메서드 내에서의 할당으로 알아보는 자바와 닷넷의 GC 차이점 [1]
11017정성태8/9/201632054웹: 33. HTTP 쿠키에 한글 값을 설정하는 방법
11016정성태8/7/201629714개발 환경 구성: 291. Windows Server Containers 소개
11015정성태8/7/201628426오류 유형: 348. Windows Server 2016 TP5에서 Windows Containers의 docker run 실행 시 encountered an error during Start failed in Win32
11014정성태8/6/201628588오류 유형: 347. Hyper-V Virtual Machine Management service Account does not have permission to open attachment
... 106  107  108  109  110  111  112  113  114  115  116  117  118  119  [120]  ...