Skip to content

Commit

Permalink
[CWS] cut allocation in GetProcContainerContext
Browse files Browse the repository at this point in the history
  • Loading branch information
paulcacheux committed Dec 15, 2024
1 parent 6f5f2b0 commit 33a6c46
Showing 1 changed file with 40 additions and 4 deletions.
44 changes: 40 additions & 4 deletions pkg/security/utils/cgroup.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"bufio"
"bytes"
"crypto/sha256"
"fmt"
"os"
"strconv"
"strings"
Expand Down Expand Up @@ -49,6 +50,41 @@ func (cg ControlGroup) GetContainerID() containerutils.ContainerID {
return containerutils.ContainerID(id)
}

// GetFirstProcControlGroups returns the first cgroup membership of the specified task.
func GetFirstProcControlGroups(tgid, pid uint32) (ControlGroup, error) {
data, err := os.ReadFile(CgroupTaskPath(tgid, pid))
if err != nil {
return ControlGroup{}, err
}

index := bytes.IndexByte(data, '\n')
if index < 0 {
index = len(data)
}
firstLine := string(data[:index])

idstr, rest, ok := strings.Cut(firstLine, ":")
if !ok {
return ControlGroup{}, fmt.Errorf("invalid cgroup line: %s", firstLine)
}

id, err := strconv.Atoi(idstr)
if err != nil {
return ControlGroup{}, err
}

controllers, path, ok := strings.Cut(rest, ":")
if !ok {
return ControlGroup{}, fmt.Errorf("invalid cgroup line: %s", firstLine)
}

return ControlGroup{
ID: id,
Controllers: strings.Split(controllers, ","),
Path: path,
}, nil
}

// GetProcControlGroups returns the cgroup membership of the specified task.
func GetProcControlGroups(tgid, pid uint32) ([]ControlGroup, error) {
data, err := os.ReadFile(CgroupTaskPath(tgid, pid))
Expand Down Expand Up @@ -85,14 +121,14 @@ func GetProcContainerID(tgid, pid uint32) (containerutils.ContainerID, 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 GetProcContainerContext(tgid, pid uint32) (containerutils.ContainerID, model.CGroupContext, error) {
cgroups, err := GetProcControlGroups(tgid, pid)
if err != nil || len(cgroups) == 0 {
cgroup, err := GetFirstProcControlGroups(tgid, pid)
if err != nil {
return "", model.CGroupContext{}, err
}

containerID, runtime := cgroups[0].GetContainerContext()
containerID, runtime := cgroup.GetContainerContext()
cgroupContext := model.CGroupContext{
CGroupID: containerutils.CGroupID(cgroups[0].Path),
CGroupID: containerutils.CGroupID(cgroup.Path),
CGroupFlags: runtime,
}

Expand Down

0 comments on commit 33a6c46

Please sign in to comment.