manager

package module
Version: v0.2.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 9, 2022 License: AGPL-3.0 Imports: 25 Imported by: 0

README

介绍

HoneyGopher

ebpfmanager参照datadog/ebpf/manager包的思想,基于cilium/ebpf实现的ebpf类库封装。

相比cilium/ebpf实现配置化,自动加载,更具备面向对象思想,且实现了probe颗粒的卡开启关闭功能。 相比datadog/ebpf,实现了依赖包方式加载cilium/ebpf ,而非fork方式,这点与其期望走的方向一致。且依赖cilium/ebpf版本更新到最新v0.8.1。

Work is underway to convert this library to wrap the upstream library, rather than forking.

依赖

go get -d github.com/shuLhan/go-bindata/cmd/go-bindata

说明

manager与probe是一对多关系。每个probe必须配置SectionEbpfFuncName两个属性。如果是k(ret)probeu(ret)probe,则还需要配置AttachToFuncName属性。

    // UID 可选自定义的唯一字符串
    UID string
    
    // Section elf字节码的Section名字,比如SEC("[section]"). 用于识别probe的类型[ku](ret)?probe/xdp/(raw_)?tracepoint/tc等
    // 早期datadog/ebpf类库用于manager的collectionSpec.Programs的索引。
    // 但cilium/ebpf v0.7.0中,不被返回作为programSpec map作为索引。索引改用MatchFuncName
    Section string
    
    // AttachToFuncName 被HOOK的syscall名字,忽略系统内核版本、CPU位数,比如 mkdirat 会被转换为__x64_sys_mkdirat、__ia32_sys_mkdirat等
    // Uprobe时,直接作为挂载的函数名。
    // 若不填写,则自动获取  Section 字段的最后一段作为挂载函数名   
    AttachToFuncName string
    
    // EbpfFuncName 表示字节码内内核态C函数的名字,取自字节码elf的符号表
    EbpfFuncName string
    
    // funcName 目标hook对象的函数名;私有属性,会自动计算赋值。uprobe中,若为空,则使用offset。
    funcName  string

使用方法

参考examples目录下例子,比如uprobe

package main

import (
	"github.com/ehids/ebpfmanager"
	"github.com/sirupsen/logrus"
)

var m = &manager.Manager{
	Probes: []*manager.Probe{
		{
			Section:          "uprobe/readline",
			EbpfFuncName:     "uprobe_readline",
			AttachToFuncName: "readline",
			BinaryPath:       "/usr/bin/bash",
		},
	},
}

func main() {
	// Initialize the manager
	if err := m.Init(recoverAssets()); err != nil {
		logrus.Fatal(err)
	}

	// Start the manager
	if err := m.Start(); err != nil {
		logrus.Fatal(err)
	}

	logrus.Println("successfully started, head over to /sys/kernel/debug/tracing/trace_pipe")

	// Spawn a bash and right a command to trigger the probe
	if err := trigger(); err != nil {
		logrus.Error(err)
	}

	// Close the manager
	if err := m.Stop(manager.CleanAll); err != nil {
		logrus.Fatal(err)
	}
}

案例项目

A Linux Host-based Intrusion Detection System based on eBPF.

注意

  1. v0.7.0及以后的版本中,ebpf在loadProgram函数返回的progs map中,索引已经改为C代码中函数名。 见elf_reader.go312行res[prog.Name] = prog ,这点不同于老版本。(老版本是以section名字作为索引)
  2. datadog/ebpf af587081 Nov 17, 2021 版本上实现本类库。

Documentation

Index

Examples

Constants

View Source
const (
	Ingress = TrafficType(tc.HandleMinIngress)
	Egress  = TrafficType(tc.HandleMinEgress)
)
View Source
const (

	// MaxEventNameLen - maximum length for a kprobe (or uprobe) event name
	// MAX_EVENT_NAME_LEN (linux/kernel/trace/trace.h)
	MaxEventNameLen    = 64
	MinFunctionNameLen = 10
)

Variables

View Source
var (
	ErrManagerNotInitialized = errors.New("the manager must be initialized first")
	ErrManagerNotStarted     = errors.New("the manager must be started first")
	ErrManagerRunning        = errors.New("the manager is already running")

	// Deprecated: 废弃段相关问题
	ErrUnknownSection = errors.New("unknown section")

	ErrUnknownMatchFuncName    = errors.New("unknown EbpfFuncName")
	ErrUnknownMatchFuncSpec    = errors.New("unknown MatchFuncSpec")
	ErrUnknownMap              = errors.New("unknown bpf map")
	ErrPinnedObjectNotFound    = errors.New("pinned object not found")
	ErrMapNameInUse            = errors.New("the provided map name is already taken")
	ErrIdentificationPairInUse = errors.New("the provided identification pair already exists")
	ErrProbeNotInitialized     = errors.New("the probe must be initialized first")
	ErrSectionFormat           = errors.New("invalid section format")
	ErrSymbolNotFound          = errors.New("symbol not found")
	ErrKprobeIDNotExist        = errors.New("kprobe id file doesn't exist")
	ErrUprobeIDNotExist        = errors.New("uprobe id file doesn't exist")
	ErrCloneProbeRequired      = errors.New("use CloneProbe to load 2 instances of the same program")
	ErrInterfaceNotSet         = errors.New("interface not provided: at least one of Ifindex and Ifname must be set")
	ErrMapInitialized          = errors.New("map already initialized")
	ErrMapNotInitialized       = errors.New("the map must be initialized first")
	ErrMapNotRunning           = errors.New("the map is not running")
)

Functions

func ConcatErrors

func ConcatErrors(err1, err2 error) error

ConcatErrors - Concatenate 2 errors into one error.

func FindFilterFunction

func FindFilterFunction(funcName string) (string, error)

func FindSymbolOffsets

func FindSymbolOffsets(path string, pattern *regexp.Regexp) ([]elf.Symbol, error)

FindSymbolOffsets - Parses the provided file and returns the offsets of the symbols that match the provided pattern

func GenerateEventName

func GenerateEventName(probeType, funcName, UID string, attachPID int) (string, error)

func GetSyscallFnName

func GetSyscallFnName(name string) (string, error)

GetSyscallFnName - Returns the kernel function of the provided syscall, after reading /proc/kallsyms to retrieve the list of symbols of the current kernel.

func GetSyscallFnNameWithSymFile

func GetSyscallFnNameWithSymFile(name string, symFile string) (string, error)

GetSyscallFnNameWithSymFile - Returns the kernel function of the provided syscall, after reading symFile to retrieve the list of symbols of the current kernel.

func IsUnreferencedSymbol

func IsUnreferencedSymbol(err error) bool

IsUnreferencedSymbol returns true if err was caused by an unreferenced symbol.

func OpenAndListSymbols

func OpenAndListSymbols(path string) (*elf.File, []elf.Symbol, error)

OpenAndListSymbols - Opens an elf file and extracts all its symbols

func SanitizeUprobeAddresses

func SanitizeUprobeAddresses(f *elf.File, syms []elf.Symbol)

SanitizeUprobeAddresses - sanitizes the addresses of the provided symbols

Types

type AllOf

type AllOf struct {
	Selectors []ProbesSelector
}

AllOf - This selector is used to ensure that all the proves in the provided list are running.

func (*AllOf) EditProbeIdentificationPair

func (ao *AllOf) EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)

EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they now select the new one

func (*AllOf) GetProbesIdentificationPairList

func (ao *AllOf) GetProbesIdentificationPairList() []ProbeIdentificationPair

GetProbesIdentificationPairList - Returns the list of probes that this selector activates

func (*AllOf) RunValidator

func (ao *AllOf) RunValidator(manager *Manager) error

RunValidator - Ensures that the probes that were successfully activated follow the selector goal. For example, see OneOf.

func (*AllOf) String

func (ao *AllOf) String() string

type BestEffort

type BestEffort struct {
	Selectors []ProbesSelector
}

BestEffort - This selector is used to load probes in best effort mode

func (*BestEffort) EditProbeIdentificationPair

func (be *BestEffort) EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)

EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they now select the new one

func (*BestEffort) GetProbesIdentificationPairList

func (be *BestEffort) GetProbesIdentificationPairList() []ProbeIdentificationPair

GetProbesIdentificationPairList - Returns the list of probes that this selector activates

func (*BestEffort) RunValidator

func (be *BestEffort) RunValidator(manager *Manager) error

RunValidator - Ensures that the probes that were successfully activated follow the selector goal. For example, see OneOf.

func (*BestEffort) String

func (be *BestEffort) String() string

type ConstantEditor

type ConstantEditor struct {
	// Name - Name of the constant to rewrite
	Name string

	// Value - Value to write in the eBPF bytecode. When using the asm load method, the Value has to be a uint64.
	Value interface{}

	// FailOnMissing - If FailOMissing is set to true, the constant edition process will return an error if the constant
	// was missing in at least one program
	FailOnMissing bool

	// ProbeIdentificationPairs - Identifies the list of programs to edit. If empty, it will apply to all the programs
	// of the manager. Will return an error if at least one edition failed.
	ProbeIdentificationPairs []ProbeIdentificationPair
}

ConstantEditor - A constant editor tries to rewrite the value of a constant in a compiled eBPF program.

Constant edition only works before the eBPF programs are loaded in the kernel, and therefore before the Manager is started. If no program sections are provided, the manager will try to edit the constant in all eBPF programs.

type Editor

type Editor struct {
	ReferenceOffsets map[string][]int
	// contains filtered or unexported fields
}

Editor modifies eBPF instructions.

Example (RewriteConstant)

ExampleEditor_rewriteConstant shows how to change constants in compiled eBPF byte code.

The C should look something like this:

#define LOAD_CONSTANT(param, var) asm("%0 = " param " ll" : "=r"(var))

int xdp() {
    bool my_constant;
    LOAD_CONSTANT("SYMBOL_NAME", my_constant);

    if (my_constant) ...
// This assembly is roughly equivalent to what clang
// would emit for the C above.
insns := asm.Instructions{
	asm.LoadImm(asm.R0, 0, asm.DWord),
	asm.Return(),
}

insns[0].Reference = "my_ret"

editor := Edit(&insns)
if err := editor.RewriteConstant("my_ret", 42); err != nil {
	panic(err)
}

fmt.Printf("%0.0s", insns)
Output:

0: LdImmDW dst: r0 imm: 42 <my_ret>
2: Exit

func Edit

func Edit(insns *asm.Instructions) *Editor

Edit creates a new Editor.

The editor retains a reference to insns and modifies its contents.

func (*Editor) RewriteConstant

func (ed *Editor) RewriteConstant(symbol string, value uint64) error

RewriteConstant rewrites all loads of a symbol to a constant value.

This is a way to parameterize clang-compiled eBPF byte code at load time.

The following macro should be used to access the constant:

#define LOAD_CONSTANT(param, var) asm("%0 = " param " ll" : "=r"(var))

int xdp() {
    bool my_constant;
    LOAD_CONSTANT("SYMBOL_NAME", my_constant);

    if (my_constant) ...

Caveats:

- The symbol name you pick must be unique

- Failing to rewrite a symbol will not result in an error,
  0 will be loaded instead (subject to change)

Use IsUnreferencedSymbol if you want to rewrite potentially unused symbols.

type Manager

type Manager struct {

	// Probes - List of probes handled by the manager
	Probes []*Probe

	// Maps - List of maps handled by the manager. PerfMaps should not be defined here, but instead in the PerfMaps
	// section
	Maps []*Map

	// PerfMaps - List of perf ring buffers handled by the manager
	PerfMaps []*PerfMap
	// contains filtered or unexported fields
}

Manager - Helper structure that manages multiple eBPF programs and maps

func (*Manager) AddHook

func (m *Manager) AddHook(UID string, newProbe Probe) error

AddHook - Hook an existing program to a hook point. This is particularly useful when you need to trigger an existing program on a hook point that is determined at runtime. For example, you might want to hook an existing eBPF TC classifier to the newly created interface of a container. Make sure to specify a unique uid in the new probe, you will need it if you want to detach the program later. The original program is selected using the provided UID and the section provided in the new probe.

func (*Manager) CloneMap

func (m *Manager) CloneMap(name string, newName string, options MapOptions) (*ebpf.Map, error)

CloneMap - Duplicates the spec of an existing map, before creating a new one. Use a MapRoute to make this map available to the programs of the manager.

func (*Manager) ClonePerfRing

func (m *Manager) ClonePerfRing(name string, newName string, options MapOptions, perfMapOptions PerfMapOptions) (*ebpf.Map, error)

ClonePerfRing - Clone an existing perf map and create a new one with the same spec. Use a MapRoute to make this map available to the programs of the manager.

func (*Manager) CloneProgram

func (m *Manager) CloneProgram(UID string, newProbe Probe, constantsEditors []ConstantEditor, mapEditors map[string]*ebpf.Map) error

CloneProgram - Create a clone of a program, load it in the kernel and attach it to its hook point. Since the eBPF program instructions are copied before the program is loaded, you can edit them with a ConstantEditor, or remap the eBPF maps as you like. This is particularly useful to workaround the absence of Array of Maps and Hash of Maps: first create the new maps you need, then clone the program you're interested in and rewrite it with the new maps, using a MapEditor. The original program is selected using the provided UID and the section provided in the new probe. Note that the BTF based constant edition will note work with this method.

func (*Manager) DetachHook

func (m *Manager) DetachHook(section string, UID string) error

DetachHook - Detach an eBPF program from a hook point. If there is only one instance left of this program in the kernel, then the probe will be detached but the program will not be closed (so that it can be used later). In that case, calling DetachHook has essentially the same effect as calling Detach() on the right Probe instance. However, if there are more than one instance in the kernel of the requested program, then the probe selected by (section, UID) is detached, and its own version of the program is closed.

func (*Manager) DumpMaps

func (m *Manager) DumpMaps(maps ...string) (string, error)

DumpMaps - Return a string containing human readable info about eBPF maps Dumps the set of maps provided, otherwise dumping all maps with a DumpHandler set.

func (*Manager) GetMap

func (m *Manager) GetMap(name string) (*ebpf.Map, bool, error)

GetMap - Return a pointer to the requested eBPF map name: name of the map, as defined by its section SEC("maps/[name]")

func (*Manager) GetMapSpec

func (m *Manager) GetMapSpec(name string) (*ebpf.MapSpec, bool, error)

GetMapSpec - Return a pointer to the requested eBPF MapSpec. This is useful when duplicating a map.

func (*Manager) GetPerfMap

func (m *Manager) GetPerfMap(name string) (*PerfMap, bool)

GetPerfMap - Select a perf map by its name

func (*Manager) GetProbe

func (m *Manager) GetProbe(id ProbeIdentificationPair) (*Probe, bool)

GetProbe - Select a probe by its section and UID

func (*Manager) GetProgram

func (m *Manager) GetProgram(id ProbeIdentificationPair) ([]*ebpf.Program, bool, error)

GetProgram - Return a pointer to the requested eBPF program section: section of the program, as defined by its section SEC("[section]") id: unique identifier given to a probe. If UID is empty, then all the programs matching the provided section are returned.

func (*Manager) GetProgramSpec

func (m *Manager) GetProgramSpec(id ProbeIdentificationPair) ([]*ebpf.ProgramSpec, bool, error)

GetProgramSpec - Return a pointer to the requested eBPF program spec section: section of the program, as defined by its section SEC("[section]") id: unique identifier given to a probe. If UID is empty, then the original program spec with the right section in the collection spec (if found) is return

func (*Manager) Init

func (m *Manager) Init(elf io.ReaderAt) error

Init - Initialize the manager. elf: reader containing the eBPF bytecode

func (*Manager) InitWithOptions

func (m *Manager) InitWithOptions(elf io.ReaderAt, options Options) error

InitWithOptions - Initialize the manager. elf: reader containing the eBPF bytecode options: options provided to the manager to configure its initialization

func (*Manager) NewMap

func (m *Manager) NewMap(spec ebpf.MapSpec, options MapOptions) (*ebpf.Map, error)

NewMap - Create a new map using the provided parameters. The map is added to the list of maps managed by the manager. Use a MapRoute to make this map available to the programs of the manager.

func (*Manager) NewPerfRing

func (m *Manager) NewPerfRing(spec ebpf.MapSpec, options MapOptions, perfMapOptions PerfMapOptions) (*ebpf.Map, error)

NewPerfRing - Creates a new perf ring and start listening for events. Use a MapRoute to make this map available to the programs of the manager.

func (*Manager) Start

func (m *Manager) Start() error

Start - Attach eBPF programs, start perf ring readers and apply maps and tail calls routing.

func (*Manager) Stop

func (m *Manager) Stop(cleanup MapCleanupType) error

Stop - Detach all eBPF programs and stop perf ring readers. The cleanup parameter defines which maps should be closed. See MapCleanupType for mode.

func (*Manager) UpdateActivatedProbes

func (m *Manager) UpdateActivatedProbes(selectors []ProbesSelector) error

UpdateActivatedProbes - update the list of activated probes

func (*Manager) UpdateMapRoutes

func (m *Manager) UpdateMapRoutes(router ...MapRoute) error

UpdateMapRoutes - Update one or multiple map of maps structures so that the provided keys point to the provided maps.

func (*Manager) UpdateTailCallRoutes

func (m *Manager) UpdateTailCallRoutes(router ...TailCallRoute) error

UpdateTailCallRoutes - Update one or multiple program arrays so that the provided keys point to the provided programs.

type Map

type Map struct {

	// Name - Name of the map as defined in its section SEC("maps/[name]")
	Name string

	// Contents - The initial contents of the map. May be nil.
	Contents []ebpf.MapKV

	// Freeze - Whether to freeze a map after setting its initial contents.
	Freeze bool

	// Other options
	MapOptions
	// contains filtered or unexported fields
}

func (*Map) Close

func (m *Map) Close(cleanup MapCleanupType) error

Close - Close underlying eBPF map. When externalCleanup is set to true, even if the map was recovered from an external source (pinned or rewritten from another manager), the map is cleaned up.

func (*Map) Init

func (m *Map) Init(manager *Manager) error

Init - Initialize a map

type MapCleanupType

type MapCleanupType int

MapCleanupType - The map clean up type defines how the maps of a manager should be cleaned up on exit.

We call "external" a map that wasn't loaded by the current manager. Those maps can end up being used by the current manager through 2 different ways: either because they were pinned or because they were edited into the programs of the manager before they were loaded. However those maps might still be used by other managers out there, even after the current one closes.

A map can only be in one of the following categories

             ----------------------         ---------------------------------------
            |   Internally loaded  |       |           Externally loaded           |
             ----------------------         ---------------------------------------
Categories: |  Pinned | Not Pinned |       |  Pinned | Pinned and Edited  | Edited |
             ----------------------         ---------------------------------------
const (
	CleanInternalPinned          MapCleanupType = 1 << 1
	CleanInternalNotPinned       MapCleanupType = 1 << 2
	CleanExternalPinned          MapCleanupType = 1 << 3
	CleanExternalPinnedAndEdited MapCleanupType = 1 << 4
	CleanExternalEdited          MapCleanupType = 1 << 5
	CleanInternal                MapCleanupType = CleanInternalPinned | CleanInternalNotPinned
	CleanExternal                MapCleanupType = CleanExternalPinned | CleanExternalPinnedAndEdited | CleanExternalEdited
	CleanAll                     MapCleanupType = CleanInternal | CleanExternal
)

type MapOptions

type MapOptions struct {
	// PinPath - Once loaded, the eBPF map will be pinned to this path. If the map has already been pinned and is
	// already present in the kernel, then it will be loaded from this path.
	PinPath string

	// AlwaysCleanup - Overrides the clean up type given to the manager. See CleanupType for more.
	AlwaysCleanup bool

	// DumpHandler - Callback function called when manager.Dump() is called
	// and dump the current state (human readable)
	DumpHandler func(currentMap *Map, manager *Manager) string
}

MapOptions - Generic Map options that are not shared with the MapSpec definition

type MapRoute

type MapRoute struct {
	// RoutingMapName - Name of the BPF_MAP_TYPE_ARRAY_OF_MAPS or BPF_MAP_TYPE_HASH_OF_MAPS map, as defined in its
	// section SEC("maps/[RoutingMapName]")
	RoutingMapName string

	// Key - Key at which the program will be inserted in the routing map
	Key interface{}

	// RoutedName - Section of the map that will be inserted
	RoutedName string

	// Map - Map to insert in the routing map
	Map *ebpf.Map
}

MapRoute - A map route defines how multiple maps should be routed between eBPF programs.

The provided eBPF map will be inserted in the provided eBPF array of maps (or hash of maps), at the provided key. The inserted eBPF map can be provided by its section or by its *ebpf.Map representation.

type MapSpecEditor

type MapSpecEditor struct {
	// Type - Type of the map.
	Type ebpf.MapType
	// MaxEntries - Max Entries of the map.
	MaxEntries uint32
	// Flags - Flags provided to the kernel during the loading process.
	Flags uint32
	// EditorFlag - Use this flag to specify what fields should be updated. See MapSpecEditorFlag.
	EditorFlag MapSpecEditorFlag

	// InnerMap
	InnerMap *ebpf.MapSpec
}

MapSpecEditor - A MapSpec editor defines how specific parameters of specific maps should be updated at runtime

For example, this can be used if you need to change the max_entries of a map before it is loaded in the kernel, but you don't know what this value should be initially.

type MapSpecEditorFlag

type MapSpecEditorFlag uint

MapSpecEditorFlag - Flag used to specify what a MapSpecEditor should edit.

const (
	EditType       MapSpecEditorFlag = 1 << 1
	EditMaxEntries MapSpecEditorFlag = 1 << 2
	EditFlags      MapSpecEditorFlag = 1 << 3
)

type OneOf

type OneOf struct {
	Selectors []ProbesSelector
}

OneOf - This selector is used to ensure that at least of a list of probe selectors is valid. In other words, this can be used to ensure that at least one of a list of optional probes is activated.

func (*OneOf) EditProbeIdentificationPair

func (oo *OneOf) EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)

EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they now select the new one

func (*OneOf) GetProbesIdentificationPairList

func (oo *OneOf) GetProbesIdentificationPairList() []ProbeIdentificationPair

GetProbesIdentificationPairList - Returns the list of probes that this selector activates

func (*OneOf) RunValidator

func (oo *OneOf) RunValidator(manager *Manager) error

RunValidator - Ensures that the probes that were successfully activated follow the selector goal. For example, see OneOf.

func (*OneOf) String

func (oo *OneOf) String() string

type Options

type Options struct {
	// ActivatedProbes - List of the probes that should be activated, identified by their identification string.
	// If the list is empty, all probes will be activated.
	ActivatedProbes []ProbesSelector

	// ExcludedSections - A list of sections that should not even be verified. This list overrides the ActivatedProbes
	// list: since the excluded sections aren't loaded in the kernel, all the probes using those sections will be
	// deactivated.
	// Deprecated: 废弃段信息
	ExcludedSections []string

	// ExcludedEbpfFuncs 用于存储排除的符号表函数列表。来自ebpf字节码中符号表函数。
	ExcludedEbpfFuncs []string

	// ConstantsEditor - Post-compilation constant edition. See ConstantEditor for more.
	ConstantEditors []ConstantEditor

	// MapSpecEditor - Pre-loading MapSpec editors.
	MapSpecEditors map[string]MapSpecEditor

	// VerifierOptions - Defines the log level of the verifier and the size of its log buffer. Set to 0 to disable
	// logging and 1 to get a verbose output of the error. Increase the buffer size if the output is truncated.
	VerifierOptions ebpf.CollectionOptions

	// MapEditors - External map editor. The provided eBPF maps will overwrite the maps of the Manager if their names
	// match.
	// This is particularly useful to share maps across Managers (and therefore across isolated eBPF programs), without
	// having to use the MapRouter indirection. However this technique only works before the eBPF programs are loaded,
	// and therefore before the Manager is started. The keys of the map are the names of the maps to edit, as defined
	// in their sections SEC("maps/[name]").
	MapEditors map[string]*ebpf.Map

	// MapRouter - External map routing. See MapRoute for more.
	MapRouter []MapRoute

	// TailCallRouter - External tail call routing. See TailCallRoute for more.
	TailCallRouter []TailCallRoute

	// SymFile - Kernel symbol file. If not provided, the default `/proc/kallsyms` will be used.
	SymFile string

	// PerfRingBufferSize - Manager-level default value for the perf ring buffers. Defaults to the size of 1 page
	// on the system. See PerfMap.PerfRingBuffer for more.
	DefaultPerfRingBufferSize int

	// Watermark - Manager-level default value for the watermarks of the perf ring buffers.
	// See PerfMap.Watermark for more.
	DefaultWatermark int

	// DefaultKProbeMaxActive - Manager-level default value for the kprobe max active parameter.
	// See Probe.MaxActive for more.
	DefaultKProbeMaxActive int

	// ProbeRetry - Defines the number of times that a probe will retry to attach / detach on error.
	DefaultProbeRetry uint

	// ProbeRetryDelay - Defines the delay to wait before a probe should retry to attach / detach on error.
	DefaultProbeRetryDelay time.Duration

	// RLimit - The maps & programs provided to the manager might exceed the maximum allowed memory lock.
	// (RLIMIT_MEMLOCK) If a limit is provided here it will be applied when the manager is initialized.
	RLimit *unix.Rlimit
}

Options - Options of a Manager. These options define how a manager should be initialized.

type PerfMap

type PerfMap struct {

	// Map - A PerfMap has the same features as a normal Map
	Map
	PerfMapOptions
	// contains filtered or unexported fields
}

PerfMap - Perf ring buffer reader wrapper

func (*PerfMap) Init

func (m *PerfMap) Init(manager *Manager) error

Init - Initialize a map

func (*PerfMap) Pause

func (m *PerfMap) Pause() error

Pause - Pauses a perf ring buffer reader

func (*PerfMap) Resume

func (m *PerfMap) Resume() error

Resume - Resumes a perf ring buffer reader

func (*PerfMap) Start

func (m *PerfMap) Start() error

Start - Starts fetching events on a perf ring buffer

func (*PerfMap) Stop

func (m *PerfMap) Stop(cleanup MapCleanupType) error

Stop - Stops the perf ring buffer

type PerfMapOptions

type PerfMapOptions struct {
	// PerfRingBufferSize - Size in bytes of the perf ring buffer. Defaults to the manager value if not set.
	PerfRingBufferSize int

	// Watermark - The reader will start processing samples once their sizes in the perf ring buffer
	// exceed this value. Must be smaller than PerfRingBufferSize. Defaults to the manager value if not set.
	Watermark int

	// PerfErrChan - Perf reader error channel
	PerfErrChan chan error

	// DataHandler - Callback function called when a new sample was retrieved from the perf
	// ring buffer.
	DataHandler func(CPU int, data []byte, perfMap *PerfMap, manager *Manager)

	// LostHandler - Callback function called when one or more events where dropped by the kernel
	// because the perf ring buffer was full.
	LostHandler func(CPU int, count uint64, perfMap *PerfMap, manager *Manager)

	// PerfMapStats - Perf map statistics event like nr Read errors, lost samples,
	// RawSamples bytes count. Need to be initialized via manager.NewPerfMapStats()
	PerfMapStats *PerfMapStats

	// DumpHandler - Callback function called when manager.Dump() is called
	// and dump the current state (human readable)
	DumpHandler func(perfMap *PerfMap, manager *Manager) string
}

PerfMapOptions - Perf map specific options

type PerfMapStats

type PerfMapStats struct {
	ReadErrors  uint64
	RawSamples  map[int]uint64
	LostSamples map[int]uint64
}

PerfMapStats contain perf map read/errors statistics including per CPU map bytes and lost bytes

func NewPerfMapStats

func NewPerfMapStats() *PerfMapStats

NewPerfMapStats create/enable counting the perf map statistics performance/debug information

func (*PerfMapStats) Diff

func (new *PerfMapStats) Diff(old *PerfMapStats) (diff *PerfMapStats)

type Probe

type Probe struct {

	// UID - (optional) this field can be used to identify your probes when the same eBPF program is used on multiple
	// hook points. Keep in mind that the pair (probe section, probe UID) needs to be unique
	// system-wide for the kprobes and uprobes registration to work.
	UID string

	// Section - Section of the program, as defined in its section SEC("[section]"). This section is therefore made of
	// a prefix
	//
	// NOTE: 字节码中段信息不被新版ebpf库programSpec map作为索引。 v0.7.0
	// 故,不能作为programSpec[]的索引来使用。索引改用MatchFuncName
	Section string

	// CopyProgram - When enabled, this option will make a unique copy of the program section for the current program
	CopyProgram bool

	// EbpfFuncName - Name of the syscall on which the program should be hooked. As the exact kernel symbol may
	// differ from one kernel version to the other, the right prefix will be computed automatically at runtime.
	// If a syscall name is not provided, the section name (without its probe type prefix) is assumed to be the
	// hook point.
	EbpfFuncName string

	// AttachToFuncName - Pattern used to find the function(s) to attach to
	// FOR KPROBES: When this option is activated, the provided pattern is matched against the list of available symbols
	// in /sys/kernel/debug/tracing/available_filter_functions. If the exact function does not exist, then the first
	// symbol matching the provided pattern will be used. This option requires debugfs.
	//
	// FOR UPROBES: When this option is activated, the provided pattern is matched the list of symbols in the symbol
	// table of the provided elf binary. If the exact function does not exist, then the first symbol matching the
	// provided pattern will be used.
	AttachToFuncName string

	// Enabled - Indicates if a probe should be enabled or not. This parameter can be set at runtime using the
	// Manager options (see ActivatedProbes)
	Enabled bool

	// PinPath - Once loaded, the eBPF program will be pinned to this path. If the eBPF program has already been pinned
	// and is already running in the kernel, then it will be loaded from this path.
	PinPath string

	// KProbeMaxActive - (kretprobes) With kretprobes, you can configure the maximum number of instances of the function that can be
	// probed simultaneously with maxactive. If maxactive is 0 it will be set to the default value: if CONFIG_PREEMPT is
	// enabled, this is max(10, 2*NR_CPUS); otherwise, it is NR_CPUS. For kprobes, maxactive is ignored.
	KProbeMaxActive int

	// UprobeOffset - If UprobeOffset is provided, the uprobe will be attached to it directly without looking for the
	// symbol in the elf binary. If the file is a non-PIE executable, the provided address must be a virtual address,
	// otherwise it must be an offset relative to the file load address.
	UprobeOffset uint64

	// ProbeRetry - Defines the number of times that the probe will retry to attach / detach on error.
	ProbeRetry uint

	// ProbeRetryDelay - Defines the delay to wait before the probe should retry to attach / detach on error.
	ProbeRetryDelay time.Duration

	// BinaryPath - (uprobes) A Uprobe is attached to a specific symbol in a user space binary. The offset is
	// automatically computed for the symbol name provided in the uprobe section ( SEC("uprobe/[symbol_name]") ).
	BinaryPath string

	// CGrouPath - (cgroup family programs) All CGroup programs are attached to a CGroup (v2). This field provides the
	// path to the CGroup to which the probe should be attached. The attach type is determined by the section.
	CGroupPath string

	// SocketFD - (socket filter) Socket filter programs are bound to a socket and filter the packets they receive
	// before they reach user space. The probe will be bound to the provided file descriptor
	SocketFD int

	// Ifindex - (TC classifier & XDP) Interface index used to identify the interface on which the probe will be
	// attached. If not set, fall back to Ifname.
	Ifindex int32

	// Ifname - (TC Classifier & XDP) Interface name on which the probe will be attached.
	Ifname string

	// IfindexNetns - (TC Classifier & XDP) Network namespace in which the network interface lives
	IfindexNetns uint64

	// XDPAttachMode - (XDP) XDP attach mode. If not provided the kernel will automatically select the best available
	// mode.
	XDPAttachMode XdpAttachMode

	// NetworkDirection - (TC classifier) Network traffic direction of the classifier. Can be either Ingress or Egress. Keep
	// in mind that if you are hooking on the host side of a virtuel ethernet pair, Ingress and Egress are inverted.
	NetworkDirection TrafficType
	// contains filtered or unexported fields
}

Probe - Main eBPF probe wrapper. This structure is used to store the required data to attach a loaded eBPF program to its hook point.

func (*Probe) Attach

func (p *Probe) Attach() error

Attach - Attaches the probe to the right hook point in the kernel depending on the program type and the provided parameters.

func (*Probe) Benchmark

func (p *Probe) Benchmark(in []byte, repeat int, reset func()) (uint32, time.Duration, error)

Benchmark - Benchmark runs the Program with the given input for a number of times and returns the time taken per iteration.

Returns the result of the last execution of the program and the time per run or an error. reset is called whenever the benchmark syscall is interrupted, and should be set to testing.B.ResetTimer or similar.

func (*Probe) Copy

func (p *Probe) Copy() *Probe

Copy - Returns a copy of the current probe instance. Only the exported fields are copied.

func (*Probe) Detach

func (p *Probe) Detach() error

Detach - Detaches the probe from its hook point depending on the program type and the provided parameters. This method does not close the underlying eBPF program, which means that Attach can be called again later.

func (*Probe) GetIdentificationPair

func (p *Probe) GetIdentificationPair() ProbeIdentificationPair

GetIdentificationPair - Returns the identification pair (probe section, probe UID)

func (*Probe) GetLastError

func (p *Probe) GetLastError() error

GetLastError - Returns the last error that the probe encountered

func (*Probe) IdentificationPairMatches

func (p *Probe) IdentificationPairMatches(id ProbeIdentificationPair) bool

IdentificationPairMatches - Returns true if the identification pair (probe uid, probe section) matches.

func (*Probe) Init

func (p *Probe) Init(manager *Manager) error

Init - Initialize a probe

func (*Probe) InitWithOptions

func (p *Probe) InitWithOptions(manager *Manager, manualLoadNeeded bool, checkPin bool) error

InitWithOptions - Initializes a probe with options

func (*Probe) IsInitialized

func (p *Probe) IsInitialized() bool

IsInitialized - Returns true if the probe was successfully initialized, started and is currently running.

func (*Probe) IsRunning

func (p *Probe) IsRunning() bool

IsRunning - Returns true if the probe was successfully initialized, started and is currently running.

func (*Probe) Program

func (p *Probe) Program() *ebpf.Program

func (*Probe) Stop

func (p *Probe) Stop() error

Stop - Detaches the probe from its hook point and close the underlying eBPF program.

func (*Probe) Test

func (p *Probe) Test(in []byte) (uint32, []byte, error)

Test - Triggers the probe with the provided test data. Returns the length of the output, the raw output or an error.

type ProbeIdentificationPair

type ProbeIdentificationPair struct {
	UID string
	//Section string
	EbpfFuncName string //在cilium/efbp v0.7.0里,返回的paramsspec中,改为以.o字节码中符号表函数名为索引的map,故这里改为matchfunName。 section信息无法使用
}

func (ProbeIdentificationPair) Matches

Matches - Returns true if the identification pair (probe uid, probe section) matches.

func (ProbeIdentificationPair) String

func (pip ProbeIdentificationPair) String() string

type ProbeSelector

type ProbeSelector struct {
	ProbeIdentificationPair
}

ProbeSelector - This selector is used to unconditionally select a probe by its identification pair and validate that it is activated

func (*ProbeSelector) EditProbeIdentificationPair

func (ps *ProbeSelector) EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)

EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they mow select the new one

func (*ProbeSelector) GetProbesIdentificationPairList

func (ps *ProbeSelector) GetProbesIdentificationPairList() []ProbeIdentificationPair

GetProbesIdentificationPairList - Returns the list of probes that this selector activates

func (*ProbeSelector) RunValidator

func (ps *ProbeSelector) RunValidator(manager *Manager) error

RunValidator - Ensures that the probes that were successfully activated follow the selector goal. For example, see OneOf.

type ProbesSelector

type ProbesSelector interface {
	// GetProbesIdentificationPairList - Returns the list of probes that this selector activates
	GetProbesIdentificationPairList() []ProbeIdentificationPair
	// RunValidator - Ensures that the probes that were successfully activated follow the selector goal.
	// For example, see OneOf.
	RunValidator(manager *Manager) error
	// EditProbeIdentificationPair - Changes all the selectors looking for the old ProbeIdentificationPair so that they
	// mow select the new one
	EditProbeIdentificationPair(old ProbeIdentificationPair, new ProbeIdentificationPair)
}

ProbesSelector - A probe selector defines how a probe (or a group of probes) should be activated.

For example, this can be used to specify that out of a group of optional probes, at least one should be activated.

type TailCallRoute

type TailCallRoute struct {
	// ProgArrayName - Name of the BPF_MAP_TYPE_PROG_ARRAY map as defined in its section SEC("maps/[ProgArray]")
	ProgArrayName string

	// Key - Key at which the program will be inserted in the ProgArray map
	Key uint32

	// ProbeIdentificationPair - Selector of the program to insert in the ProgArray map
	ProbeIdentificationPair ProbeIdentificationPair

	// Program - Program to insert in the ProgArray map
	Program *ebpf.Program
}

TailCallRoute - A tail call route defines how tail calls should be routed between eBPF programs.

The provided eBPF program will be inserted in the provided eBPF program array, at the provided key. The eBPF program can be provided by its section or by its *ebpf.Program representation.

type TrafficType

type TrafficType uint32

type XdpAttachMode

type XdpAttachMode int

XdpAttachMode selects a way how XDP program will be attached to interface

const (
	// XdpAttachModeNone stands for "best effort" - kernel automatically
	// selects best mode (would try Drv first, then fallback to Generic).
	// NOTE: Kernel will not fallback to Generic XDP if NIC driver failed
	//       to install XDP program.
	XdpAttachModeNone XdpAttachMode = 0
	// XdpAttachModeSkb is "generic", kernel mode, less performant comparing to native,
	// but does not requires driver support.
	XdpAttachModeSkb XdpAttachMode = 1 << 1
	// XdpAttachModeDrv is native, driver mode (support from driver side required)
	XdpAttachModeDrv XdpAttachMode = 1 << 2
	// XdpAttachModeHw suitable for NICs with hardware XDP support
	XdpAttachModeHw XdpAttachMode = 1 << 3
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL