Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions pkg/metrics/eventmetrics/eventmetrics_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,11 @@ func TestHandleProcessedEvent(t *testing.T) {
}},
})

// invalid UTF-8
handleProcessedEvent(nil, &tetragon.GetEventsResponse{Event: &tetragon.GetEventsResponse_ProcessKprobe{ProcessKprobe: &tetragon.ProcessKprobe{
Process: &tetragon.Process{Binary: "binary_\xb5"},
}}})

expected := strings.NewReader(`# HELP tetragon_events_total The total number of Tetragon events
# TYPE tetragon_events_total counter
tetragon_events_total{binary="",event_type="PROCESS_KPROBE",namespace="",node_name="",pod="",workload=""} 1
Expand All @@ -90,6 +95,7 @@ tetragon_events_total{binary="binary_c",event_type="PROCESS_TRACEPOINT",namespac
tetragon_events_total{binary="binary_e",event_type="PROCESS_EXIT",namespace="",node_name="",pod="",workload=""} 1
tetragon_events_total{binary="binary_e",event_type="PROCESS_EXIT",namespace="namespace_e",node_name="",pod="pod_e",workload="workload_e"} 1
tetragon_events_total{binary="binary_f",event_type="PROCESS_KPROBE",namespace="",node_name="node_a",pod="",workload=""} 1
tetragon_events_total{binary="binary_�",event_type="PROCESS_KPROBE",namespace="",node_name="",pod="",workload=""} 1
`)
require.NoError(t, testutil.CollectAndCompare(EventsProcessed, expected))
}
Expand Down
9 changes: 8 additions & 1 deletion pkg/metrics/filteredlabels.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package metrics

import (
"github.com/cilium/tetragon/pkg/metrics/consts"
"github.com/cilium/tetragon/pkg/strutils"
)

type FilteredLabels interface {
Expand Down Expand Up @@ -46,8 +47,14 @@ func (l ProcessLabels) Keys() []string {
return []string{"namespace", "workload", "pod", "binary", "node_name"}
}

// Values replaces invalid UTF-8 with U+FFFD: the prometheus client panics on
// such label values, and a binary path can hold any bytes.
func (l ProcessLabels) Values() []string {
return []string{l.Namespace, l.Workload, l.Pod, l.Binary, l.NodeName}
values := []string{l.Namespace, l.Workload, l.Pod, l.Binary, l.NodeName}
for i, v := range values {
values[i] = strutils.ToValidUTF8(v)
}
return values
}

func (l ProcessLabels) Example() FilteredLabels {
Expand Down
15 changes: 1 addition & 14 deletions pkg/sensors/exec/procevents/proc_reader.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"fmt"
"sort"
"strings"
"unicode/utf8"

"github.com/cilium/tetragon/pkg/api"
"github.com/cilium/tetragon/pkg/api/ops"
Expand All @@ -28,18 +27,6 @@ const (
kernelPid = uint32(0)
)

func stringToUTF8(s []byte) []byte {
var utf8Cursor int
var i int

for i < len(s) {
r, size := utf8.DecodeRune(s[i:])
utf8Cursor += utf8.EncodeRune(s[utf8Cursor:], r)
i += size
}
return s
}

type procs struct {
ppid uint32
pnspid uint32
Expand Down Expand Up @@ -72,7 +59,7 @@ type procs struct {
}

func procFilename(p *procs) string {
filename := string(p.exe)
filename := strutils.UTF8FromBPFBytes(p.exe)

// If this is a kernel thread, we use its filename as process name
// similarly to what ps reports.
Expand Down
7 changes: 4 additions & 3 deletions pkg/sensors/exec/procevents/proc_reader_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/cilium/tetragon/pkg/sensors"
"github.com/cilium/tetragon/pkg/sensors/base"
"github.com/cilium/tetragon/pkg/sensors/exec/execvemap"
"github.com/cilium/tetragon/pkg/strutils"
)

const (
Expand Down Expand Up @@ -71,7 +72,7 @@ func getCWD(pid uint32) (string, uint32) {
return "", flags
}

return cwd, flags
return strutils.UTF8FromBPFBytes([]byte(cwd)), flags
}

func updateExecveMapStats(procs int64) {
Expand Down Expand Up @@ -328,8 +329,8 @@ func listRunningProcs(procPath string) ([]procs, error) {
pid: uint32(pid),
tid: uint32(pid), // Read dir does not return threads and we only track tgid
nspid: nspid,
exe: stringToUTF8([]byte(execPath)),
cmdline: stringToUTF8(cmdline),
exe: []byte(execPath),
cmdline: cmdline,
flags: api.EventProcFS | api.EventNeedsCWD,
ktime: ktime,
permitted: permitted,
Expand Down
43 changes: 43 additions & 0 deletions pkg/sensors/exec/procevents/proc_reader_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
package procevents

import (
"os"
"os/exec"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
Expand All @@ -17,6 +20,7 @@ import (

"github.com/cilium/tetragon/pkg/api"
"github.com/cilium/tetragon/pkg/observer/observertesthelper/docker"
"github.com/cilium/tetragon/pkg/strutils"
)

func TestListRunningProcs(t *testing.T) {
Expand All @@ -31,6 +35,45 @@ func TestListRunningProcs(t *testing.T) {
}
}

// TestListRunningProcsInvalidUTF8 checks that the /proc walk copes with a
// process whose exe path, argv and cwd are not valid UTF-8: the raw bytes are
// kept for the BPF maps and the strings used in events are valid UTF-8.
func TestListRunningProcsInvalidUTF8(t *testing.T) {
dir := filepath.Join(t.TempDir(), "d\xb5ir")
require.NoError(t, os.Mkdir(dir, 0o755))
// A copy of sh: coreutils can be a multi-call binary that refuses to
// run under another name.
exe := filepath.Join(dir, "s\xb5h")
data, err := os.ReadFile("/bin/sh")
require.NoError(t, err)
require.NoError(t, os.WriteFile(exe, data, 0o755))

// read blocks on the open stdin pipe until the process is killed.
cmd := exec.Command(exe, "-c", "read x", "a\xb5rg")
cmd.Dir = dir
_, err = cmd.StdinPipe()
require.NoError(t, err)
require.NoError(t, cmd.Start())
t.Cleanup(func() {
cmd.Process.Kill()
cmd.Wait()
})
pid := uint32(cmd.Process.Pid)

ps, err := listRunningProcs("/proc")
require.NoError(t, err)
idx := slices.IndexFunc(ps, func(p procs) bool { return p.pid == pid })
require.NotEqual(t, -1, idx, "pid %d not found", pid)
p := ps[idx]

require.Equal(t, []byte(exe), p.exe)
require.Equal(t, []byte(exe+"\x00-c\x00read x\x00a\xb5rg\x00"), p.cmdline)
require.Equal(t, strutils.UTF8FromBPFBytes([]byte(exe)), procFilename(&p))
require.Equal(t, `-c "read x" a�rg`, procArgs(&p))
cwd, _ := getCWD(pid)
require.Equal(t, strutils.UTF8FromBPFBytes([]byte(dir)), cwd)
}

func TestProcToKeyValueArgsExcludeArgv0(t *testing.T) {
p := procs{
exe: []byte("/usr/bin/curl"),
Expand Down
8 changes: 4 additions & 4 deletions pkg/sensors/exec/procevents/proc_reader_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,8 @@ var (
pid: 4,
tid: 4,
nspid: 0,
exe: stringToUTF8([]byte("system")),
cmdline: stringToUTF8([]byte("system")),
exe: []byte("system"),
cmdline: []byte("system"),
flags: api.EventProcFS | api.EventNeedsCWD,
ktime: bootTimeEpoch,
kernelThread: true,
Expand Down Expand Up @@ -580,8 +580,8 @@ func NewProcess(procEntry windows.ProcessEntry32) (procs, error) {
pid: uint32(pid),
tid: uint32(pid), // Read dir does not return threads and we only track tgid
nspid: nsPID,
exe: stringToUTF8([]byte(execPath)),
cmdline: stringToUTF8([]byte(cmdline)),
exe: []byte(execPath),
cmdline: []byte(cmdline),
flags: api.EventProcFS | api.EventNeedsCWD,
ktime: ktime,
permitted: permitted,
Expand Down
10 changes: 10 additions & 0 deletions pkg/strutils/strutls.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,16 @@ func UTF8FromBPFBytes(b []byte) string {
return strings.ToValidUTF8(string(b), replacementChar)
}

// ToValidUTF8 is UTF8FromBPFBytes for strings.
func ToValidUTF8(s string) string {
// fast path
if utf8.ValidString(s) {
return s
}

return strings.ToValidUTF8(s, replacementChar)
}

func WriteUTF8FromBPFBytes(b *strings.Builder, data []byte) {
if utf8.Valid(data) {
// fast path, does not materialise a temp string
Expand Down
Loading