link

package
v0.0.0-...-386ab62 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2023 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package link allows attaching eBPF programs to various kernel hooks.

Index

Examples

Constants

View Source
const (
	UnspecifiedType   = sys.BPF_LINK_TYPE_UNSPEC
	RawTracepointType = sys.BPF_LINK_TYPE_RAW_TRACEPOINT
	TracingType       = sys.BPF_LINK_TYPE_TRACING
	CgroupType        = sys.BPF_LINK_TYPE_CGROUP
	IterType          = sys.BPF_LINK_TYPE_ITER
	NetNsType         = sys.BPF_LINK_TYPE_NETNS
	XDPType           = sys.BPF_LINK_TYPE_XDP
	PerfEventType     = sys.BPF_LINK_TYPE_PERF_EVENT
	KprobeMultiType   = sys.BPF_LINK_TYPE_KPROBE_MULTI
)

Valid link types.

Variables

View Source
var (

	// ErrNoSymbol indicates that the given symbol was not found
	// in the ELF symbols table.
	ErrNoSymbol = errors.New("not found")
)
View Source
var ErrNotSupported = internal.ErrNotSupported

Functions

func AttachSocketFilter

func AttachSocketFilter(conn syscall.Conn, program *ebpf.Program) error

AttachSocketFilter attaches a SocketFilter BPF program to a socket.

func DetachSocketFilter

func DetachSocketFilter(conn syscall.Conn) error

DetachSocketFilter detaches a SocketFilter BPF program from a socket.

func QueryPrograms

func QueryPrograms(opts QueryOptions) ([]ebpf.ProgramID, error)

QueryPrograms retrieves ProgramIDs associated with the AttachType.

It only returns IDs of programs that were attached using PROG_ATTACH and not bpf_link. Returns (nil, nil) if there are no programs attached to the queried kernel resource. Calling QueryPrograms on a kernel missing PROG_QUERY will result in ErrNotSupported.

func RawAttachProgram

func RawAttachProgram(opts RawAttachProgramOptions) error

RawAttachProgram is a low level wrapper around BPF_PROG_ATTACH.

You should use one of the higher level abstractions available in this package if possible.

func RawDetachProgram

func RawDetachProgram(opts RawDetachProgramOptions) error

RawDetachProgram is a low level wrapper around BPF_PROG_DETACH.

You should use one of the higher level abstractions available in this package if possible.

Types

type CgroupInfo

type CgroupInfo sys.CgroupLinkInfo

type CgroupOptions

type CgroupOptions struct {
	// Path to a cgroupv2 folder.
	Path string
	// One of the AttachCgroup* constants
	Attach ebpf.AttachType
	// Program must be of type CGroup*, and the attach type must match Attach.
	Program *ebpf.Program
}

type Executable

type Executable struct {
	// contains filtered or unexported fields
}

Executable defines an executable program on the filesystem.

func OpenExecutable

func OpenExecutable(path string) (*Executable, error)

To open a new Executable, use:

OpenExecutable("/bin/bash")

The returned value can then be used to open Uprobe(s).

func (*Executable) Uprobe

func (ex *Executable) Uprobe(symbol string, prog *ebpf.Program, opts *UprobeOptions) (Link, error)

Uprobe attaches the given eBPF program to a perf event that fires when the given symbol starts executing in the given Executable. For example, /bin/bash::main():

ex, _ = OpenExecutable("/bin/bash")
ex.Uprobe("main", prog, nil)

When using symbols which belongs to shared libraries, an offset must be provided via options:

up, err := ex.Uprobe("main", prog, &UprobeOptions{Offset: 0x123})

Note: Setting the Offset field in the options supersedes the symbol's offset.

Losing the reference to the resulting Link (up) will close the Uprobe and prevent further execution of prog. The Link must be Closed during program shutdown to avoid leaking system resources.

Functions provided by shared libraries can currently not be traced and will result in an ErrNotSupported.

func (*Executable) Uretprobe

func (ex *Executable) Uretprobe(symbol string, prog *ebpf.Program, opts *UprobeOptions) (Link, error)

Uretprobe attaches the given eBPF program to a perf event that fires right before the given symbol exits. For example, /bin/bash::main():

ex, _ = OpenExecutable("/bin/bash")
ex.Uretprobe("main", prog, nil)

When using symbols which belongs to shared libraries, an offset must be provided via options:

up, err := ex.Uretprobe("main", prog, &UprobeOptions{Offset: 0x123})

Note: Setting the Offset field in the options supersedes the symbol's offset.

Losing the reference to the resulting Link (up) will close the Uprobe and prevent further execution of prog. The Link must be Closed during program shutdown to avoid leaking system resources.

Functions provided by shared libraries can currently not be traced and will result in an ErrNotSupported.

type ID

type ID = sys.LinkID

ID uniquely identifies a BPF link.

type Info

type Info struct {
	Type    Type
	ID      ID
	Program ebpf.ProgramID
	// contains filtered or unexported fields
}

Info contains metadata on a link.

func (Info) Cgroup

func (r Info) Cgroup() *CgroupInfo

Cgroup returns cgroup type-specific link info.

Returns nil if the type-specific link info isn't available.

func (Info) NetNs

func (r Info) NetNs() *NetNsInfo

NetNs returns netns type-specific link info.

Returns nil if the type-specific link info isn't available.

func (Info) Tracing

func (r Info) Tracing() *TracingInfo

Tracing returns tracing type-specific link info.

Returns nil if the type-specific link info isn't available.

func (Info) XDP

func (r Info) XDP() *XDPInfo

ExtraNetNs returns XDP type-specific link info.

Returns nil if the type-specific link info isn't available.

type Iter

type Iter struct {
	RawLink
}

Iter represents an attached bpf_iter.

func AttachIter

func AttachIter(opts IterOptions) (*Iter, error)

AttachIter attaches a BPF seq_file iterator.

func (*Iter) Open

func (it *Iter) Open() (io.ReadCloser, error)

Open creates a new instance of the iterator.

Reading from the returned reader triggers the BPF program.

type IterOptions

type IterOptions struct {
	// Program must be of type Tracing with attach type
	// AttachTraceIter. The kind of iterator to attach to is
	// determined at load time via the AttachTo field.
	//
	// AttachTo requires the kernel to include BTF of itself,
	// and it to be compiled with a recent pahole (>= 1.16).
	Program *ebpf.Program

	// Map specifies the target map for bpf_map_elem and sockmap iterators.
	// It may be nil.
	Map *ebpf.Map
}

type KprobeMultiOptions

type KprobeMultiOptions struct {
	// Symbols takes a list of kernel symbol names to attach an ebpf program to.
	//
	// Mutually exclusive with Addresses.
	Symbols []string

	// Addresses takes a list of kernel symbol addresses in case they can not
	// be referred to by name.
	//
	// Note that only start addresses can be specified, since the fprobe API
	// limits the attach point to the function entry or return.
	//
	// Mutually exclusive with Symbols.
	Addresses []uintptr

	// Cookies specifies arbitrary values that can be fetched from an eBPF
	// program via `bpf_get_attach_cookie()`.
	//
	// If set, its length should be equal to the length of Symbols or Addresses.
	// Each Cookie is assigned to the Symbol or Address specified at the
	// corresponding slice index.
	Cookies []uint64
}

KprobeMultiOptions defines additional parameters that will be used when opening a KprobeMulti Link.

type KprobeOptions

type KprobeOptions struct {
	// Arbitrary value that can be fetched from an eBPF program
	// via `bpf_get_attach_cookie()`.
	//
	// Needs kernel 5.15+.
	Cookie uint64
	// Offset of the kprobe relative to the traced symbol.
	// Can be used to insert kprobes at arbitrary offsets in kernel functions,
	// e.g. in places where functions have been inlined.
	Offset uint64
	// Increase the maximum number of concurrent invocations of a kretprobe.
	// Required when tracing some long running functions in the kernel.
	//
	// Deprecated: this setting forces the use of an outdated kernel API and is not portable
	// across kernel versions.
	RetprobeMaxActive int
}

KprobeOptions defines additional parameters that will be used when loading Kprobes.

type LSMOptions

type LSMOptions struct {
	// Program must be of type LSM with attach type
	// AttachLSMMac.
	Program *ebpf.Program
}
type Link interface {
	// Replace the current program with a new program.
	//
	// Passing a nil program is an error. May return an error wrapping ErrNotSupported.
	Update(*ebpf.Program) error

	// Persist a link by pinning it into a bpffs.
	//
	// May return an error wrapping ErrNotSupported.
	Pin(string) error

	// Undo a previous call to Pin.
	//
	// May return an error wrapping ErrNotSupported.
	Unpin() error

	// Close frees resources.
	//
	// The link will be broken unless it has been successfully pinned.
	// A link may continue past the lifetime of the process if Close is
	// not called.
	Close() error

	// Info returns metadata on a link.
	//
	// May return an error wrapping ErrNotSupported.
	Info() (*Info, error)
	// contains filtered or unexported methods
}

Link represents a Program attached to a BPF hook.

func AttachCgroup

func AttachCgroup(opts CgroupOptions) (Link, error)

AttachCgroup links a BPF program to a cgroup.

func AttachFreplace

func AttachFreplace(targetProg *ebpf.Program, name string, prog *ebpf.Program) (Link, error)

AttachFreplace attaches the given eBPF program to the function it replaces.

The program and name can either be provided at link time, or can be provided at program load time. If they were provided at load time, they should be nil and empty respectively here, as they will be ignored by the kernel. Examples:

AttachFreplace(dispatcher, "function", replacement)
AttachFreplace(nil, "", replacement)

func AttachLSM

func AttachLSM(opts LSMOptions) (Link, error)

AttachLSM links a Linux security module (LSM) BPF Program to a BPF hook defined in kernel modules.

func AttachRawTracepoint

func AttachRawTracepoint(opts RawTracepointOptions) (Link, error)

AttachRawTracepoint links a BPF program to a raw_tracepoint.

Requires at least Linux 4.17.

func AttachTracing

func AttachTracing(opts TracingOptions) (Link, error)

AttachTracing links a tracing (fentry/fexit/fmod_ret) BPF program or a BTF-powered raw tracepoint (tp_btf) BPF Program to a BPF hook defined in kernel modules.

func AttachXDP

func AttachXDP(opts XDPOptions) (Link, error)

AttachXDP links an XDP BPF program to an XDP hook.

func Kprobe

func Kprobe(symbol string, prog *ebpf.Program, opts *KprobeOptions) (Link, error)

Kprobe attaches the given eBPF program to a perf event that fires when the given kernel symbol starts executing. See /proc/kallsyms for available symbols. For example, printk():

kp, err := Kprobe("printk", prog, nil)

Losing the reference to the resulting Link (kp) will close the Kprobe and prevent further execution of prog. The Link must be Closed during program shutdown to avoid leaking system resources.

func KprobeMulti

func KprobeMulti(prog *ebpf.Program, opts KprobeMultiOptions) (Link, error)

KprobeMulti attaches the given eBPF program to the entry point of a given set of kernel symbols.

The difference with Kprobe() is that multi-kprobe accomplishes this in a single system call, making it significantly faster than attaching many probes one at a time.

Requires at least Linux 5.18.

func Kretprobe

func Kretprobe(symbol string, prog *ebpf.Program, opts *KprobeOptions) (Link, error)

Kretprobe attaches the given eBPF program to a perf event that fires right before the given kernel symbol exits, with the function stack left intact. See /proc/kallsyms for available symbols. For example, printk():

kp, err := Kretprobe("printk", prog, nil)

Losing the reference to the resulting Link (kp) will close the Kretprobe and prevent further execution of prog. The Link must be Closed during program shutdown to avoid leaking system resources.

On kernels 5.10 and earlier, setting a kretprobe on a nonexistent symbol incorrectly returns unix.EINVAL instead of os.ErrNotExist.

func KretprobeMulti

func KretprobeMulti(prog *ebpf.Program, opts KprobeMultiOptions) (Link, error)

KretprobeMulti attaches the given eBPF program to the return point of a given set of kernel symbols.

The difference with Kretprobe() is that multi-kprobe accomplishes this in a single system call, making it significantly faster than attaching many probes one at a time.

Requires at least Linux 5.18.

func LoadPinnedLink(fileName string, opts *ebpf.LoadPinOptions) (Link, error)

LoadPinnedLink loads a link that was persisted into a bpffs.

func Tracepoint

func Tracepoint(group, name string, prog *ebpf.Program, opts *TracepointOptions) (Link, error)

Tracepoint attaches the given eBPF program to the tracepoint with the given group and name. See /sys/kernel/debug/tracing/events to find available tracepoints. The top-level directory is the group, the event's subdirectory is the name. Example:

tp, err := Tracepoint("syscalls", "sys_enter_fork", prog, nil)

Losing the reference to the resulting Link (tp) will close the Tracepoint and prevent further execution of prog. The Link must be Closed during program shutdown to avoid leaking system resources.

Note that attaching eBPF programs to syscalls (sys_enter_*/sys_exit_*) is only possible as of kernel 4.14 (commit cf5f5ce).

type NetNsInfo

type NetNsInfo sys.NetNsLinkInfo
type NetNsLink struct {
	RawLink
}

NetNsLink is a program attached to a network namespace.

func AttachNetNs

func AttachNetNs(ns int, prog *ebpf.Program) (*NetNsLink, error)

AttachNetNs attaches a program to a network namespace.

Example
prog, err := createSkLookupProgram()
if err != nil {
	panic(err)
}
defer prog.Close()

// This can be a path to another netns as well.
netns, err := os.Open("/proc/self/ns/net")
if err != nil {
	panic(err)
}
defer netns.Close()

link, err := AttachNetNs(int(netns.Fd()), prog)
if err != nil {
	panic(err)
}

// The socket lookup program is now active until Close().
link.Close()
Output:

type QueryOptions

type QueryOptions struct {
	// Path can be a path to a cgroup, netns or LIRC2 device
	Path string
	// Attach specifies the AttachType of the programs queried for
	Attach ebpf.AttachType
	// QueryFlags are flags for BPF_PROG_QUERY, e.g. BPF_F_QUERY_EFFECTIVE
	QueryFlags uint32
}

QueryOptions defines additional parameters when querying for programs.

type RawAttachProgramOptions

type RawAttachProgramOptions struct {
	// File descriptor to attach to. This differs for each attach type.
	Target int
	// Program to attach.
	Program *ebpf.Program
	// Program to replace (cgroups).
	Replace *ebpf.Program
	// Attach must match the attach type of Program (and Replace).
	Attach ebpf.AttachType
	// Flags control the attach behaviour. This differs for each attach type.
	Flags uint32
}

type RawDetachProgramOptions

type RawDetachProgramOptions struct {
	Target  int
	Program *ebpf.Program
	Attach  ebpf.AttachType
}
type RawLink struct {
	// contains filtered or unexported fields
}

RawLink is the low-level API to bpf_link.

You should consider using the higher level interfaces in this package instead.

func AttachRawLink(opts RawLinkOptions) (*RawLink, error)

AttachRawLink creates a raw link.

func (*RawLink) Close

func (l *RawLink) Close() error

Close breaks the link.

Use Pin if you want to make the link persistent.

func (*RawLink) FD

func (l *RawLink) FD() int

FD returns the raw file descriptor.

func (*RawLink) Info

func (l *RawLink) Info() (*Info, error)

Info returns metadata about the link.

func (*RawLink) IsPinned

func (l *RawLink) IsPinned() bool

IsPinned returns true if the Link has a non-empty pinned path.

func (*RawLink) Pin

func (l *RawLink) Pin(fileName string) error

Pin persists a link past the lifetime of the process.

Calling Close on a pinned Link will not break the link until the pin is removed.

func (*RawLink) Unpin

func (l *RawLink) Unpin() error

Unpin implements the Link interface.

func (*RawLink) Update

func (l *RawLink) Update(new *ebpf.Program) error

Update implements the Link interface.

func (*RawLink) UpdateArgs

func (l *RawLink) UpdateArgs(opts RawLinkUpdateOptions) error

UpdateArgs updates a link based on args.

type RawLinkOptions

type RawLinkOptions struct {
	// File descriptor to attach to. This differs for each attach type.
	Target int
	// Program to attach.
	Program *ebpf.Program
	// Attach must match the attach type of Program.
	Attach ebpf.AttachType
	// BTF is the BTF of the attachment target.
	BTF btf.TypeID
	// Flags control the attach behaviour.
	Flags uint32
}

RawLinkOptions control the creation of a raw link.

type RawLinkUpdateOptions

type RawLinkUpdateOptions struct {
	New   *ebpf.Program
	Old   *ebpf.Program
	Flags uint32
}

RawLinkUpdateOptions control the behaviour of RawLink.UpdateArgs.

type RawTracepointOptions

type RawTracepointOptions struct {
	// Tracepoint name.
	Name string
	// Program must be of type RawTracepoint*
	Program *ebpf.Program
}

type TracepointOptions

type TracepointOptions struct {
	// Arbitrary value that can be fetched from an eBPF program
	// via `bpf_get_attach_cookie()`.
	//
	// Needs kernel 5.15+.
	Cookie uint64
}

TracepointOptions defines additional parameters that will be used when loading Tracepoints.

type TracingInfo

type TracingInfo sys.TracingLinkInfo

type TracingOptions

type TracingOptions struct {
	// Program must be of type Tracing with attach type
	// AttachTraceFEntry/AttachTraceFExit/AttachModifyReturn or
	// AttachTraceRawTp.
	Program *ebpf.Program
}

type Type

type Type = sys.LinkType

Type is the kind of link.

type UprobeOptions

type UprobeOptions struct {
	// Symbol address. Must be provided in case of external symbols (shared libs).
	// If set, overrides the address eventually parsed from the executable.
	Address uint64
	// The offset relative to given symbol. Useful when tracing an arbitrary point
	// inside the frame of given symbol.
	//
	// Note: this field changed from being an absolute offset to being relative
	// to Address.
	Offset uint64
	// Only set the uprobe on the given process ID. Useful when tracing
	// shared library calls or programs that have many running instances.
	PID int
	// Automatically manage SDT reference counts (semaphores).
	//
	// If this field is set, the Kernel will increment/decrement the
	// semaphore located in the process memory at the provided address on
	// probe attach/detach.
	//
	// See also:
	// sourceware.org/systemtap/wiki/UserSpaceProbeImplementation (Semaphore Handling)
	// github.com/torvalds/linux/commit/1cc33161a83d
	// github.com/torvalds/linux/commit/a6ca88b241d5
	RefCtrOffset uint64
	// Arbitrary value that can be fetched from an eBPF program
	// via `bpf_get_attach_cookie()`.
	//
	// Needs kernel 5.15+.
	Cookie uint64
}

UprobeOptions defines additional parameters that will be used when loading Uprobes.

type XDPAttachFlags

type XDPAttachFlags uint32

XDPAttachFlags represents how XDP program will be attached to interface.

const (
	// XDPGenericMode (SKB) links XDP BPF program for drivers which do
	// not yet support native XDP.
	XDPGenericMode XDPAttachFlags = 1 << (iota + 1)
	// XDPDriverMode links XDP BPF program into the driver’s receive path.
	XDPDriverMode
	// XDPOffloadMode offloads the entire XDP BPF program into hardware.
	XDPOffloadMode
)

type XDPInfo

type XDPInfo sys.XDPLinkInfo

type XDPOptions

type XDPOptions struct {
	// Program must be an XDP BPF program.
	Program *ebpf.Program

	// Interface is the interface index to attach program to.
	Interface int

	// Flags is one of XDPAttachFlags (optional).
	//
	// Only one XDP mode should be set, without flag defaults
	// to driver/generic mode (best effort).
	Flags XDPAttachFlags
}

Jump to

Keyboard shortcuts

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