#依赖包
github.com/fearful-symmetry/garlic
#原理
netlink_connector
package main
import (
"bufio"
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"os"
"strings"
"github.com/fearful-symmetry/garlic"
)
type Exec struct {
Procname string `json:"procname"`
Procpath string `json:"procpath"`
Pid uint32 `json:"pid"`
Cmdline string `json:"cmdline"`
Md5hash string `json:"md5_hash"`
}
func filemd5(filePath string) string {
file, _ := os.Open(filePath)
defer file.Close()
h := md5.New()
io.Copy(h, file)
md := h.Sum(nil)
mdString := hex.EncodeToString(md)
return mdString
}
func getProcMd5(filepath string) string {
r := filepath
f, err := os.Open(r)
if err != nil {
log.Println(err)
}
defer f.Close()
reader := bufio.NewReader(f)
execpath, _, _ := reader.ReadLine()
md5string := filemd5(string(execpath))
return md5string
}
func getProcpath(pid uint32) string {
path := fmt.Sprintf("/proc/%d/exe", pid)
r ,err := os.Readlink(strings.TrimSpace(path))
if err !=nil{
log.Fatalln("Procpath err")
}
return strings.TrimSpace(r)
}
func getProcName(pid uint32) string {
path := fmt.Sprintf("/proc/%d/comm", pid)
f, err := os.Open(path)
if err != nil {
log.Println(err)
}
defer f.Close()
reader := bufio.NewReader(f)
cmdtext, _, _ := reader.ReadLine()
return strings.TrimSpace(string(cmdtext))
}
func getCmdLine(pid uint32) string {
path := fmt.Sprintf("/proc/%d/cmdline", pid)
f, err := os.Open(path)
if err != nil {
log.Println(err)
}
defer f.Close()
reader := bufio.NewReader(f)
cmdtext, _, _ := reader.ReadLine()
return strings.Replace(string(cmdtext), "\u0000", " ", -1)
}
func main() {
cn, err := garlic.DialPCNWithEvents([]garlic.EventType{garlic.ProcEventExec})
if err != nil {
fmt.Printf("%s", err)
}
//Read in events
for {
data, err := cn.ReadPCN()
if err != nil {
fmt.Printf("Read fail: %s", err)
}
execdata := data[0].EventData
pid := execdata.Pid()
procname := getProcName(pid)
procpath := getProcpath(pid)
cmdline := getCmdLine(pid)
md5hash := getProcMd5(procpath)
evtstr := Exec{
Procname:procname,
Pid:pid,
Procpath:procname,
Cmdline:cmdline,
Md5hash:md5hash,
}
jsonEvt, err := json.Marshal(evtstr)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(jsonEvt))
}
}