utils

package
v0.0.0-...-663520b Latest Latest
Warning

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

Go to latest
Published: Dec 27, 2024 License: Apache-2.0 Imports: 44 Imported by: 0

Documentation

Overview

Package utils holds utils related files

Package utils groups multiple utils function that can be used by the secl package

Package utils holds utils related files

Index

Constants

View Source
const ContainerIDLen = sha256.Size * 2

ContainerIDLen is the length of a container ID is the length of the hex representation of a sha256 hash

Variables

View Source
var Syscalls = map[SyscallKey]string{}/* 713 elements not displayed */

Syscalls maps the (arch,syscall_id) to the syscall string

Functions

func BoolTouint64

func BoolTouint64(value bool) uint64

BoolTouint64 converts a boolean value to an uint64

func BuildPatterns

func BuildPatterns(ruleset []*rules.RuleDefinition) []*rules.RuleDefinition

BuildPatterns find and build patterns for the path in the ruleset

func CapEffCapEprm

func CapEffCapEprm(pid uint32) (uint64, uint64, error)

CapEffCapEprm returns the effective and permitted kernel capabilities of a process

func CgroupSysPath

func CgroupSysPath(controller string, path string, file string) string

CgroupSysPath returns the path to the provided file within the provided cgroup

func CgroupTaskPath

func CgroupTaskPath(tgid, pid uint32) string

CgroupTaskPath returns the path to the cgroup file of a pid in /proc

func CheckForPatterns

func CheckForPatterns(path string) string

CheckForPatterns replace patterns like uuid with *

func EnvVars

func EnvVars(priorityEnvsPrefixes []string, pid uint32, maxEnvVars int) ([]string, bool, error)

EnvVars returns a array with the environment variables of the given pid

func FetchLoadedModules

func FetchLoadedModules() (map[string]ProcFSModule, error)

FetchLoadedModules returns a map of loaded modules

func FindPidNamespace

func FindPidNamespace(nspid uint32, ns uint64) (uint32, error)

FindPidNamespace search and return the host PID for the given namespaced PID + its namespace

func FindTraceesByTracerPid

func FindTraceesByTracerPid(pid uint32) ([]uint32, error)

FindTraceesByTracerPid returns the process list being trced by the given tracer host PID

func GetAgentSemverVersion

func GetAgentSemverVersion() (*semver.Version, error)

GetAgentSemverVersion returns the agent version as a semver version

func GetEndpointURL

func GetEndpointURL(endpoint logsconfig.Endpoint, uri string) string

GetEndpointURL returns the formatted URL of the provided endpoint

func GetFSTypeFromFilePath

func GetFSTypeFromFilePath(path string) string

GetFSTypeFromFilePath returns the filesystem type of the mount holding the speficied file path

func GetHostname

func GetHostname() (string, error)

GetHostname attempts to acquire a hostname by connecting to the core agent's gRPC endpoints.

func GetHostnameWithContextAndFallback

func GetHostnameWithContextAndFallback(ctx context.Context) (string, error)

GetHostnameWithContextAndFallback attempts to acquire a hostname by connecting to the core agent's gRPC endpoints extending the given context, or falls back to local resolution

func GetLoginUID

func GetLoginUID(pid uint32) (uint32, error)

GetLoginUID returns the login uid of the provided process

func GetNsPids

func GetNsPids(pid uint32, task string) ([]uint32, error)

GetNsPids returns the namespaced pids of the the givent root pid

func GetPidTasks

func GetPidTasks(pid uint32) ([]string, error)

GetPidTasks returns the task IDs of a process

func GetProcContainerContext

func GetProcContainerContext(tgid, pid uint32) (containerutils.ContainerID, model.CGroupContext, error)

GetProcContainerContext returns the container ID which the process belongs to along with its manager. Returns "" if the process does not belong to a container.

func GetProcContainerID

func GetProcContainerID(tgid, pid uint32) (containerutils.ContainerID, error)

GetProcContainerID returns the container ID which the process belongs to. Returns "" if the process does not belong to a container.

func GetProcessPidNamespace

func GetProcessPidNamespace(pid uint32) (uint64, error)

GetProcessPidNamespace returns the PID namespace of the given PID

func GetProcesses

func GetProcesses() ([]*process.Process, error)

GetProcesses returns list of active processes

func GetTagName

func GetTagName(tag string) string

GetTagName returns the key of a tag in the tag_name:tag_value format

func GetTagValue

func GetTagValue(tagName string, tags []string) string

GetTagValue returns the value of the given tag in the given list

func GetTracerPid

func GetTracerPid(pid uint32) (uint32, error)

GetTracerPid returns the tracer pid of the the givent root pid

func Getpid

func Getpid() uint32

Getpid returns the current process ID in the host namespace

func LoginUIDPath

func LoginUIDPath(pid uint32) string

LoginUIDPath returns the path to the loginuid file of a pid in /proc

func MarshalEasyJSON

func MarshalEasyJSON(i easyjson.Marshaler) ([]byte, error)

MarshalEasyJSON easyjson marshal helper

func Mkdev

func Mkdev(major uint32, minor uint32) uint32

Mkdev returns the representation of a device use the kernel algorithm, the golang unix.Mkdev function bring inconsistency between representations of device https://elixir.bootlin.com/linux/v6.4.9/source/include/linux/kdev_t.h#L12

func ModulesPath

func ModulesPath() string

ModulesPath returns the path to the modules file in /proc

func NewCookie

func NewCookie() uint64

NewCookie returns a new random cookie

func NumCPU

func NumCPU() (int, error)

NumCPU returns the count of CPUs in the CPU affinity mask of the pid 1 process

func ParseCgroupFileValue

func ParseCgroupFileValue(controller string, path string, file string) (int, error)

ParseCgroupFileValue parses the content of a cgroup file into an int

func PathPatternBuilder

func PathPatternBuilder(pattern string, path string, opts PathPatternMatchOpts) (string, bool)

PathPatternBuilder pattern builder for files

func PathPatternMatch

func PathPatternMatch(pattern string, path string, opts PathPatternMatchOpts) bool

PathPatternMatch pattern builder for files

func PidTTY

func PidTTY(pid uint32) string

PidTTY returns the TTY of the given pid

func ProcExePath

func ProcExePath(pid uint32) string

ProcExePath returns the path to the exe file of a pid in /proc

func ProcRootFilePath

func ProcRootFilePath(pid uint32, file string) string

ProcRootFilePath returns the path to the input file after prepending the proc root path of the given pid

func ProcRootPath

func ProcRootPath(pid uint32) string

ProcRootPath returns the path to the root directory of a pid in /proc

func RandNonZeroUint64

func RandNonZeroUint64() uint64

RandNonZeroUint64 returns a new non-zero uint64

func RandString

func RandString(n int) string

RandString returns a random string of the given length size

func ReadCgroupFile

func ReadCgroupFile(controller string, path string, file string) ([]byte, string, error)

ReadCgroupFile reads the content of a cgroup file

func RuntimeArch

func RuntimeArch() string

RuntimeArch returns the arch as will be visible in CWS events and security profiles

func StatusPath

func StatusPath(pid uint32) string

StatusPath returns the path to the status file of a pid in /proc

func TaskStatusPath

func TaskStatusPath(pid uint32, task string) string

TaskStatusPath returns the path to the status file of a task pid in /proc

func TryToResolveTraceePid

func TryToResolveTraceePid(hostTracerPID uint32, tracerNSID uint64, NsTraceePid uint32) (uint32, error)

TryToResolveTraceePid tries to resolve and returnt the HOST tracee PID, given the HOST tracer PID and the namespaced tracee PID.

func UnixStat

func UnixStat(path string) (syscall.Stat_t, error)

UnixStat is an unix only equivalent to os.Stat, but alloc-free, and returning directly the platform-specific syscall.Stat_t structure.

func UnixStatModeToGoFileMode

func UnixStatModeToGoFileMode(mode uint32) fs.FileMode

UnixStatModeToGoFileMode converts a Unix mode to a Go fs.FileMode.

Types

type CIDRSet

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

CIDRSet defines a set of CIDRs

func (*CIDRSet) AppendCIDR

func (cs *CIDRSet) AppendCIDR(cidr string) error

AppendCIDR appends a CIDR to the set

func (*CIDRSet) Debug

func (cs *CIDRSet) Debug()

Debug prints on stdout the content of the CIDR set

func (*CIDRSet) MatchIP

func (cs *CIDRSet) MatchIP(ipstring string) bool

MatchIP returns true if the given IP match the CIDR set

type ControlGroup

type ControlGroup struct {
	// ID unique hierarchy ID
	ID int

	// Controllers are the list of cgroup controllers bound to the hierarchy
	Controllers []string

	// Path is the pathname of the control group to which the process
	// belongs. It is relative to the mountpoint of the hierarchy.
	Path string
}

ControlGroup describes the cgroup membership of a process

func GetProcControlGroup0

func GetProcControlGroup0(tgid, pid uint32) (ControlGroup, error)

GetProcControlGroup0 returns the cgroup membership with index 0 of the specified task.

func GetProcControlGroups

func GetProcControlGroups(tgid, pid uint32) ([]ControlGroup, error)

GetProcControlGroups returns the cgroup membership of the specified task.

func (ControlGroup) GetContainerContext

GetContainerContext returns both the container ID and its flags

func (ControlGroup) GetContainerID

func (cg ControlGroup) GetContainerID() containerutils.ContainerID

GetContainerID returns the container id extracted from the path of the control group

type EasyjsonTime

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

EasyjsonTime represents a EasyJSON enabled time wrapper

func NewEasyjsonTime

func NewEasyjsonTime(t time.Time) EasyjsonTime

NewEasyjsonTime returns a new EasyjsonTime based on the provided time

func NewEasyjsonTimeIfNotZero

func NewEasyjsonTimeIfNotZero(t time.Time) *EasyjsonTime

NewEasyjsonTimeIfNotZero returns a new EasyjsonTime based on the provided time or nil if zero time

func (*EasyjsonTime) GetInnerTime

func (t *EasyjsonTime) GetInnerTime() time.Time

GetInnerTime returns the inner time

func (EasyjsonTime) MarshalEasyJSON

func (t EasyjsonTime) MarshalEasyJSON(w *jwriter.Writer)

MarshalEasyJSON does JSON marshaling using easyjson interface

func (*EasyjsonTime) UnmarshalJSON

func (t *EasyjsonTime) UnmarshalJSON(b []byte) error

UnmarshalJSON does JSON unmarshaling

type Edge

type Edge struct {
	From  GraphID
	To    GraphID
	Color string
}

Edge describes an edge of a dot edge

type FilledProcess

type FilledProcess struct {
	Pid        int32
	Ppid       int32
	CreateTime int64
	Name       string
	Uids       []uint32
	Gids       []uint32
	MemInfo    *process.MemoryInfoStat
	Cmdline    []string
}

FilledProcess defines a filled process

func GetFilledProcess

func GetFilledProcess(p *process.Process) (*FilledProcess, error)

GetFilledProcess returns a FilledProcess from a Process input

type Graph

type Graph struct {
	Title string
	Nodes map[GraphID]*Node
	Edges []*Edge
}

Graph describes a dot graph

func (*Graph) EncodeDOT

func (g *Graph) EncodeDOT(tmpl string) (*bytes.Buffer, error)

EncodeDOT encodes an activity dump in the DOT format

type GraphID

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

GraphID represents an ID used in a graph, combination of NodeIDs

func NewGraphID

func NewGraphID(id NodeID) GraphID

NewGraphID returns a new GraphID based on the provided NodeIDs

func NewGraphIDWithDescription

func NewGraphIDWithDescription(description string, id NodeID) GraphID

NewGraphIDWithDescription returns a new GraphID based on a description and on the provided NodeIDs

func (*GraphID) Derive

func (id *GraphID) Derive(ids ...NodeID) GraphID

Derive a GraphID from a set of nodes

func (GraphID) String

func (id GraphID) String() string

type LRUStringInterner

type LRUStringInterner struct {
	sync.Mutex
	// contains filtered or unexported fields
}

LRUStringInterner is a best-effort LRU-based string deduplicator

func NewLRUStringInterner

func NewLRUStringInterner(size int) *LRUStringInterner

NewLRUStringInterner returns a new LRUStringInterner, with the cache size provided if the cache size is negative this function will panic

func (*LRUStringInterner) Deduplicate

func (si *LRUStringInterner) Deduplicate(value string) string

Deduplicate returns a possibly de-duplicated string

func (*LRUStringInterner) DeduplicateSlice

func (si *LRUStringInterner) DeduplicateSlice(values []string)

DeduplicateSlice returns a possibly de-duplicated string slice

type Limiter

type Limiter[K comparable] struct {
	// contains filtered or unexported fields
}

Limiter defines a rate limiter which limits tokens to 'numAllowedTokensPerPeriod' per 'period'

func NewLimiter

func NewLimiter[K comparable](maxUniqueToken int, numAllowedTokensPerPeriod int, period time.Duration) (*Limiter[K], error)

NewLimiter returns a rate limiter that is sized to the configured number of unique tokens, and each unique token is allowed 'numAllowedTokensPerPeriod' times per 'period'.

func (*Limiter[K]) Allow

func (l *Limiter[K]) Allow(k K) bool

Allow returns whether an entry is allowed or not

func (*Limiter[K]) Count

func (l *Limiter[K]) Count(k K)

Count marks the key as used and increments the count

func (*Limiter[K]) SwapStats

func (l *Limiter[K]) SwapStats() []LimiterStat

SwapStats returns the dropped and allowed stats, and zeros the stats

type LimiterStat

type LimiterStat struct {
	Dropped uint64
	Allowed uint64
	Tags    []string
}

LimiterStat return stats

type Listener

type Listener[O any] func(obj O)

Listener describes the callback called by a notifier

type NetNSPath

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

NetNSPath represents a network namespace path

func NetNSPathFromPath

func NetNSPathFromPath(path string) *NetNSPath

NetNSPathFromPath returns a new NetNSPath from the given path

func NetNSPathFromPid

func NetNSPathFromPid(pid uint32) *NetNSPath

NetNSPathFromPid returns a new NetNSPath from the given Pid

func (*NetNSPath) GetPath

func (path *NetNSPath) GetPath() string

GetPath returns the path for the given network namespace

func (*NetNSPath) GetProcessNetworkNamespace

func (path *NetNSPath) GetProcessNetworkNamespace() (uint32, error)

GetProcessNetworkNamespace returns the network namespace of a pid after parsing /proc/[pid]/ns/net

type Node

type Node struct {
	ID        GraphID
	Label     string
	Size      int
	Color     string
	FillColor string
	Shape     string
	IsTable   bool
}

Node describes an edge of a dot node

type NodeID

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

NodeID represents the ID of a Node

func NewNodeID

func NewNodeID(inner uint64) NodeID

NewNodeID returns a new node ID with the specified value

func NewNodeIDFromPtr

func NewNodeIDFromPtr[T any](v *T) NodeID

NewNodeIDFromPtr returns a new NodeID based on a pointer value

func NewRandomNodeID

func NewRandomNodeID() NodeID

NewRandomNodeID returns a new random NodeID

func (NodeID) IsUnset

func (id NodeID) IsUnset() bool

IsUnset checks if the NodeID is unset

type Notifier

type Notifier[E event, O any] struct {
	// contains filtered or unexported fields
}

Notifier describes a type that calls back listener that registered for a specific set of events

func NewNotifier

func NewNotifier[E event, O any]() *Notifier[E, O]

NewNotifier returns a new notifier

func (*Notifier[E, O]) NotifyListeners

func (n *Notifier[E, O]) NotifyListeners(event E, obj O)

NotifyListeners notifies all listeners of an event type

func (*Notifier[E, O]) RegisterListener

func (n *Notifier[E, O]) RegisterListener(event E, listener Listener[O]) error

RegisterListener registers an event listener

type PathPatternMatchOpts

type PathPatternMatchOpts struct {
	WildcardLimit      int // max number of wildcard in the pattern
	PrefixNodeRequired int // number of prefix nodes required
	SuffixNodeRequired int // number of suffix nodes required
	NodeSizeLimit      int // min size required to substitute with a wildcard
}

PathPatternMatchOpts PathPatternMatch options

type ProcFSModule

type ProcFSModule struct {
	// Name is the name of the module
	Name string
	// Size is the memory size of the module, in bytes
	Size int
	// InstancesCount lists how many instances of the module are currently loaded
	InstancesCount int
	// DependsOn lists the modules which the current module depends on
	DependsOn []string
	// State is the state which the current module is in
	State string
	// Address is the address at which the module was loaded
	Address int64
	// TaintState is the kernel taint state of the module
	TaintState string
}

ProcFSModule is a representation of a line in /proc/modules

type StringKeys

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

StringKeys is a map of strings, that serialize to JSON as an array of strings

func NewStringKeys

func NewStringKeys(from []string) *StringKeys

NewStringKeys returns a new `StringKeys` build from the provided keys

func (*StringKeys) ForEach

func (sk *StringKeys) ForEach(f func(string))

ForEach iterates over each key, and run `f` on them

func (*StringKeys) Insert

func (sk *StringKeys) Insert(value string)

Insert inserts a new key in the map

func (*StringKeys) Keys

func (sk *StringKeys) Keys() []string

Keys returns a slice of all the keys contained in this map

func (*StringKeys) MarshalEasyJSON

func (sk *StringKeys) MarshalEasyJSON(out *jwriter.Writer)

MarshalEasyJSON marshals the keys into JSON, using easyJSON

func (*StringKeys) MarshalJSON

func (sk *StringKeys) MarshalJSON() ([]byte, error)

MarshalJSON marshals the keys into JSON

type SyscallKey

type SyscallKey struct {
	Arch string
	ID   int
}

SyscallKey key representing the arch and syscall id

Jump to

Keyboard shortcuts

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