aboutsummaryrefslogtreecommitdiffstats
path: root/listener/godo.go
blob: 4f09b678b81a1c13d657e8eb88bc83b35d1d0bcd (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package main

import (
	"bufio"
	"flag"
	"fmt"
	"log"
	"netlink"
	"os"
	"os/exec"
	"regexp"
	"strings"
	"syscall"
	"time"

	"github.com/elastic/go-libaudit/v2"
)

var (
	fs          = flag.NewFlagSet("audit", flag.ExitOnError)
	diag        = fs.String("diag", "godo.log", "dump raw information from kernel to file")
	rate        = fs.Uint("rate", 0, "rate limit in kernel (default 0, no rate limit)")
	backlog     = fs.Uint("backlog", 1<<30, "backlog limit")
	immutable   = fs.Bool("immutable", false, "make kernel audit settings immutable (requires reboot to undo)")
	receiveOnly = fs.Bool("ro", false, "receive only using multicast, requires kernel 3.16+")
	mongoURI    = fs.String("mongo", "localhost:27017", "mongo database uri")
)

const bufferPages = 1000

func main() {
	// 检查用户身份,并添加auditd规则,监听所有syscall
	if os.Geteuid() != 0 {
		fmt.Fprintf(os.Stderr, "Err: Please run me as root, %d!\n", os.Getegid())
		return
	}

	// 所有的系统调用号与名称的关系
	err := figureOutSyscalls()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error figuring out syscall numbers: %v\n", err)
	}

	exec.Command("auditctl", "-D").Run()
	exec.Command("auditctl", "--reset-lost").Run()

	var auditCmd *exec.Cmd

	pidSyscall := []string{"execve", "pivot_root"}
	// 设置监听规则
	for i := 0; i < len(pidSyscall); i++ {
		auditCmd = exec.Command("auditctl", "-a", "exit,always", "-F", "arch=b64", "-S", pidSyscall[i])
		auditCmd.Run()
	}

	// 监听文件的消息
	fileSyscall := []string{"open", "close", "write"}
	// fileSyscall := []string{"open", "write", "creat", "unlink", "opendir", "mkdir", "rmdir", "chmod", "fchmod", "chown", "fchown", "lchown", "flock"}
	for i := 0; i < len(fileSyscall); i++ {
		auditCmd = exec.Command("auditctl", "-a", "exit,always", "-F", "arch=b64", "-S", fileSyscall[i])
		auditCmd.Run()
	}

	// 查找pid
	containerdPid, err = getPid()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error finding containerd: %v\n", err)
		return
	}

	// 开始运行,解析命令行参数后监听
	if err := fs.Parse(os.Args[1:]); err != nil {
		log.Fatal(err)
	}

	if err := read(); err != nil {
		log.Fatalf("error: %v", err)
	}
}

func coroutine(client *libaudit.AuditClient) error {
	// 各协程至此开始
	bufferSize := bufferPages * syscall.Getpagesize()
	rawChan = make(chan interface{}, bufferSize)
	cookedChan = make(chan Event, bufferSize)

	var err error
	if err = pidCol.init(dbName, pidColName); err != nil {
		fmt.Fprintf(os.Stderr, "Error while initing the mongodb: %v\n", err)
		return err
	}
	if err = initPidCol(); err != nil {
		fmt.Fprintf(os.Stderr, "Err while initing pidcol: %v\n", err)
	}

	if err = fdCol.init(dbName, fdColName); err != nil {
		fmt.Fprintf(os.Stderr, "Error while initing the mongodb: %v\n", err)
		return err
	}
	if err = fileCol.init(dbName, fileColName); err != nil {
		fmt.Fprintf(os.Stderr, "Error while initing the mongodb: %v\n", err)
	}

	defer pidCol.Disconnect()
	defer fdCol.Disconnect()
	defer fileCol.Disconnect()

	wg.Add(1)
	go deal()
	wg.Add(1)
	go receive(client)
	wg.Add(1)
	go orgnaze()
	wg.Add(1)
	go procWatch()

	wg.Wait()
	time.Sleep(2 * time.Second)
	return nil
}

func procWatch() error {
	ns, err := netlink.NewNetlinkSocket(syscall.NETLINK_CONNECTOR, 12345)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error creating socket: %v\n", err)
		return err
	}
	defer ns.Close()
	for {
		res, err := ns.Receive(bufferPages)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error recv: %v\n", err)
			continue
		}
		for i := 0; i < len(res); i++ {
			procEvent := netlink.ParseProcEvent(res[i].Data)
			switch procEvent.What {
			case netlink.PROC_EVENT_FORK:
				data := procEvent.Data.(netlink.ProcEventFork)
				cooked := Event{
					tag:        NEWPID,
					timestamp:  time.Now(),
					pid:        int(data.ChildPid),
					tgid:       int(data.ChildTgid),
					ppid:       int(data.ParentPid),
					parentTgid: int(data.ParentTgid),
				}
				checkProc(&cooked)
				cookedChan <- cooked
			case netlink.PROC_EVENT_EXIT:
				data := procEvent.Data.(netlink.ProcEventExit)
				cooked := Event{
					tag:         PIDEXIT,
					timestamp:   time.Now(),
					pid:         int(data.ProcessPid),
					exit_code:   int(data.ExitCode),
					exit_signal: int(data.ExitSignal),
				}
				cookedChan <- cooked
			default:
			}
		}
	}
}

func checkProc(pCooked *Event) {
	fileName := fmt.Sprintf("/proc/%d/task/%d/", pCooked.tgid, pCooked.pid)
	fd, err := os.Open(fileName + "cmdline")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Err: %v\n", err)
		return
	}

	scanner := bufio.NewScanner(fd)
	scanner.Split(bufio.ScanLines)
	for scanner.Scan() {
		line := scanner.Text()
		pCooked.argv = append(pCooked.argv, strings.Split(line, "\x00")...)
	}
	pCooked.argc = len(pCooked.argv)
	fd.Close()

	fd, err = os.Open(fileName + "comm")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Err: %v\n", err)
		return
	}
	scanner = bufio.NewScanner(fd)
	scanner.Split(bufio.ScanLines)
	for scanner.Scan() {
		line := scanner.Text()
		pCooked.comm = line
	}
	fd.Close()

	pCooked.cwd, err = os.Readlink(fileName + "cwd")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Err: %v\n", err)
		pCooked.cwd = ""
	}

	fd, err = os.Open(fileName + "cgroup")
	if err != nil {
		fmt.Fprintf(os.Stderr, "Err: %v\n", err)
		// cgroup记空,即没赶上
		return
	}
	scanner = bufio.NewScanner(fd)
	cgroupRegex := regexp.MustCompile(`/docker/([0-9a-f]+)$`)
	scanner.Split(bufio.ScanLines)
	for scanner.Scan() {
		line := scanner.Text()
		if cgroupRegex.MatchString(line) {
			match := cgroupRegex.FindStringSubmatch(line)
			pCooked.cgroup = match[1]
			return
		}
	}
	fd.Close()
	pCooked.cgroup = ""
}