Skip to content

Commit

Permalink
Fix capture exec for containers
Browse files Browse the repository at this point in the history
  • Loading branch information
yanivagman committed Aug 5, 2020
1 parent 425ecb7 commit 7d9c8d1
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions tracee/tracee.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ type Tracee struct {
printer eventPrinter
stats statsStore
capturedFiles map[string]int64
mntNsFirstPid map[uint32]uint32
}

type counter int32
Expand Down Expand Up @@ -186,6 +187,17 @@ func New(cfg TraceeConfig) (*Tracee, error) {
}

t.capturedFiles = make(map[string]int64)
t.mntNsFirstPid = make(map[uint32]uint32)
// Save host mount namespace init pid (1)
mnt_ns_link, err := os.Readlink("/proc/1/ns/mnt")
if err == nil {
mnt_ns_str := strings.TrimPrefix(mnt_ns_link, "mnt:[")
mnt_ns_str = strings.TrimSuffix(mnt_ns_str, "]")
mnt_ns, err := strconv.Atoi(mnt_ns_str)
if err == nil {
t.mntNsFirstPid[uint32(mnt_ns)] = 1
}
}
return t, nil
}

Expand Down Expand Up @@ -437,24 +449,34 @@ func (t *Tracee) processEvent(ctx *context, args map[argTag]interface{}) error {
if sourceFilePath[0] != '/' {
return nil
}
sourceFileStat, err := os.Stat(sourceFilePath)
if ctx.Pid == 1 {
t.mntNsFirstPid[ctx.MntID] = ctx.HostPid
}
pid := ctx.HostPid
if firstPid, ok := t.mntNsFirstPid[ctx.MntID]; ok {
pid = firstPid
}
procSourceFilePath := filepath.Join(fmt.Sprintf("/proc/%s/root", strconv.Itoa(int(pid))), sourceFilePath)
sourceFileStat, err := os.Stat(procSourceFilePath)
if err != nil {
return err
}
sourceCtime := sourceFileStat.Sys().(*syscall.Stat_t).Ctim.Nano()
lastCtime, ok := t.capturedFiles[sourceFilePath]
// Add mnt ns to path to uniquely identify it
uniqueSourceFilePath := filepath.Join(strconv.Itoa(int(ctx.MntID)), sourceFilePath)
lastCtime, ok := t.capturedFiles[uniqueSourceFilePath]
if ok && lastCtime == sourceCtime {
return nil
}
t.capturedFiles[sourceFilePath] = sourceCtime
t.capturedFiles[uniqueSourceFilePath] = sourceCtime

destinationDirPath := filepath.Join(t.config.OutputPath, strconv.Itoa(int(ctx.MntID)))
if err := os.MkdirAll(destinationDirPath, 0755); err != nil {
return err
}
destinationFilePath := filepath.Join(destinationDirPath, fmt.Sprintf("exec.%d.%s", ctx.Ts, filepath.Base(sourceFilePath)))

err = copyFileByPath(sourceFilePath, destinationFilePath)
err = copyFileByPath(procSourceFilePath, destinationFilePath)
if err != nil {
return err
}
Expand Down

0 comments on commit 7d9c8d1

Please sign in to comment.