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_CGROUP_SKB 예제 - "cgroup_skb/egress", "cgroup_skb/egress"
; https://www.sysnet.pe.kr/2/0/14037




eBPF (bpf2go) - BPF_PROG_TYPE_CGROUP_SKB 예제 - "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를 이용해 제작하는 것이 가능합니다. ("Making a firewall using eBPFs and cgroups")




하지만, 테스트 결과에서 한 가지 의문이 남는데요, 마지막 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/6/2025]

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

비밀번호

댓글 작성자
 




... 196  197  198  [199]  200  201  202 
NoWriterDateCnt.TitleFile(s)
78정성태12/27/200426473VS.NET IDE: 16. MS 제품 관련 사용되는 TCP/IP 포트 열거파일 다운로드1
77정성태12/27/200426688VS.NET IDE: 15. Virtual CD-ROM Control Panel - ISO 이미지를 CD-ROM 드라이브처럼 접근하게 해주는 EXE 프로그램 [1]파일 다운로드1
76정성태12/27/200427669VS.NET IDE: 14. VPN 접속시 IP를 고정적으로 할당받는 방법 [1]
75정성태12/27/200423720VS.NET IDE: 13. VS.NET 2005 Beta 1 - Portfolio Explorer 에 등록된 Team Server 항목 삭제 방법
84정성태1/19/200524990    답변글 VS.NET IDE: 13.1. VS.NET 2005 Beta 1 : Team Server 에 등록된 포트폴리오 프로젝트 삭제 방법
74정성태12/26/200425149VS.NET IDE: 12. [시나리오] VS.NET 2005 Team Foundation Server을 Virtual Server에 설치 [1]
80정성태12/31/200424831    답변글 VS.NET IDE: 12.1. Client Tier, 즉 VS.NET 2005가 설치된 컴퓨터도 ActiveDirectory에 참여를 해야 합니다.
81정성태12/31/200426849    답변글 VS.NET IDE: 12.2. Tier 컴퓨터를 모두 영문으로 재구성
109정성태3/4/200521224    답변글 VS.NET IDE: 12.3. [보완] MS 공식 아티클 - Installing the December CTP Release of Visual Studio Team System
73정성태11/14/200523696.NET Framework: 19. VS.NET 2005 Team Foundation Server 설치오류 - 26204 예외
72정성태12/26/200425274.NET Framework: 18. .NET Framework 2.0 Beta 설치 후에 Windows SharePoint Service 오류 [1]
136정성태3/31/200525310    답변글 .NET Framework: 18.1. Windows Sharepoint Services 를 설치한 이후 ASP.NET 오류 문제
71정성태12/26/200423168VS.NET IDE: 11. SQL Server 2005 Beta 2 를 네트워크 드라이브로부터 설치시 오류
70정성태12/26/200426135VS.NET IDE: 10. WSS 설치 후 localhost 접근 보안 오류
69정성태12/5/200423367VS.NET IDE: 9. 다른 컴퓨터(방화벽 설치)에 설치된 SQL Server에 통합 인증을 할 때 필요한 포트
68정성태10/31/200428349.NET Framework: 17. Win32_NTLogEvent를 c#에서 wmi 쿼리할 때..에러..
67정성태10/22/200425308COM 개체 관련: 12. Microsoft.XMLHTTP 개체에서 Microsoft.XMLDOM 개체를 전송할 때 charset 지정 문제?
66정성태10/16/200426896.NET Framework: 16. [닷넷 리모팅] 프록시가 죽은 것을 원격 개체가 알 수 있는 방법은?
65정성태10/16/200425720VS.NET IDE: 8. Windows 가상 메모리 사용 해제
64정성태10/3/200429614.NET Framework: 15. ASP.NET에서 .NET COM+ 개체 등록 시 "Local System"이어야 하는 이유.
63정성태10/3/200429566.NET Framework: 14. Response.Cookies.Clear는 기존 설정된 Cookie 헤더를 삭제하는 것이 아닙니다.
62정성태10/3/200428585기타: 7. DB 트랜잭션에서 Lock이 걸릴 수 있는 전형적인 예.
61정성태10/3/200428067.NET Framework: 13. Main 메서드에 붙은 STAThread 의미
60정성태10/3/200426874.NET Framework: 12. IDispatch::GetIDsOfNames 역변환 메서드 작성 힌트 ( DISPID 로 메서드 이름 알아내는 것 )
58정성태10/3/200429884.NET Framework: 11. HttpContext의 간략이해
56정성태10/3/200426509.NET Framework: 10. [.NET 리모팅] 원격개체를 호출한 클라이언트의 연결이 유효한지 판단하는 방법.
... 196  197  198  [199]  200  201  202