forked from johnjohnsp1/capsule8
/
process.go
256 lines (222 loc) · 6.96 KB
/
process.go
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
// Copyright 2017 Capsule8, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package sensor
import (
"fmt"
"strings"
"syscall"
api "github.com/capsule8/capsule8/api/v0"
"github.com/capsule8/capsule8/pkg/expression"
"github.com/capsule8/capsule8/pkg/sys"
"github.com/capsule8/capsule8/pkg/sys/perf"
"github.com/golang/glog"
"golang.org/x/sys/unix"
)
const (
exitSymbol = "do_exit"
exitFetchargs = "code=%di:s64"
)
type processFilter struct {
sensor *Sensor
}
func (f *processFilter) decodeSchedProcessFork(sample *perf.SampleRecord, data perf.TraceEventSampleData) (interface{}, error) {
childPid := data["child_pid"].(int32)
ev := f.sensor.NewEventFromSample(sample, data)
ev.Event = &api.Event_Process{
Process: &api.ProcessEvent{
Type: api.ProcessEventType_PROCESS_EVENT_TYPE_FORK,
ForkChildPid: childPid,
},
}
childID, ok := f.sensor.processCache.ProcessID(int(childPid))
if ok {
ev.GetProcess().ForkChildId = childID
}
return ev, nil
}
func (f *processFilter) decodeSchedProcessExec(sample *perf.SampleRecord, data perf.TraceEventSampleData) (interface{}, error) {
hostPid := data["common_pid"].(int32)
filename := data["filename"].(string)
// Get the command-line from the process info cache. If it's not there
// for whatever reason, fallback to using procfs
commandLine, _ := f.sensor.processCache.ProcessCommandLine(int(hostPid))
if commandLine == nil || len(commandLine) == 0 {
commandLine = sys.HostProcFS().CommandLine(int(hostPid))
}
ev := f.sensor.NewEventFromSample(sample, data)
processEvent := &api.ProcessEvent{
Type: api.ProcessEventType_PROCESS_EVENT_TYPE_EXEC,
ExecFilename: filename,
ExecCommandLine: commandLine,
}
ev.Event = &api.Event_Process{
Process: processEvent,
}
return ev, nil
}
func (f *processFilter) decodeDoExit(sample *perf.SampleRecord, data perf.TraceEventSampleData) (interface{}, error) {
var exitStatus int
var exitSignal syscall.Signal
var coreDumped bool
// The kprobe fetches the argument 'long code' as an s64. It's
// the same value returned as a status via waitpid(2).
code := data["code"].(int64)
ws := unix.WaitStatus(code)
if ws.Exited() {
exitStatus = ws.ExitStatus()
} else if ws.Signaled() {
exitSignal = ws.Signal()
coreDumped = ws.CoreDump()
}
ev := f.sensor.NewEventFromSample(sample, data)
ev.Event = &api.Event_Process{
Process: &api.ProcessEvent{
Type: api.ProcessEventType_PROCESS_EVENT_TYPE_EXIT,
ExitCode: int32(code),
ExitStatus: uint32(exitStatus),
ExitSignal: uint32(exitSignal),
ExitCoreDumped: coreDumped,
},
}
return ev, nil
}
func processFilterString(wildcard bool, filters map[string]bool) string {
if wildcard {
return ""
}
parts := make([]string, 0, len(filters))
for k := range filters {
parts = append(parts, fmt.Sprintf("(%s)", k))
}
return strings.Join(parts, " || ")
}
func rewriteProcessEventFilter(pef *api.ProcessEventFilter) {
switch pef.Type {
case api.ProcessEventType_PROCESS_EVENT_TYPE_EXEC:
if pef.ExecFilename != nil {
newExpr := expression.Equal(
expression.Identifier("filename"),
expression.Value(pef.ExecFilename.Value))
pef.FilterExpression = expression.LogicalAnd(
newExpr, pef.FilterExpression)
pef.ExecFilename = nil
pef.ExecFilenamePattern = nil
} else if pef.ExecFilenamePattern != nil {
newExpr := expression.Like(
expression.Identifier("filename"),
expression.Value(pef.ExecFilenamePattern.Value))
pef.FilterExpression = expression.LogicalAnd(
newExpr, pef.FilterExpression)
pef.ExecFilenamePattern = nil
}
case api.ProcessEventType_PROCESS_EVENT_TYPE_EXIT:
if pef.ExitCode != nil {
newExpr := expression.Equal(
expression.Identifier("code"),
expression.Value(pef.ExitCode.Value))
pef.FilterExpression = expression.LogicalAnd(
newExpr, pef.FilterExpression)
pef.ExitCode = nil
}
}
}
func registerProcessEvents(sensor *Sensor, eventMap subscriptionMap, events []*api.ProcessEventFilter) {
forkFilter := false
execFilters := make(map[string]bool)
execWildcard := false
exitFilters := make(map[string]bool)
exitWildcard := false
for _, pef := range events {
// Translate deprecated fields into an expression
rewriteProcessEventFilter(pef)
switch pef.Type {
case api.ProcessEventType_PROCESS_EVENT_TYPE_FORK:
forkFilter = true
case api.ProcessEventType_PROCESS_EVENT_TYPE_EXEC:
if pef.FilterExpression == nil {
execWildcard = true
} else {
expr, err := expression.NewExpression(pef.FilterExpression)
if err != nil {
glog.V(1).Infof("Invalid process event filter: %s", err)
continue
}
err = expr.ValidateKernelFilter()
if err != nil {
glog.V(1).Infof("Invalid process event filter as kernel filter: %s", err)
continue
}
s := expr.KernelFilterString()
execFilters[s] = true
}
case api.ProcessEventType_PROCESS_EVENT_TYPE_EXIT:
if pef.FilterExpression == nil {
exitWildcard = true
} else {
expr, err := expression.NewExpression(pef.FilterExpression)
if err != nil {
glog.V(1).Infof("Invalid process event filter: %s", err)
continue
}
err = expr.ValidateKernelFilter()
if err != nil {
glog.V(1).Infof("Invalid process event filter as kernel filter: %s", err)
continue
}
s := expr.KernelFilterString()
exitFilters[s] = true
}
default:
continue
}
}
f := processFilter{
sensor: sensor,
}
if forkFilter {
eventName := "sched/sched_process_fork"
eventID, err := sensor.monitor.RegisterTracepoint(eventName,
f.decodeSchedProcessFork)
if err != nil {
glog.V(1).Infof("Couldn't get %s event id: %v",
eventName, err)
} else {
eventMap[eventID] = &subscription{}
}
}
if execWildcard || len(execFilters) > 0 {
filterString := processFilterString(execWildcard, execFilters)
eventName := "sched/sched_process_exec"
eventID, err := sensor.monitor.RegisterTracepoint(eventName,
f.decodeSchedProcessExec, perf.WithFilter(filterString))
if err != nil {
glog.V(1).Infof("Couldn't get %s event id: %v",
eventName, err)
} else {
eventMap[eventID] = &subscription{}
}
}
if exitWildcard || len(exitFilters) > 0 {
filterString := processFilterString(exitWildcard, exitFilters)
eventID, err := sensor.monitor.RegisterKprobe(exitSymbol,
false, exitFetchargs, f.decodeDoExit,
perf.WithFilter(filterString))
if err != nil {
glog.Errorf("Couldn't register kprobe for %s: %s",
exitSymbol, err)
} else {
eventMap[eventID] = &subscription{}
}
}
}