-
Notifications
You must be signed in to change notification settings - Fork 0
/
process.c
1536 lines (940 loc) · 33.8 KB
/
process.c
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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
p0f - packet capture and overall host / flow bookkeeping
--------------------------------------------------------
Copyright (C) 2012 by Michal Zalewski <[email protected]>
Distributed under the terms and conditions of GNU LGPL.
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pcap.h>
#include <time.h>
#include <ctype.h>
#include <sys/fcntl.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/time.h>
#include <sys/stat.h>
#include "types.h"
#include "config.h"
#include "debug.h"
#include "alloc-inl.h"
#include "process.h"
#include "hash.h"
#include "tcp.h"
#include "readfp.h"
#include "p0f.h"
#include "fp_tcp.h"
#include "fp_mtu.h"
#include "fp_http.h"
u64 packet_cnt; /* Total number of packets processed */
static s8 link_off = -1; /* Link-specific IP header offset */
static u8 bad_packets; /* Seen non-IP packets? */
static struct host_data *host_by_age, /* All host entries, by last mod */
*newest_host; /* Tail of the list */
static struct packet_flow *flow_by_age, /* All flows, by creation time */
*newest_flow; /* Tail of the list */
static struct timeval* cur_time; /* Current time, courtesy of pcap */
/* Bucketed hosts and flows: */
static struct host_data *host_b[HOST_BUCKETS];
static struct packet_flow *flow_b[FLOW_BUCKETS];
static u32 host_cnt, flow_cnt; /* Counters for bookkeeping purposes */
static void flow_dispatch(struct packet_data* pk);
static void nuke_flows(u8 silent);
static void expire_cache(void);
/* Get unix time in milliseconds. */
u64 get_unix_time_ms(void) {
return ((u64)cur_time->tv_sec) * 1000 + (cur_time->tv_usec / 1000);
}
/* Get unix time in seconds. */
u32 get_unix_time(void) {
return cur_time->tv_sec;
}
/* Find link-specific offset (pcap knows, but won't tell). */
static void find_offset(const u8* data, s32 total_len) {
u8 i;
/* Check hardcoded values for some of the most common options. */
switch (link_type) {
case DLT_RAW: link_off = 0; return;
case DLT_NULL:
case DLT_PPP: link_off = 4; return;
case DLT_LOOP:
#ifdef DLT_PPP_SERIAL
case DLT_PPP_SERIAL:
#endif /* DLT_PPP_SERIAL */
case DLT_PPP_ETHER: link_off = 8; return;
case DLT_EN10MB: link_off = 14; return;
#ifdef DLT_LINUX_SLL
case DLT_LINUX_SLL: link_off = 16; return;
#endif /* DLT_LINUX_SLL */
case DLT_PFLOG: link_off = 28; return;
case DLT_IEEE802_11: link_off = 32; return;
}
/* If this fails, try to auto-detect. There is a slight risk that if the
first packet we see is maliciously crafted, and somehow gets past the
configured BPF filter, we will configure the wrong offset. But that
seems fairly unlikely. */
for (i = 0; i < 40; i += 2, total_len -= 2) {
if (total_len < MIN_TCP4) break;
/* Perhaps this is IPv6? We check three things: IP version (first 4 bits);
total length sufficient to accommodate IPv6 and TCP headers; and the
"next protocol" field equal to PROTO_TCP. */
if (total_len >= MIN_TCP6 && (data[i] >> 4) == IP_VER6) {
struct ipv6_hdr* hdr = (struct ipv6_hdr*)(data + i);
if (hdr->proto == PROTO_TCP) {
DEBUG("[#] Detected packet offset of %u via IPv6 (link type %u).\n", i,
link_type);
link_off = i;
break;
}
}
/* Okay, let's try IPv4 then. The same approach, except the shortest packet
size must be just enough to accommodate IPv4 + TCP (already checked). */
if ((data[i] >> 4) == IP_VER4) {
struct ipv4_hdr* hdr = (struct ipv4_hdr*)(data + i);
if (hdr->proto == PROTO_TCP) {
DEBUG("[#] Detected packet offset of %u via IPv4 (link type %u).\n", i,
link_type);
link_off = i;
break;
}
}
}
/* If we found something, adjust for VLAN tags (ETH_P_8021Q == 0x8100). Else,
complain once and try again soon. */
if (link_off >= 4 && data[i-4] == 0x81 && data[i-3] == 0x00) {
DEBUG("[#] Adjusting offset due to VLAN tagging.\n");
link_off -= 4;
} else if (link_off == -1) {
link_off = -2;
WARN("Unable to find link-specific packet offset. This is bad.");
}
}
/* Convert IPv4 or IPv6 address to a human-readable form. */
u8* addr_to_str(u8* data, u8 ip_ver) {
static char tmp[128];
/* We could be using inet_ntop(), but on systems that have older libc
but still see passing IPv6 traffic, we would be in a pickle. */
if (ip_ver == IP_VER4) {
sprintf(tmp, "%u.%u.%u.%u", data[0], data[1], data[2], data[3]);
} else {
sprintf(tmp, "%x:%x:%x:%x:%x:%x:%x:%x",
(data[0] << 8) | data[1], (data[2] << 8) | data[3],
(data[4] << 8) | data[5], (data[6] << 8) | data[7],
(data[8] << 8) | data[9], (data[10] << 8) | data[11],
(data[12] << 8) | data[13], (data[14] << 8) | data[15]);
}
return (u8*)tmp;
}
/* Parse PCAP input, with plenty of sanity checking. Store interesting details
in a protocol-agnostic buffer that will be then examined upstream. */
void parse_packet(void* junk, const struct pcap_pkthdr* hdr, const u8* data) {
struct tcp_hdr* tcp;
struct packet_data pk;
s32 packet_len;
u32 tcp_doff;
u8* opt_end;
packet_cnt++;
cur_time = (struct timeval*)&hdr->ts;
if (!(packet_cnt % EXPIRE_INTERVAL)) expire_cache();
/* Be paranoid about how much data we actually have off the wire. */
packet_len = MIN(hdr->len, hdr->caplen);
if (packet_len > SNAPLEN) packet_len = SNAPLEN;
// DEBUG("[#] Received packet: len = %d, caplen = %d, limit = %d\n",
// hdr->len, hdr->caplen, SNAPLEN);
/* Account for link-level headers. */
if (link_off < 0) find_offset(data, packet_len);
if (link_off > 0) {
data += link_off;
packet_len -= link_off;
}
/* If there is no way we could have received a complete TCP packet, bail
out early. */
if (packet_len < MIN_TCP4) {
DEBUG("[#] Packet too short for any IPv4 + TCP headers, giving up!\n");
return;
}
pk.quirks = 0;
if ((*data >> 4) == IP_VER4) {
/************************
* IPv4 header parsing. *
************************/
const struct ipv4_hdr* ip4 = (struct ipv4_hdr*)data;
u32 hdr_len = (ip4->ver_hlen & 0x0F) * 4;
u16 flags_off = ntohs(RD16(ip4->flags_off));
u16 tot_len = ntohs(RD16(ip4->tot_len));
/* If the packet claims to be shorter than what we received off the wire,
honor this claim to account for etherleak-type bugs. */
if (packet_len > tot_len) {
packet_len = tot_len;
// DEBUG("[#] ipv4.tot_len = %u, adjusted accordingly.\n", tot_len);
}
/* Bail out if the result leaves no room for IPv4 + TCP headers. */
if (packet_len < MIN_TCP4) {
DEBUG("[#] packet_len = %u. Too short for IPv4 + TCP, giving up!\n",
packet_len);
return;
}
/* Bail out if the declared length of IPv4 headers is nonsensical. */
if (hdr_len < sizeof(struct ipv4_hdr)) {
DEBUG("[#] ipv4.hdr_len = %u. Too short for IPv4, giving up!\n",
hdr_len);
return;
}
/* If the packet claims to be longer than the recv buffer, best to back
off - even though we could just ignore this and recover. */
if (tot_len > packet_len) {
DEBUG("[#] ipv4.tot_len = %u but packet_len = %u, bailing out!\n",
tot_len, packet_len);
return;
}
/* And finally, bail out if after skipping the IPv4 header as specified
(including options), there wouldn't be enough room for TCP. */
if (hdr_len + sizeof(struct tcp_hdr) > packet_len) {
DEBUG("[#] ipv4.hdr_len = %u, packet_len = %d, no room for TCP!\n",
hdr_len, packet_len);
return;
}
/* Bail out if the subsequent protocol is not TCP. */
if (ip4->proto != PROTO_TCP) {
DEBUG("[#] Whoa, IPv4 packet with non-TCP payload (%u)?\n", ip4->proto);
return;
}
/* Ignore any traffic with MF or non-zero fragment offset specified. We
can do enough just fingerprinting the non-fragmented traffic. */
if (flags_off & ~(IP4_DF | IP4_MBZ)) {
DEBUG("[#] Packet fragment (0x%04x), letting it slide!\n", flags_off);
return;
}
/* Store some relevant information about the packet. */
pk.ip_ver = IP_VER4;
pk.ip_opt_len = hdr_len - 20;
memcpy(pk.src, ip4->src, 4);
memcpy(pk.dst, ip4->dst, 4);
pk.tos = ip4->tos_ecn >> 2;
pk.ttl = ip4->ttl;
if (ip4->tos_ecn & (IP_TOS_CE | IP_TOS_ECT)) pk.quirks |= QUIRK_ECN;
/* Tag some of the corner cases associated with implementation quirks. */
if (flags_off & IP4_MBZ) pk.quirks |= QUIRK_NZ_MBZ;
if (flags_off & IP4_DF) {
pk.quirks |= QUIRK_DF;
if (RD16(ip4->id)) pk.quirks |= QUIRK_NZ_ID;
} else {
if (!RD16(ip4->id)) pk.quirks |= QUIRK_ZERO_ID;
}
pk.tot_hdr = hdr_len;
tcp = (struct tcp_hdr*)(data + hdr_len);
packet_len -= hdr_len;
} else if ((*data >> 4) == IP_VER6) {
/************************
* IPv6 header parsing. *
************************/
const struct ipv6_hdr* ip6 = (struct ipv6_hdr*)data;
u32 ver_tos = ntohl(RD32(ip6->ver_tos));
u32 tot_len = ntohs(RD16(ip6->pay_len)) + sizeof(struct ipv6_hdr);
/* If the packet claims to be shorter than what we received off the wire,
honor this claim to account for etherleak-type bugs. */
if (packet_len > tot_len) {
packet_len = tot_len;
// DEBUG("[#] ipv6.tot_len = %u, adjusted accordingly.\n", tot_len);
}
/* Bail out if the result leaves no room for IPv6 + TCP headers. */
if (packet_len < MIN_TCP6) {
DEBUG("[#] packet_len = %u. Too short for IPv6 + TCP, giving up!\n",
packet_len);
return;
}
/* If the packet claims to be longer than the data we have, best to back
off - even though we could just ignore this and recover. */
if (tot_len > packet_len) {
DEBUG("[#] ipv6.tot_len = %u but packet_len = %u, bailing out!\n",
tot_len, packet_len);
return;
}
/* Bail out if the subsequent protocol is not TCP. One day, we may try
to parse and skip IPv6 extensions, but there seems to be no point in
it today. */
if (ip6->proto != PROTO_TCP) {
DEBUG("[#] IPv6 packet with non-TCP payload (%u).\n", ip6->proto);
return;
}
/* Store some relevant information about the packet. */
pk.ip_ver = IP_VER6;
pk.ip_opt_len = 0;
memcpy(pk.src, ip6->src, 16);
memcpy(pk.dst, ip6->dst, 16);
pk.tos = (ver_tos >> 22) & 0x3F;
pk.ttl = ip6->ttl;
if (ver_tos & 0xFFFFF) pk.quirks |= QUIRK_FLOW;
if ((ver_tos >> 20) & (IP_TOS_CE | IP_TOS_ECT)) pk.quirks |= QUIRK_ECN;
pk.tot_hdr = sizeof(struct ipv6_hdr);
tcp = (struct tcp_hdr*)(ip6 + 1);
packet_len -= sizeof(struct ipv6_hdr);
} else {
if (!bad_packets) {
WARN("Unknown packet type %u, link detection issue?", *data >> 4);
bad_packets = 1;
}
return;
}
/***************
* TCP parsing *
***************/
data = (u8*)tcp;
tcp_doff = (tcp->doff_rsvd >> 4) * 4;
/* As usual, let's start with sanity checks. */
if (tcp_doff < sizeof(struct tcp_hdr)) {
DEBUG("[#] tcp.hdr_len = %u, not enough for TCP!\n", tcp_doff);
return;
}
if (tcp_doff > packet_len) {
DEBUG("[#] tcp.hdr_len = %u, past end of packet!\n", tcp_doff);
return;
}
pk.tot_hdr += tcp_doff;
pk.sport = ntohs(RD16(tcp->sport));
pk.dport = ntohs(RD16(tcp->dport));
pk.tcp_type = tcp->flags & (TCP_SYN | TCP_ACK | TCP_FIN | TCP_RST);
/* NUL, SYN+FIN, SYN+RST, FIN+RST, etc, should go to /dev/null. */
if (((tcp->flags & TCP_SYN) && (tcp->flags & (TCP_FIN | TCP_RST))) ||
((tcp->flags & TCP_FIN) && (tcp->flags & TCP_RST)) ||
!pk.tcp_type) {
DEBUG("[#] Silly combination of TCP flags: 0x%02x.\n", tcp->flags);
return;
}
pk.win = ntohs(RD16(tcp->win));
pk.seq = ntohl(RD32(tcp->seq));
/* Take note of miscellanous features and quirks. */
if ((tcp->flags & (TCP_ECE | TCP_CWR)) ||
(tcp->doff_rsvd & TCP_NS_RES)) pk.quirks |= QUIRK_ECN;
if (!pk.seq) pk.quirks |= QUIRK_ZERO_SEQ;
if (tcp->flags & TCP_ACK) {
if (!RD32(tcp->ack)) pk.quirks |= QUIRK_ZERO_ACK;
} else {
/* A good proportion of RSTs tend to have "illegal" ACK numbers, so
ignore these. */
if (RD32(tcp->ack) & !(tcp->flags & TCP_RST)) {
DEBUG("[#] Non-zero ACK on a non-ACK packet: 0x%08x.\n",
ntohl(RD32(tcp->ack)));
pk.quirks |= QUIRK_NZ_ACK;
}
}
if (tcp->flags & TCP_URG) {
pk.quirks |= QUIRK_URG;
} else {
if (RD16(tcp->urg)) {
DEBUG("[#] Non-zero UPtr on a non-URG packet: 0x%08x.\n",
ntohl(RD16(tcp->urg)));
pk.quirks |= QUIRK_NZ_URG;
}
}
if (tcp->flags & TCP_PUSH) pk.quirks |= QUIRK_PUSH;
/* Handle payload data. */
if (tcp_doff == packet_len) {
pk.payload = NULL;
pk.pay_len = 0;
} else {
pk.payload = (u8*)data + tcp_doff;
pk.pay_len = packet_len - tcp_doff;
}
/**********************
* TCP option parsing *
**********************/
opt_end = (u8*)data + tcp_doff; /* First byte of non-option data */
data = (u8*)(tcp + 1);
pk.opt_cnt = 0;
pk.opt_eol_pad = 0;
pk.mss = 0;
pk.wscale = 0;
pk.ts1 = 0;
/* Option parsing problems are non-fatal, but we want to keep track of
them to spot buggy TCP stacks. */
while (data < opt_end && pk.opt_cnt < MAX_TCP_OPT) {
pk.opt_layout[pk.opt_cnt++] = *data;
switch (*data++) {
case TCPOPT_EOL:
/* EOL is a single-byte option that aborts further option parsing.
Take note of how many bytes of option data are left, and if any of
them are non-zero. */
pk.opt_eol_pad = opt_end - data;
while (data < opt_end && !*data++);
if (data != opt_end) {
pk.quirks |= QUIRK_OPT_EOL_NZ;
data = opt_end;
}
break;
case TCPOPT_NOP:
/* NOP is a single-byte option that does nothing. */
break;
case TCPOPT_MAXSEG:
/* MSS is a four-byte option with specified size. */
if (*data != 4) {
DEBUG("[#] MSS option expected to have 4 bytes, not %u.\n", *data);
pk.quirks |= QUIRK_OPT_BAD;
}
if (data + 3 > opt_end) {
DEBUG("[#] MSS option would end past end of header (%u left).\n",
opt_end - data);
goto abort_options;
}
pk.mss = ntohs(RD16p(data+1));
data += 3;
break;
case TCPOPT_WSCALE:
/* WS is a three-byte option with specified size. */
if (*data != 3) {
DEBUG("[#] MSS option expected to have 3 bytes, not %u.\n", *data);
pk.quirks |= QUIRK_OPT_BAD;
}
if (data + 2 > opt_end) {
DEBUG("[#] WS option would end past end of header (%u left).\n",
opt_end - data);
goto abort_options;
}
pk.wscale = data[1];
if (pk.wscale > 14) pk.quirks |= QUIRK_OPT_EXWS;
data += 2;
break;
case TCPOPT_SACKOK:
/* SACKOK is a two-byte option with specified size. */
if (*data != 2) {
DEBUG("[#] SACKOK option expected to have 2 bytes, not %u.\n", *data);
pk.quirks |= QUIRK_OPT_BAD;
}
if (data + 1 > opt_end) {
DEBUG("[#] SACKOK option would end past end of header (%u left).\n",
opt_end - data);
goto abort_options;
}
data++;
break;
case TCPOPT_SACK:
/* SACK is a variable-length option of 10 to 34 bytes. Because we don't
know the size any better, we need to bail out if it looks wonky. */
if (*data < 10 || *data > 34) {
DEBUG("[#] SACK length out of range (%u), bailing out.\n", *data);
goto abort_options;
}
if (data - 1 + *data > opt_end) {
DEBUG("[#] SACK option (len %u) is too long (%u left).\n",
*data, opt_end - data);
goto abort_options;
}
data += *data - 1;
break;
case TCPOPT_TSTAMP:
/* Timestamp is a ten-byte option with specified size. */
if (*data != 10) {
DEBUG("[#] TStamp option expected to have 10 bytes, not %u.\n",
*data);
pk.quirks |= QUIRK_OPT_BAD;
}
if (data + 9 > opt_end) {
DEBUG("[#] TStamp option would end past end of header (%u left).\n",
opt_end - data);
goto abort_options;
}
pk.ts1 = ntohl(RD32p(data + 1));
if (!pk.ts1) pk.quirks |= QUIRK_OPT_ZERO_TS1;
if (pk.tcp_type == TCP_SYN && RD32p(data + 5)) {
DEBUG("[#] Non-zero second timestamp: 0x%08x.\n",
ntohl(*(u32*)(data + 5)));
pk.quirks |= QUIRK_OPT_NZ_TS2;
}
data += 9;
break;
default:
/* Unknown option, presumably with specified size. */
if (*data < 2 || *data > 40) {
DEBUG("[#] Unknown option 0x%02x has invalid length %u.\n",
data[-1], *data);
goto abort_options;
}
if (data - 1 + *data > opt_end) {
DEBUG("[#] Unknown option 0x%02x (len %u) is too long (%u left).\n",
data[-1], *data, opt_end - data);
goto abort_options;
}
data += *data - 1;
}
}
if (data != opt_end) {
abort_options:
DEBUG("[#] Option parsing aborted (cnt = %u, remainder = %u).\n",
pk.opt_cnt, opt_end - data);
pk.quirks |= QUIRK_OPT_BAD;
}
flow_dispatch(&pk);
}
/* Calculate hash bucket for packet_flow. Keep the hash symmetrical: switching
source and dest should have no effect. */
static u32 get_flow_bucket(struct packet_data* pk) {
u32 bucket;
if (pk->ip_ver == IP_VER4) {
bucket = hash32(pk->src, 4, hash_seed) ^ hash32(pk->dst, 4, hash_seed);
} else {
bucket = hash32(pk->src, 16, hash_seed) ^ hash32(pk->dst, 16, hash_seed);
}
bucket ^= hash32(&pk->sport, 2, hash_seed) ^ hash32(&pk->dport, 2, hash_seed);
return bucket % FLOW_BUCKETS;
}
/* Calculate hash bucket for host_data. */
static u32 get_host_bucket(u8* addr, u8 ip_ver) {
u32 bucket;
bucket = hash32(addr, (ip_ver == IP_VER4) ? 4 : 16, hash_seed);
return bucket % HOST_BUCKETS;
}
/* Look up host data. */
struct host_data* lookup_host(u8* addr, u8 ip_ver) {
u32 bucket = get_host_bucket(addr, ip_ver);
struct host_data* h = host_b[bucket];
while (CP(h)) {
if (ip_ver == h->ip_ver &&
!memcmp(addr, h->addr, (h->ip_ver == IP_VER4) ? 4 : 16))
return h;
h = h->next;
}
return NULL;
}
/* Destroy host data. */
static void destroy_host(struct host_data* h) {
u32 bucket;
bucket = get_host_bucket(CP(h)->addr, h->ip_ver);
if (h->use_cnt) FATAL("Attempt to destroy used host data.");
DEBUG("[#] Destroying host data: %s (bucket %d)\n",
addr_to_str(h->addr, h->ip_ver), bucket);
/* Remove it from the bucketed linked list. */
if (CP(h->next)) h->next->prev = h->prev;
if (CP(h->prev)) h->prev->next = h->next;
else host_b[bucket] = h->next;
/* Remove from the by-age linked list. */
if (CP(h->newer)) h->newer->older = h->older;
else newest_host = h->older;
if (CP(h->older)) h->older->newer = h->newer;
else host_by_age = h->newer;
/* Free memory. */
ck_free(h->last_syn);
ck_free(h->last_synack);
ck_free(h->http_resp);
ck_free(h->http_req_os);
ck_free(h);
host_cnt--;
}
/* Indiscriminately kill some of the older hosts. */
static void nuke_hosts(void) {
u32 kcnt = 1 + (host_cnt * KILL_PERCENT / 100);
struct host_data* target = host_by_age;
WARN("Too many host entries, deleting %u. Use -m to adjust.", kcnt);
nuke_flows(1);
while (kcnt && CP(target)) {
struct host_data* next = target->older;
if (!target->use_cnt) { kcnt--; destroy_host(target); }
target = next;
}
}
/* Create a minimal host data. */
static struct host_data* create_host(u8* addr, u8 ip_ver) {
u32 bucket = get_host_bucket(addr, ip_ver);
struct host_data* nh;
if (host_cnt > max_hosts) nuke_hosts();
DEBUG("[#] Creating host data: %s (bucket %u)\n",
addr_to_str(addr, ip_ver), bucket);
nh = ck_alloc(sizeof(struct host_data));
/* Insert into the bucketed linked list. */
if (CP(host_b[bucket])) {
host_b[bucket]->prev = nh;
nh->next = host_b[bucket];
}
host_b[bucket] = nh;
/* Insert into the by-age linked list. */
if (CP(newest_host)) {
newest_host->newer = nh;
nh->older = newest_host;
} else host_by_age = nh;
newest_host = nh;
/* Populate other data. */
nh->ip_ver = ip_ver;
memcpy(nh->addr, addr, (ip_ver == IP_VER4) ? 4 : 16);
nh->last_seen = nh->first_seen = get_unix_time();
nh->last_up_min = -1;
nh->last_class_id = -1;
nh->last_name_id = -1;
nh->http_name_id = -1;
nh->distance = -1;
host_cnt++;
return nh;
}
/* Touch host data to make it more recent. */
static void touch_host(struct host_data* h) {
CP(h);
DEBUG("[#] Refreshing host data: %s\n", addr_to_str(h->addr, h->ip_ver));
if (h != CP(newest_host)) {
/* Remove from the the by-age linked list. */
CP(h->newer);
h->newer->older = h->older;
if (CP(h->older)) h->older->newer = h->newer;
else host_by_age = h->newer;
/* Re-insert in front. */
newest_host->newer = h;
h->older = newest_host;
h->newer = NULL;
newest_host = h;
/* This wasn't the only entry on the list, so there is no
need to update the tail (host_by_age). */
}
/* Update last seen time. */
h->last_seen = get_unix_time();
}
/* Destroy a flow. */
static void destroy_flow(struct packet_flow* f) {
CP(f);
CP(f->client);
CP(f->server);
DEBUG("[#] Destroying flow: %s/%u -> ",
addr_to_str(f->client->addr, f->client->ip_ver), f->cli_port);
DEBUG("%s/%u (bucket %u)\n",
addr_to_str(f->server->addr, f->server->ip_ver), f->srv_port,
f->bucket);
/* Remove it from the bucketed linked list. */
if (CP(f->next)) f->next->prev = f->prev;
if (CP(f->prev)) f->prev->next = f->next;
else { CP(flow_b[f->bucket]); flow_b[f->bucket] = f->next; }
/* Remove from the by-age linked list. */
if (CP(f->newer)) f->newer->older = f->older;
else { CP(newest_flow); newest_flow = f->older; }
if (CP(f->older)) f->older->newer = f->newer;
else flow_by_age = f->newer;
/* Free memory, etc. */
f->client->use_cnt--;
f->server->use_cnt--;
free_sig_hdrs(&f->http_tmp);
ck_free(f->request);
ck_free(f->response);
ck_free(f);
flow_cnt--;
}
/* Indiscriminately kill some of the oldest flows. */
static void nuke_flows(u8 silent) {
u32 kcnt = 1 + (flow_cnt * KILL_PERCENT / 100);