-
Notifications
You must be signed in to change notification settings - Fork 164
/
tcpconnect.go
298 lines (270 loc) · 7.81 KB
/
tcpconnect.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
package tcpconnect
import (
"bytes"
"encoding/binary"
"fmt"
"os"
"os/signal"
"strings"
"time"
"github.com/iovisor/gobpf/bcc"
"github.com/linuxkerneltravel/lmp/eBPF_Supermarket/kernel_and_user_pod_observation/bpf"
"github.com/linuxkerneltravel/lmp/eBPF_Supermarket/sidecar/tools"
)
import "C"
const source string = `
// ver: 1e510db2fe3a134c476f582defc3c68e71e68b1b
#include <uapi/linux/ptrace.h>
#include <net/sock.h>
#include <bcc/proto.h>
BPF_HASH(currsock, u32, struct sock *);
// separate data structs for ipv4 and ipv6
struct ipv4_data_t {
u64 ts_ns;
u32 pid;
u32 tid;
u32 saddr;
u32 daddr;
u64 ip;
u16 lport;
u16 dport;
u32 pad;
char task[TASK_COMM_LEN];
};
BPF_PERF_OUTPUT(ipv4_events);
struct ipv6_data_t {
u64 ts_ns;
u32 pid;
u32 tid;
unsigned __int128 saddr;
unsigned __int128 daddr;
u64 ip;
u16 lport;
u16 dport;
u32 pad;
char task[TASK_COMM_LEN];
};
BPF_PERF_OUTPUT(ipv6_events);
int trace_connect_entry(struct pt_regs *ctx, struct sock *sk)
{
// if (container_should_be_filtered()) {
// return 0;
// }
u64 pid_tgid = bpf_get_current_pid_tgid();
u32 pid = pid_tgid >> 32;
u32 tid = pid_tgid;
/*FILTER_PID*/
// stash the sock ptr for lookup on return
currsock.update(&tid, &sk);
return 0;
};
static int trace_connect_return(struct pt_regs *ctx, short family)
{
int ret = PT_REGS_RC(ctx);
u64 pid_tgid = bpf_get_current_pid_tgid();
u32 pid = pid_tgid >> 32;
u32 tid = pid_tgid;
struct sock **skpp;
skpp = currsock.lookup(&tid);
if (skpp == 0) {
return 0; // missed entry
}
if (ret != 0) {
// failed to send SYNC packet, may not have populated
// socket __sk_common.{skc_rcv_saddr, ...}
currsock.delete(&tid);
return 0;
}
// pull in details
struct sock *skp = *skpp;
u16 lport = skp->__sk_common.skc_num;
u16 dport = skp->__sk_common.skc_dport;
/*FILTER_PORT*/
/*FILTER_FAMILY*/
if (family == 4) {
struct ipv4_data_t data4 = {.pid = pid, .ip = family};
data4.tid = tid;
data4.ts_ns = bpf_ktime_get_ns();
data4.saddr = skp->__sk_common.skc_rcv_saddr;
data4.daddr = skp->__sk_common.skc_daddr;
data4.lport = lport;
data4.dport = ntohs(dport);
bpf_get_current_comm(&data4.task, sizeof(data4.task));
ipv4_events.perf_submit(ctx, &data4, sizeof(data4));
} else /* 6 */ {
struct ipv6_data_t data6 = {.pid = pid, .ip = family};
data6.tid = tid;
data6.ts_ns = bpf_ktime_get_ns();
bpf_probe_read_kernel(&data6.saddr, sizeof(data6.saddr), skp->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32);
bpf_probe_read_kernel(&data6.daddr, sizeof(data6.daddr), skp->__sk_common.skc_v6_daddr.in6_u.u6_addr32);
data6.lport = lport;
data6.dport = ntohs(dport);
bpf_get_current_comm(&data6.task, sizeof(data6.task));
ipv6_events.perf_submit(ctx, &data6, sizeof(data6));
}
currsock.delete(&tid);
return 0;
}
int trace_connect_v4_return(struct pt_regs *ctx)
{
return trace_connect_return(ctx, 4);
}
int trace_connect_v6_return(struct pt_regs *ctx)
{
return trace_connect_return(ctx, 6);
}
`
type ipv4EventData struct {
TsNs uint64
Pid uint32
Tid uint32
SAddr tools.Ipv4Address
DAddr tools.Ipv4Address
Ip uint64
LPort uint16
DPort uint16
Pad uint32
Comm [16]byte
}
type ipv6EventData struct {
TsNs uint64
Pid uint32
Tid uint32
SAddr tools.Ipv6Address
DAddr tools.Ipv6Address
Ip uint64
LPort uint16
DPort uint16
Pad uint32
Comm [16]byte
}
type Event struct {
Time time.Duration `json:"Time,omitempty"`
Comm string `json:"Comm"`
Pid int `json:"Pid"`
Tid int `json:"Tid"`
SAddr string `json:"SAddr"`
DAddr string `json:"DAddr"`
LPort int `json:"LPort"`
DPort int `json:"DPort"`
Ip int `json:"Ip"`
}
func (e Event) Print() {
fmt.Println("╔======TCP connect begin====╗")
fmt.Println("Time :", e.Time.String())
fmt.Println("Comm :", e.Comm)
fmt.Println("Pid :", e.Pid)
fmt.Println("Tid :", e.Tid)
fmt.Println("SAddr:", e.SAddr)
fmt.Println("DAddr:", e.DAddr)
fmt.Println("LPort:", e.LPort)
fmt.Println("DPort:", e.DPort)
fmt.Println("Ip :", e.Ip)
fmt.Println("╚======TCP connect end======╝")
}
func getEventFromIpv4EventData(bpfEvent ipv4EventData) Event {
return Event{
Time: time.Duration(int64(bpfEvent.TsNs)),
Comm: strings.Trim(string(bpfEvent.Comm[:]), "\u0000"),
Pid: int(bpfEvent.Pid),
Tid: int(bpfEvent.Tid),
SAddr: bpfEvent.SAddr.ToString(),
DAddr: bpfEvent.DAddr.ToString(),
LPort: int(bpfEvent.LPort),
DPort: int(bpfEvent.DPort),
Ip: int(bpfEvent.Ip),
}
}
func getTcpEventFromIpv6EventData(bpfEvent ipv6EventData) Event {
return Event{
Time: time.Duration(int64(bpfEvent.TsNs)),
Comm: strings.Trim(string(bpfEvent.Comm[:]), "\u0000"),
Pid: int(bpfEvent.Pid),
Tid: int(bpfEvent.Tid),
SAddr: bpfEvent.SAddr.ToString(),
DAddr: bpfEvent.DAddr.ToString(),
LPort: int(bpfEvent.LPort),
DPort: int(bpfEvent.DPort),
Ip: int(bpfEvent.Ip),
}
}
// Probe probes TCP connect event and pushes it out
func Probe(pidList []int, portList []int, protocolList []string, ch chan<- Event) {
var hostEndiannessPortList []int
for i := 0; i < len(portList); i++ {
hostEndiannessPortList = append(hostEndiannessPortList, int(tools.NetToHostShort(uint16(portList[i]))))
}
pidFg := bpf.IntFilterGenerator{Name: "pid", List: pidList, Action: "return 0;", Reverse: false}
portFg := bpf.IntFilterGenerator{Name: "dport", List: hostEndiannessPortList, Action: "currsock.delete(&tid); return 0;", Reverse: false}
familyFg := bpf.FamilyFilterGenerator{List: protocolList}
sourceBpf := source
sourceBpf = strings.Replace(sourceBpf, "/*FILTER_PID*/", pidFg.Generate(), 1)
sourceBpf = strings.Replace(sourceBpf, "/*FILTER_PORT*/", portFg.Generate(), 1)
sourceBpf = strings.Replace(sourceBpf, "/*FILTER_FAMILY*/", familyFg.Generate(), 1)
m := bcc.NewModule(sourceBpf, []string{})
defer m.Close()
bpf.AttachKprobe(m, "trace_connect_entry", "tcp_v4_connect")
bpf.AttachKprobe(m, "trace_connect_entry", "tcp_v6_connect")
bpf.AttachKretprobe(m, "trace_connect_v4_return", "tcp_v4_connect")
bpf.AttachKretprobe(m, "trace_connect_v6_return", "tcp_v6_connect")
tablev4 := bcc.NewTable(m.TableId("ipv4_events"), m)
channelv4 := make(chan []byte, 1000)
perfMapv4, err := bcc.InitPerfMap(tablev4, channelv4, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to init perf map: %s\n", err)
os.Exit(1)
}
tablev6 := bcc.NewTable(m.TableId("ipv6_events"), m)
channelv6 := make(chan []byte, 1000)
perfMapv6, err := bcc.InitPerfMap(tablev6, channelv6, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to init perf map: %s\n", err)
os.Exit(1)
}
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt, os.Kill)
fmt.Println("TCP Connect started!")
go func() {
for {
data := <-channelv4
var event ipv4EventData
err := binary.Read(bytes.NewBuffer(data), bcc.GetHostByteOrder(), &event)
if err != nil {
fmt.Printf("failed to decode received data: %s\n", err)
continue
}
goEvent := getEventFromIpv4EventData(event)
ch <- goEvent
}
}()
go func() {
for {
data := <-channelv6
var event ipv6EventData
err := binary.Read(bytes.NewBuffer(data), bcc.GetHostByteOrder(), &event)
if err != nil {
fmt.Printf("failed to decode received data: %s\n", err)
continue
}
goEvent := getTcpEventFromIpv6EventData(event)
ch <- goEvent
}
}()
perfMapv4.Start()
perfMapv6.Start()
<-sig
perfMapv4.Stop()
perfMapv6.Stop()
}
// Sample provides a no argument function call
func Sample() {
var pidList []int
var portList []int
var protocolList []string
ch := make(chan Event, 10000)
go Probe(pidList, portList, protocolList, ch)
for {
event := <-ch
event.Print()
}
}