eBPF BCC 实现UNIX socket抓包「建议收藏」

eBPF BCC 实现UNIX socket抓包「建议收藏」在之前,我写了一个《eBPFbpftrace实现个UNIXsocket抓包试试》,但是很受限啊,不能完整打印包数据信息,今天又写了一个BCC的,感觉没问题了。不多说,直接上代码:#!/usr/bin/python#@lint-avoid-python-3-compatibility-imports##undumpDumpUNIXsocketpackets.#ForLinux,usesBCC,eBPF.Embedded

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

在之前,我写了一个《eBPF bpftrace 实现个UNIX socket抓包试试》,但是很受限啊,不能完整打印包数据信息,今天又写了一个BCC的,感觉没问题了。

不多说,直接上代码:

#!/usr/bin/python
# @lint-avoid-python-3-compatibility-imports
# 
# undump        Dump UNIX socket packets.
#               For Linux, uses BCC, eBPF. Embedded C.
# USAGE: undump [-h] [-t] [-p PID]
#
# This uses dynamic tracing of kernel functions, and will need to be updated
# to match kernel changes.
#
# Copyright (c) 2021 Rong Tao.
# Licensed under the GPL License, Version 2.0
#
# 27-Aug-2021   Rong Tao   Created this.
#
from __future__ import print_function
from bcc import BPF
from bcc.containers import filter_by_containers
from bcc.utils import printb
import argparse
from socket import inet_ntop, ntohs, AF_INET, AF_INET6
from struct import pack
from time import sleep
from datetime import datetime
import sys

# arguments
examples = """examples:
    ./undump           # trace/dump all UNIX packets
    ./undump -t        # include timestamps
    ./undump -p 181    # only trace/dump PID 181
"""
parser = argparse.ArgumentParser(
    description="Dump UNIX socket packets",
    formatter_class=argparse.RawDescriptionHelpFormatter,
    epilog=examples)
    
parser.add_argument("-t", "--timestamp", 
        action="store_true", help="include timestamp on output")
parser.add_argument("-p", "--pid",
        help="trace this PID only")
args = parser.parse_args()

# define BPF program
bpf_text = """
#include <uapi/linux/ptrace.h>
#include <net/sock.h>
#include <bcc/proto.h>
#include <linux/aio.h>
#include <linux/socket.h>
#include <linux/net.h>
#include <linux/fs.h>
#include <linux/mount.h>
#include <linux/module.h>
#include <net/sock.h>
#include <net/af_unix.h>


// separate data structs for ipv4 and ipv6
struct stream_data_t {
    u64 ts_us;
    u32 pid;
    u32 uid;
    u32 sock_state;
    u32 sock_type;  //type of socket[STREAM|DRGMA]
    u64 sock_flags;
    char task[TASK_COMM_LEN];
    char *unix_sock_path;
    int msg_namelen;
};
BPF_PERF_OUTPUT(stream_recvmsg_events);

#define MAX_PKT 512
struct recv_data_t {
    u32 recv_len;
    u8  pkt[MAX_PKT];
};

// single element per-cpu array to hold the current event off the stack
BPF_PERCPU_ARRAY(unix_data, struct recv_data_t,1);

BPF_PERF_OUTPUT(unix_recv_events);


//static int unix_stream_recvmsg(struct socket *sock, struct msghdr *msg,
//			       size_t size, int flags)
int trace_stream_entry(struct pt_regs *ctx)
{
    int ret = PT_REGS_RC(ctx);
    
    u64 pid_tgid = bpf_get_current_pid_tgid();
    u32 pid = pid_tgid >> 32;
    u32 tid = pid_tgid;

    FILTER_PID

    struct stream_data_t data4 = {.pid = pid,};
    data4.uid = bpf_get_current_uid_gid();
    data4.ts_us = bpf_ktime_get_ns() / 1000;

    struct socket *sock = (struct socket *)PT_REGS_PARM1(ctx);   
    struct msghdr *msg = (struct msghdr *)PT_REGS_PARM2(ctx);    

    data4.sock_state = sock->state;
    data4.sock_type = sock->type;
    data4.sock_flags = sock->flags;

    data4.msg_namelen = msg->msg_namelen;
    
    bpf_get_current_comm(&data4.task, sizeof(data4.task));
    
    struct unix_sock *unsock = (struct unix_sock *)sock->sk;
    data4.unix_sock_path = (char *)unsock->path.dentry->d_name.name;
    
    stream_recvmsg_events.perf_submit(ctx, &data4, sizeof(data4));

    
    return 0;
};


int trace_unix_stream_read_actor(struct pt_regs *ctx)
{
    u32 zero = 0;
    int ret = PT_REGS_RC(ctx);
    u64 pid_tgid = bpf_get_current_pid_tgid();
    u32 pid = pid_tgid >> 32;
    u32 tid = pid_tgid;

    FILTER_PID

	struct sk_buff *skb = (struct sk_buff *)PT_REGS_PARM1(ctx);

    struct recv_data_t *data = unix_data.lookup(&zero);
    if (!data) 
        return 0;

    unsigned int data_len = skb->len;
    if(data_len > MAX_PKT)
        return 0;
        
    void *iodata = (void *)skb->data;
    data->recv_len = data_len;
    
    bpf_probe_read(data->pkt, data_len, iodata);
    unix_recv_events.perf_submit(ctx, data, data_len+sizeof(u32));
    
    return 0;
}

"""

if args.pid:
    bpf_text = bpf_text.replace('FILTER_PID',
        'if (pid != %s) { return 0; }' % args.pid)

bpf_text = bpf_text.replace('FILTER_PID', '')
    


# process event
def print_stream_event(cpu, data, size):
    event = b["stream_recvmsg_events"].event(data)
    global start_ts
    if args.timestamp:
        if start_ts == 0:
            start_ts = event.ts_us
        printb(b"%-9.3f" % ((float(event.ts_us) - start_ts) / 1000000), nl="")
    printb(b"%-6s %-12s" % (event.pid, event.task))

# process event
def print_recv_pkg(cpu, data, size):
    event = b["unix_recv_events"].event(data)
    print("----------------", end="")
    for i in range(0, event.recv_len):
        print("%02x " % event.pkt[i], end="")
        sys.stdout.flush()
        if (i+1)%16 == 0:
            print("")
            print("----------------", end="")
    print("\n----------------recv %d bytes" % event.recv_len)
    

# initialize BPF
b = BPF(text=bpf_text)
b.attach_kprobe(event="unix_stream_recvmsg", fn_name="trace_stream_entry")
b.attach_kprobe(event="unix_stream_read_actor", fn_name="trace_unix_stream_read_actor")


print("Tracing UNIX socket packets ... Hit Ctrl-C to end")

# header
if args.timestamp:
    print("%-9s" % ("TIME(s)"), end="")


print("%-6s %-12s" % ("PID", "COMM"), end="")
print()


print()
start_ts = 0

# read events
b["stream_recvmsg_events"].open_perf_buffer(print_stream_event)
b["unix_recv_events"].open_perf_buffer(print_recv_pkg)

while True:
    try:
        b.perf_buffer_poll()
    except KeyboardInterrupt:
        exit()

help信息

[root@localhost study]# ./undump.py -h
usage: undump.py [-h] [-t] [-p PID]

Dump UNIX socket packets

optional arguments:
  -h, --help         show this help message and exit
  -t, --timestamp    include timestamp on output
  -p PID, --pid PID  trace this PID only

examples:
    ./undump           # trace/dump all UNIX packets
    ./undump -t        # include timestamps
    ./undump -p 181    # only trace/dump PID 181

效果:

eBPF BCC 实现UNIX socket抓包「建议收藏」

abcdef前面的字段是我的消息头

 

struct MsgHdr {
    int src;
    int dst;
    int id;
    char data[];
}__attribute__((packed));

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/191175.html原文链接:https://javaforall.net

(0)
上一篇 2026年2月6日 下午1:15
下一篇 2026年2月6日 下午1:43


相关推荐

  • 最简单DIY串口蓝牙硬件实现方案

    最简单DIY串口蓝牙硬件实现方案51 单片机物联网智能小车系列文章目录第一篇 最简单 DIY 的 51 蓝牙遥控小车设计方案第二篇 最简单 DIY 串口蓝牙硬件实现方案文章目录 51 单片机物联网智能小车系列文章目录前言一 最简单 DIY 串口蓝牙硬件实现方案是什么 二 制作步骤 1 搭建 ESP32 开发环境 2 下载代码 3 根据软件和硬件完成硬件连接三 仿真与调试 1 准备好硬件 小车上电和打开 arduino 串口监视器 输入指令 点击发送 2 接收小车返回的响应总结前言 daodanjishui 物联网核心原创技术之最简单 DIY 串口

    2026年3月18日
    1
  • NLP学习之使用pytorch搭建textCNN模型进行中文文本分类

    NLP学习之使用pytorch搭建textCNN模型进行中文文本分类最近花周末两天时间利用pytorch实现了TextCNN进行了中文文本分类,在此进行记录。数据获取中文数据是从https://github.com/brightmart/nlp_chinese_corpus下载的。具体是第3个,百科问答Json版,因为感觉大小适中,适合用来学习。下载下来得到两个文件:baike_qa_train.json和baike_qa_valid.json。内容如下:{…

    2022年6月28日
    148
  • Hello-Agents —— 02智能体发展史 通俗总结

    Hello-Agents —— 02智能体发展史 通俗总结

    2026年3月16日
    3
  • 常用存储过程语法

    常用存储过程语法 前面学过了基本的存储过程,见 存储过程入门 现在学一下常用的存储过程的语法,只要花一点点时间学习下,就能用存储过程实现很复杂的功能,可以少写很多代码。 为了方便说明,数据库使用SQLServer的示例数据库,Northwind和pubs,如果SQLServer中没有的话,可以按下面的方法安装1,下载SQL2000SampleDb.msi,下载地址是:http://ww

    2022年7月17日
    20
  • W3C标准及规范_地脚螺栓标准规范

    W3C标准及规范_地脚螺栓标准规范1.概念:W3C标准中文名:万维网联盟,外文名:WorldWideWebConsortium万维网联盟标准不是某一个标准,而是一些列标准的集合。网页主要有三部分组成:结构(Structure)、表现(Presentation)、行为(Behavior)。对应的标准也有三方面:结构化标准主要包括XHTML和XML,表现标准语言主要包括CSS、行为标准主要包括(如W3CDOM)、…

    2025年12月15日
    3
  • Android开发——LinearLayout和RelativeLayout的性能对比

    Android开发——LinearLayout和RelativeLayout的性能对比0 前言我们都知道新建一个 Android 项目自动生成的 Xml 布局文件的根节点默认是 RelativeLayo 这不是 IDE 默认设置 而是由 android sdk tools templates activities EmptyActivit root res layout activity simple xml ftl 这个文件事先就定好了的 在我们的理解里貌似 LinearLayout 的性能是

    2026年3月19日
    6

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号