-
-
Notifications
You must be signed in to change notification settings - Fork 274
/
sockets.go
382 lines (320 loc) Β· 9.61 KB
/
sockets.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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
// Copyright Safing ICS Technologies GmbH. Use of this source code is governed by the AGPL license that can be found in the LICENSE file.
package proc
import (
"bufio"
"encoding/hex"
"fmt"
"net"
"os"
"strconv"
"strings"
"sync"
"unicode"
"github.com/Safing/portbase/log"
)
/*
1. find socket inode
- by incoming (listenting sockets) or outgoing (local port + external IP + port) - also local IP?
- /proc/net/{tcp|udp}[6]
2. get list of processes of uid
3. find socket inode in process fds
- if not found, refresh map of uid->pids
- if not found, check ALL pids: maybe euid != uid
4. gather process info
Cache every step!
*/
const (
TCP4 uint8 = iota
UDP4
TCP6
UDP6
ICMP4
ICMP6
TCP4Data = "/proc/net/tcp"
UDP4Data = "/proc/net/udp"
TCP6Data = "/proc/net/tcp6"
UDP6Data = "/proc/net/udp6"
ICMP4Data = "/proc/net/icmp"
ICMP6Data = "/proc/net/icmp6"
TCP_ESTABLISHED = iota + 1
TCP_SYN_SENT
TCP_SYN_RECV
TCP_FIN_WAIT1
TCP_FIN_WAIT2
TCP_TIME_WAIT
TCP_CLOSE
TCP_CLOSE_WAIT
TCP_LAST_ACK
TCP_LISTEN
TCP_CLOSING
TCP_NEW_SYN_RECV
)
var (
// connectionSocketsLock sync.Mutex
// connectionTCP4 = make(map[string][]int)
// connectionUDP4 = make(map[string][]int)
// connectionTCP6 = make(map[string][]int)
// connectionUDP6 = make(map[string][]int)
listeningSocketsLock sync.Mutex
addressListeningTCP4 = make(map[string][]int)
addressListeningUDP4 = make(map[string][]int)
addressListeningTCP6 = make(map[string][]int)
addressListeningUDP6 = make(map[string][]int)
globalListeningTCP4 = make(map[uint16][]int)
globalListeningUDP4 = make(map[uint16][]int)
globalListeningTCP6 = make(map[uint16][]int)
globalListeningUDP6 = make(map[uint16][]int)
)
func getConnectionSocket(localIP net.IP, localPort uint16, protocol uint8) (int, int, bool) {
// listeningSocketsLock.Lock()
// defer listeningSocketsLock.Unlock()
var procFile string
var localIPHex string
switch protocol {
case TCP4:
procFile = TCP4Data
localIPBytes := []byte(localIP.To4())
localIPHex = strings.ToUpper(hex.EncodeToString([]byte{localIPBytes[3], localIPBytes[2], localIPBytes[1], localIPBytes[0]}))
case UDP4:
procFile = UDP4Data
localIPBytes := []byte(localIP.To4())
localIPHex = strings.ToUpper(hex.EncodeToString([]byte{localIPBytes[3], localIPBytes[2], localIPBytes[1], localIPBytes[0]}))
case TCP6:
procFile = TCP6Data
localIPHex = hex.EncodeToString([]byte(localIP))
case UDP6:
procFile = UDP6Data
localIPHex = hex.EncodeToString([]byte(localIP))
}
localPortHex := fmt.Sprintf("%04X", localPort)
// log.Tracef("process/proc: searching for PID of: %s:%d (%s:%s)", localIP, localPort, localIPHex, localPortHex)
// open file
socketData, err := os.Open(procFile)
if err != nil {
log.Warningf("process/proc: could not read %s: %s", procFile, err)
return -1, -1, false
}
defer socketData.Close()
// file scanner
scanner := bufio.NewScanner(socketData)
scanner.Split(bufio.ScanLines)
// parse
scanner.Scan() // skip first line
for scanner.Scan() {
line := strings.FieldsFunc(scanner.Text(), procDelimiter)
// log.Tracef("line: %s", line)
if len(line) < 14 {
// log.Tracef("process: too short: %s", line)
continue
}
if line[1] != localIPHex {
continue
}
if line[2] != localPortHex {
continue
}
ok := true
uid, err := strconv.ParseInt(line[11], 10, 32)
if err != nil {
log.Warningf("process: could not parse uid %s: %s", line[11], err)
uid = -1
ok = false
}
inode, err := strconv.ParseInt(line[13], 10, 32)
if err != nil {
log.Warningf("process: could not parse inode %s: %s", line[13], err)
inode = -1
ok = false
}
// log.Tracef("process/proc: identified process of %s:%d: socket=%d uid=%d", localIP, localPort, int(inode), int(uid))
return int(uid), int(inode), ok
}
return -1, -1, false
}
func getListeningSocket(localIP net.IP, localPort uint16, protocol uint8) (uid, inode int, ok bool) {
listeningSocketsLock.Lock()
defer listeningSocketsLock.Unlock()
var addressListening map[string][]int
var globalListening map[uint16][]int
switch protocol {
case TCP4:
addressListening = addressListeningTCP4
globalListening = globalListeningTCP4
case UDP4:
addressListening = addressListeningUDP4
globalListening = globalListeningUDP4
case TCP6:
addressListening = addressListeningTCP6
globalListening = globalListeningTCP6
case UDP6:
addressListening = addressListeningUDP6
globalListening = globalListeningUDP6
}
data, ok := addressListening[fmt.Sprintf("%s:%d", localIP, localPort)]
if !ok {
data, ok = globalListening[localPort]
}
if ok {
return data[0], data[1], true
}
updateListeners(protocol)
data, ok = addressListening[fmt.Sprintf("%s:%d", localIP, localPort)]
if !ok {
data, ok = globalListening[localPort]
}
if ok {
return data[0], data[1], true
}
return 0, 0, false
}
func procDelimiter(c rune) bool {
return unicode.IsSpace(c) || c == ':'
}
func convertIPv4(data string) net.IP {
decoded, err := hex.DecodeString(data)
if err != nil {
log.Warningf("process: could not parse IPv4 %s: %s", data, err)
return nil
}
if len(decoded) != 4 {
log.Warningf("process: decoded IPv4 %s has wrong length")
return nil
}
ip := net.IPv4(decoded[3], decoded[2], decoded[1], decoded[0])
return ip
}
func convertIPv6(data string) net.IP {
decoded, err := hex.DecodeString(data)
if err != nil {
log.Warningf("process: could not parse IPv6 %s: %s", data, err)
return nil
}
if len(decoded) != 16 {
log.Warningf("process: decoded IPv6 %s has wrong length")
return nil
}
ip := net.IP(decoded)
return ip
}
func updateListeners(protocol uint8) {
switch protocol {
case TCP4:
addressListeningTCP4, globalListeningTCP4 = getListenerMaps(TCP4Data, "00000000", "0A", convertIPv4)
case UDP4:
addressListeningUDP4, globalListeningUDP4 = getListenerMaps(UDP4Data, "00000000", "07", convertIPv4)
case TCP6:
addressListeningTCP6, globalListeningTCP6 = getListenerMaps(TCP6Data, "00000000000000000000000000000000", "0A", convertIPv6)
case UDP6:
addressListeningUDP6, globalListeningUDP6 = getListenerMaps(UDP6Data, "00000000000000000000000000000000", "07", convertIPv6)
}
}
func getListenerMaps(procFile, zeroIP, socketStatusListening string, ipConverter func(string) net.IP) (map[string][]int, map[uint16][]int) {
addressListening := make(map[string][]int)
globalListening := make(map[uint16][]int)
// open file
socketData, err := os.Open(procFile)
if err != nil {
log.Warningf("process: could not read %s: %s", procFile, err)
return addressListening, globalListening
}
defer socketData.Close()
// file scanner
scanner := bufio.NewScanner(socketData)
scanner.Split(bufio.ScanLines)
// parse
scanner.Scan() // skip first line
for scanner.Scan() {
line := strings.FieldsFunc(scanner.Text(), procDelimiter)
if len(line) < 14 {
// log.Tracef("process: too short: %s", line)
continue
}
if line[5] != socketStatusListening {
// skip if not listening
// log.Tracef("process: not listening %s: %s", line, line[5])
continue
}
port, err := strconv.ParseUint(line[2], 16, 16)
// log.Tracef("port: %s", line[2])
if err != nil {
log.Warningf("process: could not parse port %s: %s", line[2], err)
continue
}
uid, err := strconv.ParseInt(line[11], 10, 32)
// log.Tracef("uid: %s", line[11])
if err != nil {
log.Warningf("process: could not parse uid %s: %s", line[11], err)
continue
}
inode, err := strconv.ParseInt(line[13], 10, 32)
// log.Tracef("inode: %s", line[13])
if err != nil {
log.Warningf("process: could not parse inode %s: %s", line[13], err)
continue
}
if line[1] == zeroIP {
globalListening[uint16(port)] = []int{int(uid), int(inode)}
} else {
address := ipConverter(line[1])
if address != nil {
addressListening[fmt.Sprintf("%s:%d", address, port)] = []int{int(uid), int(inode)}
}
}
}
return addressListening, globalListening
}
// GetActiveConnectionIDs returns all connection IDs that are still marked as active by the OS.
func GetActiveConnectionIDs() []string {
var connections []string
connections = append(connections, getConnectionIDsFromSource(TCP4Data, 6, convertIPv4)...)
connections = append(connections, getConnectionIDsFromSource(UDP4Data, 17, convertIPv4)...)
connections = append(connections, getConnectionIDsFromSource(TCP6Data, 6, convertIPv6)...)
connections = append(connections, getConnectionIDsFromSource(UDP6Data, 17, convertIPv6)...)
return connections
}
func getConnectionIDsFromSource(source string, protocol uint16, ipConverter func(string) net.IP) []string {
var connections []string
// open file
socketData, err := os.Open(source)
if err != nil {
log.Warningf("process: could not read %s: %s", source, err)
return connections
}
defer socketData.Close()
// file scanner
scanner := bufio.NewScanner(socketData)
scanner.Split(bufio.ScanLines)
// parse
scanner.Scan() // skip first line
for scanner.Scan() {
line := strings.FieldsFunc(scanner.Text(), procDelimiter)
if len(line) < 14 {
// log.Tracef("process: too short: %s", line)
continue
}
// skip listeners and closed connections
if line[5] == "0A" || line[5] == "07" {
continue
}
localIP := ipConverter(line[1])
if localIP == nil {
continue
}
localPort, err := strconv.ParseUint(line[2], 16, 16)
if err != nil {
log.Warningf("process: could not parse port: %s", err)
continue
}
remoteIP := ipConverter(line[3])
if remoteIP == nil {
continue
}
remotePort, err := strconv.ParseUint(line[4], 16, 16)
if err != nil {
log.Warningf("process: could not parse port: %s", err)
continue
}
connections = append(connections, fmt.Sprintf("%d-%s-%d-%s-%d", protocol, localIP, localPort, remoteIP, remotePort))
}
return connections
}