{{ message }}
Repository navigation
Expand file tree
/
Copy pathnetworkTracker.cpp
More file actions
937 lines (829 loc) · 32.5 KB
/
Copy pathnetworkTracker.cpp
File metadata and controls
937 lines (829 loc) · 32.5 KB
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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
/*
SysmonForLinux
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS* PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//====================================================================
//
// networkTracker.cpp
//
// Class for tracking the various network connection telemetry,
// including managing eBPF maps (ageing off, handling saturation).
//
//====================================================================
#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include "networkTracker.h"
#include "linuxHelpers.h"
#include "missingdefs.h"
extern int mapFds[];
//--------------------------------------------------------------------
//
// NetworkTracker constructor
//
// Initialise values.
//
//--------------------------------------------------------------------
NetworkTracker::NetworkTracker(LONGLONG staleSeconds, LONGLONG checkSeconds)
{
staleDuration = staleSeconds * 1000 * 1000 * 10; // in ns intervals
checkDuration = checkSeconds * 1000 * 1000 * 10; // in ns intervals
GetSystemTimeAsLargeInteger(&timeLastChecked);
}
//--------------------------------------------------------------------
//
// PurgeStale
//
// Purge old entries in the Connect and Accept trackers. Uses a
// time-based ordered map to walk the entries, which holds keys to the
// other data structures.
//
//--------------------------------------------------------------------
void NetworkTracker::PurgeStale()
{
LARGE_INTEGER curTime;
// periodically remove stale entries
GetSystemTimeAsLargeInteger(&curTime);
if (curTime.QuadPart - timeLastChecked.QuadPart > checkDuration) {
auto it = connectTrackerTimes.cbegin();
while (it != connectTrackerTimes.cend()) {
if (curTime.QuadPart - it->first > staleDuration) {
connectTracker.erase(it->second);
it = connectTrackerTimes.erase(it);
} else {
break; // as this is an ordered map, we have exhausted all stale items
}
}
auto it2 = acceptTrackerTimes.cbegin();
while (it2 != acceptTrackerTimes.cend()) {
if (curTime.QuadPart - it2->first > staleDuration) {
acceptTracker.erase(*(it2->second));
it2 = acceptTrackerTimes.erase(it2);
} else {
break; // as this is an ordered map, we have exhausted all stale items
}
}
}
GetSystemTimeAsLargeInteger(&timeLastChecked);
}
//--------------------------------------------------------------------
//
// SeenConnect
//
// Connects are observed in three transitions: CLOSE->SYN_SENT,
// SYN_SENT->ESTABLISHED, ESTABLISHED->CLOSE. The first transistion
// is in the process context and the associated process ID is of the
// process making the connection - this is stored, but the connection
// hasn't yet been properly established (maybe the port is closed,
// for example). The second transition establishes the connection, but
// the process ID is of a daemon as this happens asynchronously, hence
// retrieve the PID from the first transition. The third transition
// is the connection closing, so remove any SYN_SENT transitions.
//
// Returns the PID for established connections, otherwise 0.
//
//--------------------------------------------------------------------
pid_t NetworkTracker::SeenConnect(PSYSMON_EVENT_HEADER eventHdr)
{
if (eventHdr == NULL) {
fprintf(stderr, "NetworkTracker::SeenConnect invalid params\n");
return 0;
}
pid_t pid = 0;
PSYSMON_LINUX_NETWORK_EVENT event = (PSYSMON_LINUX_NETWORK_EVENT)&eventHdr->m_EventBody;
if (event->m_NewState == TCP_CLOSE) {
// remove state
auto it = connectTracker.find(event->m_SockId);
if (it != connectTracker.end()) {
connectTrackerTimes.erase(it->second.second);
connectTracker.erase(it);
}
pid = 0;
} else {
// attempt to insert - bool indicates success/failure
auto ret = connectTracker.emplace(event->m_SockId, std::pair<pid_t, LONGLONG>(event->m_ProcessId, event->m_EventTime.QuadPart));
if (ret.second) {
// successful insertion - didn't already exist
connectTrackerTimes.emplace(event->m_EventTime.QuadPart, event->m_SockId);
pid = 0;
} else {
// already exists
pid = ret.first->second.first;
if (event->m_NewState == TCP_ESTABLISHED) {
// connection is established, so remove it
connectTracker.erase(event->m_SockId);
connectTrackerTimes.erase(event->m_EventTime.QuadPart);
}
}
}
PurgeStale();
return pid;
}
//--------------------------------------------------------------------
//
// SeenAccept - transition of port state
//
// Accept transitions all happen asynchronously, so store the
// established transitions (which contains full source/dest
// addr/port).
//
//--------------------------------------------------------------------
void NetworkTracker::SeenAccept(AddrAndPort sourceAddrAndPort, AddrAndPort destAddrAndPort, LONGLONG eventTime)
{
acceptTracker.erase(sourceAddrAndPort);
auto ret = acceptTracker.emplace(sourceAddrAndPort, std::pair<AddrAndPort, LONGLONG>(destAddrAndPort, eventTime));
acceptTrackerTimes.emplace(eventTime, &(ret.first->first));
PurgeStale();
}
//--------------------------------------------------------------------
//
// SeenAccept - successful call to accept() syscall
//
// Calls to accept() don't provide easy access to full source/dest
// addr/port, but do happen in the context of the process, so the
// process ID is valid. This function matches the successful call to
// accept() to the previously stored port transition from SYN_RECV to
// ESTABLISHED.
//
// Returns true on success, false otherwise.
//
//--------------------------------------------------------------------
bool NetworkTracker::SeenAccept(AddrAndPort sourceAddrAndPort, AddrAndPort *destAddrAndPort)
{
if (destAddrAndPort == NULL) {
fprintf(stderr, "NetworkTracker::SeenAccept invalid params\n");
return false;
}
auto it = acceptTracker.find(sourceAddrAndPort);
if (it == acceptTracker.end()) {
return false;
}
acceptTrackerTimes.erase(it->second.second);
memcpy(destAddrAndPort, &it->second.first, sizeof(AddrAndPort));
acceptTracker.erase(it);
return true;
}
//--------------------------------------------------------------------
//
// CleseAccept
//
// Remove entries where port was closed.
//
//--------------------------------------------------------------------
void NetworkTracker::CloseAccept(AddrAndPort sourceAddrAndPort, AddrAndPort destAddrAndPort)
{
auto it = acceptTracker.find(sourceAddrAndPort);
if (it == acceptTracker.end()) {
return;
}
if (!(it->second.first == destAddrAndPort)) {
return;
}
acceptTrackerTimes.erase(it->second.second);
acceptTracker.erase(it);
}
//--------------------------------------------------------------------
//
// FindOrEraseUdpPidFd
//
// For inbound UDP connections, PID and file descriptors are stored.
// This function locates and optionally erases them from the data
// structures.
//
// Returns the last time they were reported, or 0 if not found.
//
//--------------------------------------------------------------------
LONGLONG NetworkTracker::FindOrEraseUdpPidFd(pid_t pid, int fd, const PacketAddresses *p, bool erase)
{
LONGLONG lastTime = 0;
auto it = udpRecvTrackerPidFds.find(pid);
if (it == udpRecvTrackerPidFds.end())
// no existing pid entry
return 0;
auto it2 = it->second.find(fd);
if (it2 == it->second.end())
// no existing fd entry
return 0;
if (p == NULL || it2->second.second != *p) {
// packet doesn't match
lastTime = 0;
} else {
lastTime = it2->second.first;
}
if (erase) {
// remove entries
it->second.erase(it2);
if (it->second.empty()) {
udpRecvTrackerPidFds.erase(it);
}
}
return lastTime;
}
//--------------------------------------------------------------------
//
// FindOrEraseUdpPidAddr
//
// For outbound UDP connections, PID and addresses are stored.
// This function locates and optionally erases them from the data
// structures.
//
// Returns the last time they were reported, or 0 if not found.
//
//--------------------------------------------------------------------
LONGLONG NetworkTracker::FindOrEraseUdpPidAddr(pid_t pid, const PacketAddresses *p, bool erase)
{
if (p == NULL) {
fprintf(stderr, "NetworkTracker::FindOrEraseUdpPidAddr invalid params\n");
return 0;
}
LONGLONG lastTime = 0;
auto it = udpSendTrackerPidAddrs.find(pid);
if (it == udpSendTrackerPidAddrs.end())
// no existing pid entry
return 0;
auto it2 = it->second.find(*p);
if (it2 == it->second.end())
// no existing address entry
return 0;
lastTime = it2->second;
if (erase) {
// remove entries
it->second.erase(it2);
if (it->second.empty()) {
udpSendTrackerPidAddrs.erase(it);
}
}
return lastTime;
}
//--------------------------------------------------------------------
//
// UpdateUdpPidFd
//
// For inbound UDP connections, updates a PID/FD entry.
//
// Returns the last time they were reported, or 0 if not previous
// entry.
//
//--------------------------------------------------------------------
LONGLONG NetworkTracker::UpdateUdpPidFd(pid_t pid, int fd, LONGLONG ctime, const PacketAddresses *p)
{
if (p == NULL) {
fprintf(stderr, "NetworkTracker::UpdateUdpPidFd invalid params\n");
return 0;
}
LONGLONG lastTime = 0;
std::pair<LONGLONG, PacketAddresses> newEntry(ctime, *p);
auto it = udpRecvTrackerPidFds.find(pid);
if (it == udpRecvTrackerPidFds.end()) {
// no existing pid entry
udpRecvTrackerPidFds.emplace(pid, std::unordered_map<int, std::pair<LONGLONG, PacketAddresses>>({{fd, newEntry}}));
return 0;
}
auto it2 = it->second.find(fd);
if (it2 == it->second.end()) {
// no existing fd entry
it->second.emplace(fd, newEntry);
return 0;
}
// update entry and return previous time
if (it2->second.second == *p) {
lastTime = it2->second.first;
it2->second.first = ctime;
return lastTime;
}
// entry was for a previous socket
it->second.erase(it2);
it->second.emplace(fd, newEntry);
return 0;
}
//--------------------------------------------------------------------
//
// UpdateUdpPidAddr
//
// For outbound UDP connections, updates a PID/Address entry.
//
// Returns the last time they were reported, or 0 if not previous
// entry.
//
//--------------------------------------------------------------------
LONGLONG NetworkTracker::UpdateUdpPidAddr(pid_t pid, LONGLONG ctime, const PacketAddresses *p)
{
if (p == NULL) {
fprintf(stderr, "NetworkTracker::UpdateUdpPidAddr invalid params\n");
return 0;
}
LONGLONG lastTime = 0;
auto it = udpSendTrackerPidAddrs.find(pid);
if (it == udpSendTrackerPidAddrs.end()) {
// no existing pid entry
udpSendTrackerPidAddrs.emplace(pid, std::unordered_map<PacketAddresses, LONGLONG>({{*p, ctime}}));
return 0;
}
auto it2 = it->second.find(*p);
if (it2 == it->second.end()) {
// no existing address entry
it->second.emplace(*p, ctime);
return 0;
}
// update entry and return previous time
lastTime = it2->second;
it2->second = ctime;
return lastTime;
}
//--------------------------------------------------------------------
//
// PurgeUdp
//
// Purge old entries in the outbound and inbound UDP trackers. Uses a
// time-based ordered map to walk the entries, which holds keys to the
// other data structures.
//
//--------------------------------------------------------------------
void NetworkTracker::PurgeUdp(LONGLONG curTime)
{
LONGLONG lastTime = 0;
pid_t pid = 0;
int fd;
// traverse all PID/FD entries chronologically
auto it = udpRecvTrackerTimes.cbegin();
while (it != udpRecvTrackerTimes.cend()) {
// if an entry is older than our reporting interval
if (curTime - it->first > UDP_REPORT_INTERVAL) {
pid = it->second >> 32;
fd = it->second & 0xFFFFFFFF;
// check if the kernel version is older than our reporting interval or not
if (telemetryMapLookupElem(mapFds[UDP_PIDFD_HASH], &it->second, &lastTime) < 0) {
FindOrEraseUdpPidFd(pid, fd, NULL, true);
} else {
if (curTime - lastTime > UDP_REPORT_INTERVAL) {
// remove the element from the kernel hash
telemetryMapDeleteElem(mapFds[UDP_PIDFD_HASH], &it->second);
// remove from the pid and fd tracker
FindOrEraseUdpPidFd(pid, fd, NULL, true);
} else {
// update our records with latest seen time
PacketAddresses p;
if (GetUdp(&p, pid, fd)) {
UpdateUdpPidFd(pid, fd, lastTime, &p);
udpRecvTrackerTimes.emplace(lastTime, it->second);
} else {
FindOrEraseUdpPidFd(pid, fd, NULL, true);
}
}
}
// remove existing time entry and iterate
it = udpRecvTrackerTimes.erase(it);
} else {
break; // as this is an ordered map, we have exhausted all stale items
}
}
// traverse all packetAddrs entries chronologically
auto it2 = udpSendTrackerTimes.cbegin();
while (it2 != udpSendTrackerTimes.cend()) {
// if an entry is older than our reporting interval
if (curTime - it2->first > UDP_REPORT_INTERVAL) {
PacketAddresses p(it2->second.IPv4, it2->second.srcAddr, it2->second.srcPort,
it2->second.dstAddr, it2->second.dstPort);
// check if the kernel version is older than our reporting interval or not
if (telemetryMapLookupElem(mapFds[UDP_ADDRS_HASH], &it2->second, &lastTime) < 0) {
FindOrEraseUdpPidAddr(pid, &p, true);
} else {
if (curTime - lastTime > UDP_REPORT_INTERVAL) {
// remove the element from the kernel hash
telemetryMapDeleteElem(mapFds[UDP_ADDRS_HASH], &it2->second);
// remove from the pid and addr tracker
FindOrEraseUdpPidAddr(pid, &p, true);
} else {
// update our records with latest seen time
UpdateUdpPidAddr(pid, lastTime, &p);
udpSendTrackerTimes.emplace(lastTime, it2->second);
}
}
// remove existing time entry and iterate
it2 = udpSendTrackerTimes.erase(it2);
} else {
break; // as this is an ordered map, we have exhausted all stale items
}
}
}
//--------------------------------------------------------------------
//
// PathToInode
//
// Returns the inode associated with a socket FD, or 0 if the FD isn't
// an inode path.
//
//--------------------------------------------------------------------
uint64_t NetworkTracker::PathToInode(const char *path)
{
if (path == NULL) {
fprintf(stderr, "NetworkTracker::PathToInode invalid params\n");
return 0;
}
if (strncmp(path, INODE_SOCK_PRE1, strlen(INODE_SOCK_PRE1)) == 0) {
return atoi(path + strlen(INODE_SOCK_PRE1));
} else if (strncmp(path, INODE_SOCK_PRE2, strlen(INODE_SOCK_PRE2)) == 0) {
return atoi(path + strlen(INODE_SOCK_PRE2));
}
return 0;
}
//--------------------------------------------------------------------
//
// InodeToAddr
//
// Looks up a socket inode in the UDP and UDP6 tables in /proc.
//
// Returns true on success, othewise false.
//
//--------------------------------------------------------------------
bool NetworkTracker::InodeToAddr(PacketAddresses *p, bool IPv4, uint64_t inodeIn)
{
if (p == NULL) {
fprintf(stderr, "NetworkTracker::InodeToAddr invalid params\n");
return false;
}
FILE *fp = NULL;
char *line = NULL;
size_t len = 0;
int numTokens = 0;
char lAddrText[33];
char rAddrText[33];
uint32_t sl, st, tr, uid, timeout;
uint64_t txQueue, rxQueue, tmWhen, retrnsmt, inode;
char file[PATH_MAX];
if (IPv4) {
snprintf(file, PATH_MAX, "%s", PROC_UDP_FNAME);
} else {
snprintf(file, PATH_MAX, "%s", PROC_UDP6_FNAME);
}
memset(p->localAddr, 0, sizeof(p->localAddr));
memset(p->remoteAddr, 0, sizeof(p->remoteAddr));
fp = fopen(file, "r");
if (fp == NULL)
return false;
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-result"
getline(&line, &len, fp); // skip first line
#pragma GCC diagnostic pop
while ((getline(&line, &len, fp)) >= 0) {
numTokens = sscanf(line, "%u: %32[0-9A-Fa-f]:%hX %32[0-9A-Fa-f]:%hX %X %lX:%lX %X:%lX %lX %u %u %lu %*s\n",
&sl, lAddrText, &p->localPort, rAddrText, &p->remotePort, &st, &txQueue, &rxQueue, &tr, &tmWhen,
&retrnsmt, &uid, &timeout, &inode);
if (numTokens < 14 || inode != inodeIn)
continue;
if (strlen(lAddrText) == 8) {
// IPv4
p->IPv4 = true;
*(uint32_t *)p->localAddr = strtoul(lAddrText, NULL, 16);
*(uint32_t *)p->remoteAddr = strtoul(rAddrText, NULL, 16);
free(line);
fclose(fp);
return true;
}
if (strlen(lAddrText) == 32) {
// IPv6
p->IPv4 = false;
sscanf(lAddrText, "%08X%08X%08X%08X", (uint32_t *)p->localAddr, (uint32_t *)(p->localAddr + 4),
(uint32_t *)(p->localAddr + 8), (uint32_t *)(p->localAddr + 12));
sscanf(rAddrText, "%08X%08X%08X%08X", (uint32_t *)p->remoteAddr, (uint32_t *)(p->remoteAddr + 4),
(uint32_t *)(p->remoteAddr + 8), (uint32_t *)(p->remoteAddr + 12));
free(line);
fclose(fp);
return true;
}
}
free(line);
fclose(fp);
return false;
}
//--------------------------------------------------------------------
//
// GetUdp
//
// Maps a PID and FD to a UDP connection.
//
// Returns true on success, otherwise false.
//
//--------------------------------------------------------------------
bool NetworkTracker::GetUdp(PacketAddresses *p, pid_t pid, int fd)
{
if (p == NULL) {
fprintf(stderr, "NetworkTracker::GetUdp invalid params\n");
return false;
}
char fdPath[PATH_MAX];
char fdSocket[PATH_MAX];
uint64_t inode = 0;
snprintf(fdPath, sizeof(fdPath), "/proc/%d/fd/%d", pid, fd);
if (readlink(fdPath, fdSocket, sizeof(fdSocket)) == -1)
return false;
inode = PathToInode(fdSocket);
if (inode == 0)
return false;
if (InodeToAddr(p, true, inode))
return true;
if (InodeToAddr(p, false, inode))
return true;
return false;
}
/*
These functions are called when the EBPF program sees a socket read or write.
The EBPF program should have logged it together with the current time; if it
hasn't then the EBPF hash is full and needs rapid purging, and then the
recent observation needs storing.
Otherwise (the usual case), we need to check if our existing entry is old
enough to qualify sending this one as an event - it is possible the last
observation was purged from the EBPF hash and therefore this observation has
occurred within the cool-off window.
If so, we need to update our local version with the new time. Regardless
we need to purge aged events from both hashes.
The EBPF recv hash maps PID|FD to time, and is used to limit the observations
sent to userland.
The udpRecvTrackerTimes hash maps time to PID|FD, and is used to purge old
observations (ordered map).
The udpRecvTrackerPidsFd hash maps PID to FD to time, and is used to remove
entries in the other hashes when processes terminate (map).
An EBPF program attahed to close() deletes entries from the EBPF recv hash
as sockets are closed.
The send hashes work a similar way, with the EBPF send hash mapping a
packetAddr (struct) to time, the udpSendTrackerTimes mapping times to
packetAddrs, and the udpSendTrackerPidsAddr mapping PID to PacketAddresses to
time.
Returns whether to send event - because we haven't seen this one recently.
*/
//--------------------------------------------------------------------
//
// SeenUdp - inbound read/recv/recvmsg/recvmmsg
//
// Checks if an inbound UDP connection should be reported.
//
// Returns true if it should be reported, otherwise false.
//
//--------------------------------------------------------------------
bool NetworkTracker::SeenUdp(PacketAddresses *p, pid_t pid, int fd)
{
if (p == NULL) {
fprintf(stderr, "NetworkTracker::SeenUdp invalid params\n");
return false;
}
LARGE_INTEGER curTime;
LONGLONG lastTime;
uint64_t pidFd = ((uint64_t)pid << 32) | fd;
GetSystemTimeAsLargeInteger(&curTime);
if (!GetUdp(p, pid, fd)) {
// failed to look up in /proc
return false;
}
// get the most recent sent time from the kernel
if (telemetryMapLookupElem(mapFds[UDP_PIDFD_HASH], &pidFd, &lastTime) < 0) {
// kernel has sent this entry but it's not in the hash. This means
// the hash is full. So rapidly empty a significant proportion of it
// to make space for additional observations.
auto it = udpRecvTrackerTimes.cbegin();
for (unsigned int i=0; i<UDP_HASH_SIZE * UDP_HASH_RPP && it != udpRecvTrackerTimes.cend(); i++) {
telemetryMapDeleteElem(mapFds[UDP_PIDFD_HASH], &it->second);
it++;
}
// insert the one we have just received
// find the last time we sent it
lastTime = FindOrEraseUdpPidFd(pid, fd, p, false);
if (lastTime > 0) {
// copy to kernel table
telemetryMapUpdateElem(mapFds[UDP_PIDFD_HASH], &pidFd, &lastTime, MAP_UPDATE_CREATE_OR_OVERWRITE);
} else {
// insert new element
telemetryMapUpdateElem(mapFds[UDP_PIDFD_HASH], &pidFd, &curTime.QuadPart, MAP_UPDATE_CREATE_OR_OVERWRITE);
UpdateUdpPidFd(pid, fd, curTime.QuadPart, p);
udpRecvTrackerTimes.emplace(curTime.QuadPart, pidFd);
}
PurgeUdp(curTime.QuadPart);
return (curTime.QuadPart - lastTime > UDP_REPORT_INTERVAL);
}
LONGLONG prevTime = FindOrEraseUdpPidFd(pid, fd, p, false);
if (prevTime > 0) {
if (curTime.QuadPart - prevTime > UDP_REPORT_INTERVAL) {
// not sent this entry for long enough - update records and send event
telemetryMapUpdateElem(mapFds[UDP_PIDFD_HASH], &pidFd, &curTime.QuadPart, MAP_UPDATE_CREATE_OR_OVERWRITE);
lastTime = UpdateUdpPidFd(pid, fd, curTime.QuadPart, p);
udpRecvTrackerTimes.erase(lastTime);
udpRecvTrackerTimes.emplace(curTime.QuadPart, pidFd);
PurgeUdp(curTime.QuadPart);
return true;
} else {
// our local entry is older than the kernel one - update it
telemetryMapUpdateElem(mapFds[UDP_PIDFD_HASH], &pidFd, &prevTime, MAP_UPDATE_CREATE_OR_OVERWRITE);
PurgeUdp(curTime.QuadPart);
return false;
}
} else {
// we don't have an existing entry
UpdateUdpPidFd(pid, fd, lastTime, p);
udpRecvTrackerTimes.emplace(lastTime, pidFd);
PurgeUdp(curTime.QuadPart);
return true;
}
}
//--------------------------------------------------------------------
//
// SeenUdp - outbound packet capture
//
// Checks if an outbound UDP connection should be reported.
//
// Returns true if it should be reported, otherwise false.
//
//--------------------------------------------------------------------
bool NetworkTracker::SeenUdp(const PacketAddresses *p, pid_t pid)
{
if (p == NULL) {
fprintf(stderr, "NetworkTracker::SeenUdp invalid params\n");
return false;
}
LARGE_INTEGER curTime;
LONGLONG lastTime;
packetAddrs pa;
pa.IPv4 = p->IPv4;
pa.srcPort = p->localPort;
pa.dstPort = p->remotePort;
memcpy(pa.srcAddr, p->localAddr, sizeof(pa.srcAddr));
memcpy(pa.dstAddr, p->remoteAddr, sizeof(pa.dstAddr));
GetSystemTimeAsLargeInteger(&curTime);
// get the most recent sent time from the kernel
if (telemetryMapLookupElem(mapFds[UDP_ADDRS_HASH], &pa, &lastTime) < 0) {
// kernel has sent this entry but it's not in the hash. This means
// the hash is full. So rapidly empty a significant proportion of it
// to make space for additional observations.
auto it = udpSendTrackerTimes.cbegin();
for (unsigned int i=0; i<UDP_HASH_SIZE * UDP_HASH_RPP && it != udpSendTrackerTimes.cend(); i++) {
telemetryMapDeleteElem(mapFds[UDP_PIDFD_HASH], &it->second);
it++;
}
// insert the one we have just received
// find the last time we sent it
lastTime = FindOrEraseUdpPidAddr(pid, p, false);
if (lastTime > 0) {
// copy to kernel table
telemetryMapUpdateElem(mapFds[UDP_ADDRS_HASH], &pa, &lastTime, MAP_UPDATE_CREATE_OR_OVERWRITE);
} else {
// insert new element
telemetryMapUpdateElem(mapFds[UDP_ADDRS_HASH], &pa, &curTime.QuadPart, MAP_UPDATE_CREATE_OR_OVERWRITE);
UpdateUdpPidAddr(pid, curTime.QuadPart, p);
udpSendTrackerTimes.emplace(curTime.QuadPart, pa);
}
PurgeUdp(curTime.QuadPart);
return (curTime.QuadPart - lastTime > UDP_REPORT_INTERVAL);
}
LONGLONG prevTime = FindOrEraseUdpPidAddr(pid, p, false);
if (prevTime > 0) {
if (curTime.QuadPart - prevTime > UDP_REPORT_INTERVAL) {
// not sent this entry for long enough - update records and send event
telemetryMapUpdateElem(mapFds[UDP_ADDRS_HASH], &pa, &curTime.QuadPart, MAP_UPDATE_CREATE_OR_OVERWRITE);
lastTime = UpdateUdpPidAddr(pid, curTime.QuadPart, p);
udpSendTrackerTimes.erase(lastTime);
udpSendTrackerTimes.emplace(curTime.QuadPart, pa);
PurgeUdp(curTime.QuadPart);
return true;
} else {
// our local entry is older than the kernel one - update it
telemetryMapUpdateElem(mapFds[UDP_ADDRS_HASH], &pa, &prevTime, MAP_UPDATE_CREATE_OR_OVERWRITE);
PurgeUdp(curTime.QuadPart);
return false;
}
} else {
// we don't have an existing entry
UpdateUdpPidAddr(pid, lastTime, p);
udpSendTrackerTimes.emplace(lastTime, pa);
PurgeUdp(curTime.QuadPart);
return true;
}
}
//--------------------------------------------------------------------
//
// UdpProgramTermination
//
// Purges UDP connection data when a process exits.
//
//--------------------------------------------------------------------
void NetworkTracker::UdpProgramTermination(pid_t pid)
{
auto it = udpRecvTrackerPidFds.find(pid);
if (it == udpRecvTrackerPidFds.end())
// no existing pid entry
return;
auto it2 = it->second.begin();
while (it2 != it->second.end()) {
LONGLONG lastTime = it2->second.first;
auto it3 = udpRecvTrackerTimes.find(lastTime);
if (it3 != udpRecvTrackerTimes.end()) {
telemetryMapDeleteElem(mapFds[UDP_PIDFD_HASH], &it3->second);
}
udpRecvTrackerTimes.erase(lastTime);
it2 = it->second.erase(it2);
}
udpRecvTrackerPidFds.erase(it);
auto it4 = udpSendTrackerPidAddrs.find(pid);
if (it4 == udpSendTrackerPidAddrs.end())
// no existing pid entry
return;
auto it5 = it4->second.begin();
while (it5 != it4->second.end()) {
LONGLONG lastTime = it5->second;
auto it6 = udpSendTrackerTimes.find(lastTime);
if (it6 != udpSendTrackerTimes.end()) {
telemetryMapDeleteElem(mapFds[UDP_ADDRS_HASH], &it6->second);
}
udpSendTrackerTimes.erase(lastTime);
it5 = it4->second.erase(it5);
}
}
//--------------------------------------------------------------------
//
// C wrappers for C++ methods.
//
//--------------------------------------------------------------------
extern "C" NetworkTracker *NetworkTrackerInit(LONGLONG staleSeconds, LONGLONG checkSeconds)
{
NetworkTracker *n = new NetworkTracker(staleSeconds, checkSeconds);
return n;
}
extern "C" pid_t NetworkTrackerSeenConnect(NetworkTracker *n, PSYSMON_EVENT_HEADER eventHdr)
{
if (n == NULL || eventHdr == NULL) {
fprintf(stderr, "NetworkTrackerSeenConnect invalid params\n");
return 0;
}
return n->SeenConnect(eventHdr);
}
extern "C" void NetworkTrackerSeenFullAccept(NetworkTracker *n, bool IPv4, const BYTE *sourceAddr,
unsigned short sourcePort, const BYTE *destAddr, unsigned short destPort, LONGLONG eventTime)
{
if (n == NULL || sourceAddr == NULL || destAddr == NULL) {
fprintf(stderr, "NetworkTrackerSeenFullAccept invalid params\n");
return;
}
n->SeenAccept(AddrAndPort(sourceAddr, IPv4, sourcePort), AddrAndPort(destAddr, IPv4, destPort), eventTime);
}
extern "C" bool NetworkTrackerSeenAccept(NetworkTracker *n, bool IPv4, const BYTE *sourceAddr,
unsigned short sourcePort, BYTE *destAddr, unsigned short *destPort)
{
if (n == NULL || sourceAddr == NULL || destAddr == NULL) {
fprintf(stderr, "NetworkTrackerSeenAccept invalid params\n");
return false;
}
BYTE empty[16] = {0};
AddrAndPort d(empty, IPv4, 0);
if (n->SeenAccept(AddrAndPort(sourceAddr, IPv4, sourcePort), &d)) {
memcpy(destAddr, d.addr, sizeof(d.addr));
*destPort = d.port;
return true;
}
return false;
}
extern "C" void NetworkTrackerCloseAccept(NetworkTracker *n, bool IPv4, const BYTE *sourceAddr,
unsigned short sourcePort, const BYTE *destAddr, unsigned short destPort)
{
if (n == NULL || sourceAddr == NULL || destAddr == NULL) {
fprintf(stderr, "NetworkTrackerCloseAccept invalid params\n");
return;
}
n->CloseAccept(AddrAndPort(sourceAddr, IPv4, sourcePort), AddrAndPort(destAddr, IPv4, destPort));
}
extern "C" bool NetworkTrackerSeenUdpRecv(NetworkTracker *n, bool *IPv4, BYTE *sourceAddr,
unsigned short *sourcePort, BYTE *destAddr, unsigned short *destPort, pid_t pid, int fd)
{
if (n == NULL || sourceAddr == NULL || sourcePort == NULL || destAddr == NULL || destPort == NULL) {
fprintf(stderr, "NetworkTrackerSeenUdpRecv invalid params\n");
return false;
}
PacketAddresses p;
if (!n->SeenUdp(&p, pid, fd))
return false;
*IPv4 = p.IPv4;
*sourcePort = p.localPort;
*destPort = p.remotePort;
memcpy(sourceAddr, p.localAddr, sizeof(p.localAddr));
memcpy(destAddr, p.remoteAddr, sizeof(p.remoteAddr));
return true;
}
extern "C" bool NetworkTrackerSeenUdpSend(NetworkTracker *n, bool IPv4, const BYTE *sourceAddr,
unsigned short sourcePort, const BYTE *destAddr, unsigned short destPort, pid_t pid)
{
if (n == NULL || sourceAddr == NULL || destAddr == NULL) {
fprintf(stderr, "NetworkTrackerSeenUdpSend invalid params\n");
return false;
}
PacketAddresses p(IPv4, sourceAddr, sourcePort, destAddr, destPort);
return n->SeenUdp(&p, pid);
}
extern "C" void NetworkTrackerUdpProgramTermination(NetworkTracker *n, pid_t pid)
{
if (n == NULL) {
fprintf(stderr, "NetworkTrackerUdpProgramTermination invalid params\n");
return;
}
n->UdpProgramTermination(pid);
}
You can’t perform that action at this time.
