2018-04-02 05:25:32 +02:00
|
|
|
package procmon
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/evilsocket/opensnitch/daemon/core"
|
|
|
|
)
|
|
|
|
|
2018-04-16 19:12:46 +02:00
|
|
|
func GetPIDFromINode(inode int) int {
|
|
|
|
expect := fmt.Sprintf("socket:[%d]", inode)
|
2018-04-17 18:08:03 +02:00
|
|
|
found := -1
|
|
|
|
|
|
|
|
forEachProcess(func(pid int, path string, args []string) bool {
|
2018-04-16 19:12:46 +02:00
|
|
|
// for every descriptor
|
2018-04-17 18:08:03 +02:00
|
|
|
fdPath := fmt.Sprintf("/proc/%d/fd/", pid)
|
|
|
|
if descriptors, err := ioutil.ReadDir(fdPath); err == nil {
|
2018-04-16 19:12:46 +02:00
|
|
|
for _, desc := range descriptors {
|
2018-04-17 18:08:03 +02:00
|
|
|
descLink := fmt.Sprintf("%s%s", fdPath, desc.Name())
|
2018-04-16 19:12:46 +02:00
|
|
|
// resolve the symlink and compare to what we expect
|
|
|
|
if link, err := os.Readlink(descLink); err == nil && link == expect {
|
2018-04-17 18:08:03 +02:00
|
|
|
found = pid
|
|
|
|
return true
|
2018-04-16 19:12:46 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2018-04-17 18:08:03 +02:00
|
|
|
// keep looping
|
|
|
|
return false
|
|
|
|
})
|
|
|
|
|
|
|
|
return found
|
2018-04-16 19:12:46 +02:00
|
|
|
}
|
|
|
|
|
2018-04-15 15:39:43 +02:00
|
|
|
func parseCmdLine(proc *Process) {
|
|
|
|
if data, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/cmdline", proc.ID)); err == nil {
|
|
|
|
for i, b := range data {
|
|
|
|
if b == 0x00 {
|
|
|
|
data[i] = byte(' ')
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
args := strings.Split(string(data), " ")
|
|
|
|
for _, arg := range args {
|
|
|
|
arg = core.Trim(arg)
|
|
|
|
if arg != "" {
|
|
|
|
proc.Args = append(proc.Args, arg)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func parseEnv(proc *Process) {
|
|
|
|
if data, err := ioutil.ReadFile(fmt.Sprintf("/proc/%d/environ", proc.ID)); err == nil {
|
|
|
|
for _, s := range strings.Split(string(data), "\x00") {
|
|
|
|
parts := strings.SplitN(core.Trim(s), "=", 2)
|
2018-04-15 15:40:40 +02:00
|
|
|
if parts != nil && len(parts) == 2 {
|
2018-04-15 15:39:43 +02:00
|
|
|
key := core.Trim(parts[0])
|
|
|
|
val := core.Trim(parts[1])
|
|
|
|
proc.Env[key] = val
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-02 05:25:32 +02:00
|
|
|
func FindProcess(pid int) *Process {
|
|
|
|
linkName := fmt.Sprintf("/proc/%d/exe", pid)
|
|
|
|
if core.Exists(linkName) == false {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if link, err := os.Readlink(linkName); err == nil && core.Exists(link) == true {
|
|
|
|
proc := NewProcess(pid, link)
|
|
|
|
|
2018-04-15 15:39:43 +02:00
|
|
|
parseCmdLine(proc)
|
|
|
|
parseEnv(proc)
|
2018-04-02 05:25:32 +02:00
|
|
|
|
|
|
|
return proc
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|