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)
10812정성태6/20/201531343.NET Framework: 519. C# 6.0 오픈 소스 컴파일러 Roslyn - 빌드 및 테스트 방법 [1]
10811정성태6/20/201528256오류 유형: 294. OpenAuth 사용 시 System.Data.SqlClient.SqlException 예외가 Output 창에 출력되는 문제
10810정성태6/18/201528062개발 환경 구성: 270. Visual Studio에서 github 오픈 소스를 fork해서 테스트하는 방법 [1]
10809정성태6/18/201526068.NET Framework: 518. AllowPartiallyTrustedCallers 특성이 적용된 GAC 어셈블리에서 DynamicMethod의 calli 명령어 사용파일 다운로드1
10808정성태6/17/201527092.NET Framework: 517. calli IL 호출이 DllImport 호출보다 빠를까요? [1]파일 다운로드1
10807정성태6/16/201529588.NET Framework: 516. Microsoft.AspNet.Membership.OpenAuth 사용 시 "Local Database Runtime error occurred" 오류
10806정성태6/16/201545872.NET Framework: 515. OpenAuth.VerifyAuthentication 호출 시 The remote server returned an error: (400) Bad Request
10805정성태6/15/201528627Java: 17. 자바의 재미있는 상수 처리 방식
10804정성태6/10/201528490.NET Framework: 514. .NET CLR2 보안 모델에서의 APTCA 역할 (2)파일 다운로드1
10803정성태6/2/201531149.NET Framework: 513. UWP(Universal Windows Platform) 응용 프로그램의 새로운 라이브러리 버전 관리 해법 [2]
10802정성태6/2/201529310개발 환경 구성: 269. 마이크로소프트 온라인 강좌 소개 - Azure VPN 구성 방법 [1]
10801정성태5/31/201535710.NET Framework: 512. async/await 사용 시 hang 문제가 발생하는 경우 - 두 번째 이야기 [3]
10800정성태5/29/201531196개발 환경 구성: 268. 소개 - 프로세싱(https://processing.org/)
10799정성태5/29/201527939사물인터넷: 3. 책 소개 - 라즈베리 파이로 구현하는 사물 인터넷 프로젝트 [1]
10798정성태5/26/201528046기타: 53. 2015년 6월 10일 밤 10시 온라인 세미나 - 새로운 Windows 10 App을 개발하는 방법
10797정성태5/23/201527836VC++: 91. 자식 스레드에 자동 상속되는 TEB의 SubProcessTag 필드파일 다운로드1
10796정성태5/23/201538604오류 유형: 293. SQL Server Management Studio 실행 시 "Cannot find one or more components" 오류
10795정성태5/23/201537807오류 유형: 292. InstallUtil로 .NET 서비스 등록 시 오류 - Operation is not supported. (Exception from HRESULT: 0x80131515). [3]
10794정성태5/22/201532079개발 환경 구성: 267. (무료) 마이크로소프트 온라인 강좌 소개 - 네트워킹 기초 [1]
2925정성태5/14/201530742디버깅 기술: 73. PDB 기호 파일의 경로 구성 방식파일 다운로드1
2924정성태5/14/201535506VS.NET IDE: 100. 비주얼 스튜디오 원격 디버깅 시 'Unknown function' 콜스택이 나온다면?
2923정성태5/12/201594852기타: 52. 도서: 시작하세요! C# 6.0 프로그래밍: 기본 문법부터 실전 예제까지 [17]
2922정성태5/12/201530343오류 유형: 291. ssindex.cmd 실행 시 '...[tfs_collection_url]...' not found in srcsrv.ini 오류 발생
2921정성태5/9/201537131개발 환경 구성: 266. 인텔에서 구현한 최대 절전 모드 기능 - Intel® Rapid Start Technology
2920정성태5/9/201527983오류 유형: 290. 디스크 관리자의 파티션 축소 시, There is not enough space available on the disk(s) to complete this operation.
2919정성태5/9/201527566오류 유형: 289. Error: this template attempted to load component assembly 'NuGet.VisualStudio.Interop, ...'
... 121  122  123  124  125  126  127  128  [129]  130  131  132  133  134  135  ...