-
Notifications
You must be signed in to change notification settings - Fork 8
/
main.go
308 lines (262 loc) · 7.14 KB
/
main.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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
// Copyright 2019 Peter Stöckli
//
// 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.
//go:build linux
// +build linux
package main
import (
"bytes"
"encoding/binary"
"errors"
"flag"
"log"
"net"
"os"
"os/signal"
"os/user"
"strconv"
"syscall"
"time"
"github.com/cilium/ebpf/link"
"github.com/cilium/ebpf/perf"
"github.com/cilium/ebpf/rlimit"
"github.com/p-/socket-connect-bpf/as"
"github.com/p-/socket-connect-bpf/conv"
"github.com/p-/socket-connect-bpf/linux"
"golang.org/x/sys/unix"
)
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc clang-16 -cflags "-O2 -g -Wall -Werror" -target amd64,arm64 bpf securitySocketConnectSrc.c -- -Iheaders/
var out output
func main() {
setupOutput()
setupWorkers()
}
func setupOutput() {
printAll := flag.Bool("a", false, "print all (AS numbers and process arguments in output")
flag.Parse()
if *printAll {
as.ParseASNumbersIPv4("./as/ip2asn-v4-u32.tsv")
as.ParseASNumbersIPv6("./as/ip2asn-v6.tsv")
}
out = newOutput(*printAll)
}
func setupWorkers() {
fn := "security_socket_connect"
stopper := make(chan os.Signal, 1)
signal.Notify(stopper, os.Interrupt, syscall.SIGTERM)
// Allow the current process to lock memory for eBPF resources.
if err := rlimit.RemoveMemlock(); err != nil {
log.Fatal(err)
}
// Load pre-compiled programs and maps into the kernel.
objs := bpfObjects{}
if err := loadBpfObjects(&objs, nil); err != nil {
log.Fatalf("loading objects: %v", err)
}
defer objs.Close()
kp, err := link.Kprobe(fn, objs.KprobeSecuritySocketConnect, nil)
if err != nil {
log.Fatalf("opening kprobe: %s", err)
}
defer kp.Close()
rd4, err := perf.NewReader(objs.Ipv4Events, os.Getpagesize())
if err != nil {
log.Fatalf("creating perf event reader: %s", err)
}
defer rd4.Close()
rd6, err := perf.NewReader(objs.Ipv6Events, os.Getpagesize())
if err != nil {
log.Fatalf("creating perf event reader: %s", err)
}
defer rd6.Close()
rdOther, err := perf.NewReader(objs.OtherSocketEvents, os.Getpagesize())
if err != nil {
log.Fatalf("creating perf event reader: %s", err)
}
defer rdOther.Close()
go func() {
<-stopper
log.Println("Received signal, exiting program..")
if err := rd4.Close(); err != nil {
log.Fatalf("closing perf event reader: %s", err)
}
if err := rd6.Close(); err != nil {
log.Fatalf("closing perf event reader: %s", err)
}
if err := rdOther.Close(); err != nil {
log.Fatalf("closing perf event reader: %s", err)
}
}()
out.PrintHeader()
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, os.Kill)
go (func() {
for {
if !readIP4Events(rd4) {
return
}
}
})()
go (func() {
for {
if !readIP6Events(rd6) {
return
}
}
})()
go (func() {
if !readOtherEvents(rdOther) {
return
}
})()
<-sig
}
func readIP4Events(rd *perf.Reader) bool {
var event IP4Event
record, err := rd.Read()
if err != nil {
if errors.Is(err, perf.ErrClosed) {
return false
}
log.Printf("reading from perf event reader: %s", err)
return true
}
if record.LostSamples != 0 {
log.Printf("perf event ring buffer full, dropped %d samples", record.LostSamples)
return true
}
if err := binary.Read(bytes.NewBuffer(record.RawSample), binary.LittleEndian, &event); err != nil {
log.Printf("parsing perf event: %s", err)
return true
}
eventPayload := newGenericEventPayload(&event.Event)
eventPayload.DestIP = conv.ToIP4(event.Daddr)
eventPayload.DestPort = event.Dport
asInfo := as.GetASInfoIPv4(eventPayload.DestIP)
eventPayload.ASNameInfo = ASNameInfo{Name: asInfo.Name, AsNumber: asInfo.AsNumber}
out.PrintLine(eventPayload)
return true
}
func readIP6Events(rd *perf.Reader) bool {
var event IP6Event
record, err := rd.Read()
if err != nil {
if errors.Is(err, perf.ErrClosed) {
return false
}
log.Printf("reading from perf event reader: %s", err)
return true
}
if record.LostSamples != 0 {
log.Printf("perf event ring buffer full, dropped %d samples", record.LostSamples)
return true
}
if err := binary.Read(bytes.NewBuffer(record.RawSample), binary.LittleEndian, &event); err != nil {
log.Printf("parsing perf event: %s", err)
return true
}
eventPayload := newGenericEventPayload(&event.Event)
eventPayload.DestIP = conv.ToIP6(event.Daddr1, event.Daddr2)
eventPayload.DestPort = event.Dport
asInfo := as.GetASInfoIPv6(eventPayload.DestIP)
eventPayload.ASNameInfo = ASNameInfo{Name: asInfo.Name, AsNumber: asInfo.AsNumber}
out.PrintLine(eventPayload)
return true
}
func readOtherEvents(rd *perf.Reader) bool {
var event OtherSocketEvent
record, err := rd.Read()
if err != nil {
if errors.Is(err, perf.ErrClosed) {
return false
}
log.Printf("reading from perf event reader: %s", err)
return true
}
if record.LostSamples != 0 {
log.Printf("perf event ring buffer full, dropped %d samples", record.LostSamples)
return true
}
if err := binary.Read(bytes.NewBuffer(record.RawSample), binary.LittleEndian, &event); err != nil {
log.Printf("parsing perf event: %s", err)
return true
}
eventPayload := newGenericEventPayload(&event.Event)
out.PrintLine(eventPayload)
return true
}
func newGenericEventPayload(event *Event) eventPayload {
username := strconv.Itoa(int(event.UID))
user, err := user.LookupId(username)
if err != nil {
log.Printf("Could not lookup user with id: %d", event.UID)
} else {
username = user.Username
}
pid := int(event.Pid)
payload := eventPayload{
KernelTime: strconv.Itoa(int(event.TsUs)),
GoTime: time.Now(),
AddressFamily: conv.ToAddressFamily(int(event.Af)),
Pid: event.Pid,
ProcessPath: linux.ProcessPathForPid(pid),
ProcessArgs: linux.ProcessArgsForPid(pid),
User: username,
Comm: unix.ByteSliceToString(event.Task[:]),
}
return payload
}
// Event is a common event interface
type Event struct {
TsUs uint64
Pid uint32
UID uint32
Af uint16 // Address Family
Task [16]byte
}
// IP4Event represents a socket connect event from AF_INET(4)
type IP4Event struct {
Event
Daddr uint32
Dport uint16
}
// IP6Event represents a socket connect event from AF_INET6
type IP6Event struct {
Event
Daddr1 uint64
Daddr2 uint64
Dport uint16
}
// OtherSocketEvent represents the socket connects that are not AF_INET, AF_INET6 or AF_UNIX
type OtherSocketEvent struct {
Event
}
type eventPayload struct {
KernelTime string
GoTime time.Time
AddressFamily string
Pid uint32
ProcessPath string
ProcessArgs string
User string
Comm string
Host string
DestIP net.IP
DestPort uint16
ASNameInfo ASNameInfo
}
// ASNameInfo contains the name and number of an autonomous system (AS)
type ASNameInfo struct {
AsNumber uint32
Name string
}