-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathsource-af-packet.c
2987 lines (2642 loc) · 89.5 KB
/
source-af-packet.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
/* Copyright (C) 2011-2021 Open Information Security Foundation
*
* You can copy, redistribute or modify this Program under the terms of
* the GNU General Public License version 2 as published by the Free
* Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* version 2 along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
/**
* \defgroup afppacket AF_PACKET running mode
*
* @{
*/
/**
* \file
*
* \author Eric Leblond <eric@regit.org>
*
* AF_PACKET socket acquisition support
*
*/
#define PCAP_DONT_INCLUDE_PCAP_BPF_H 1
#define SC_PCAP_DONT_INCLUDE_PCAP_H 1
#include "suricata-common.h"
#include "suricata.h"
#include "decode.h"
#include "packet-queue.h"
#include "threads.h"
#include "threadvars.h"
#include "tm-queuehandlers.h"
#include "tm-modules.h"
#include "tm-threads.h"
#include "tm-threads-common.h"
#include "conf.h"
#include "util-cpu.h"
#include "util-debug.h"
#include "util-device.h"
#include "util-ebpf.h"
#include "util-error.h"
#include "util-privs.h"
#include "util-optimize.h"
#include "util-checksum.h"
#include "util-ioctl.h"
#include "util-host-info.h"
#include "tmqh-packetpool.h"
#include "source-af-packet.h"
#include "runmodes.h"
#include "flow-storage.h"
#ifdef HAVE_AF_PACKET
#if HAVE_SYS_IOCTL_H
#include <sys/ioctl.h>
#endif
#if HAVE_LINUX_SOCKIOS_H
#include <linux/sockios.h>
#endif
#ifdef HAVE_PACKET_EBPF
#include "util-ebpf.h"
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#endif
struct bpf_program {
unsigned int bf_len;
struct bpf_insn *bf_insns;
};
#ifdef HAVE_PCAP_H
#include <pcap.h>
#endif
#ifdef HAVE_PCAP_PCAP_H
#include <pcap/pcap.h>
#endif
#include "util-bpf.h"
#if HAVE_LINUX_IF_ETHER_H
#include <linux/if_ether.h>
#endif
#if HAVE_LINUX_IF_PACKET_H
#include <linux/if_packet.h>
#endif
#if HAVE_LINUX_IF_ARP_H
#include <linux/if_arp.h>
#endif
#if HAVE_LINUX_FILTER_H
#include <linux/filter.h>
#endif
#if HAVE_SYS_MMAN_H
#include <sys/mman.h>
#endif
#ifdef HAVE_HW_TIMESTAMPING
#include <linux/net_tstamp.h>
#endif
#endif /* HAVE_AF_PACKET */
extern int max_pending_packets;
#ifndef HAVE_AF_PACKET
TmEcode NoAFPSupportExit(ThreadVars *, const void *, void **);
void TmModuleReceiveAFPRegister (void)
{
tmm_modules[TMM_RECEIVEAFP].name = "ReceiveAFP";
tmm_modules[TMM_RECEIVEAFP].ThreadInit = NoAFPSupportExit;
tmm_modules[TMM_RECEIVEAFP].Func = NULL;
tmm_modules[TMM_RECEIVEAFP].ThreadExitPrintStats = NULL;
tmm_modules[TMM_RECEIVEAFP].ThreadDeinit = NULL;
tmm_modules[TMM_RECEIVEAFP].cap_flags = 0;
tmm_modules[TMM_RECEIVEAFP].flags = TM_FLAG_RECEIVE_TM;
}
/**
* \brief Registration Function for DecodeAFP.
*/
void TmModuleDecodeAFPRegister (void)
{
tmm_modules[TMM_DECODEAFP].name = "DecodeAFP";
tmm_modules[TMM_DECODEAFP].ThreadInit = NoAFPSupportExit;
tmm_modules[TMM_DECODEAFP].Func = NULL;
tmm_modules[TMM_DECODEAFP].ThreadExitPrintStats = NULL;
tmm_modules[TMM_DECODEAFP].ThreadDeinit = NULL;
tmm_modules[TMM_DECODEAFP].cap_flags = 0;
tmm_modules[TMM_DECODEAFP].flags = TM_FLAG_DECODE_TM;
}
/**
* \brief this function prints an error message and exits.
*/
TmEcode NoAFPSupportExit(ThreadVars *tv, const void *initdata, void **data)
{
SCLogError(SC_ERR_NO_AF_PACKET,"Error creating thread %s: you do not have "
"support for AF_PACKET enabled, on Linux host please recompile "
"with --enable-af-packet", tv->name);
exit(EXIT_FAILURE);
}
#else /* We have AF_PACKET support */
#define AFP_IFACE_NAME_LENGTH 48
#define AFP_STATE_DOWN 0
#define AFP_STATE_UP 1
#define AFP_RECONNECT_TIMEOUT 500000
#define AFP_DOWN_COUNTER_INTERVAL 40
#define POLL_TIMEOUT 100
/* kernel flags defined for RX ring tp_status */
#ifndef TP_STATUS_KERNEL
#define TP_STATUS_KERNEL 0
#endif
#ifndef TP_STATUS_USER
#define TP_STATUS_USER BIT_U32(0)
#endif
#ifndef TP_STATUS_COPY
#define TP_STATUS_COPY BIT_U32(1)
#endif
#ifndef TP_STATUS_LOSING
#define TP_STATUS_LOSING BIT_U32(2)
#endif
#ifndef TP_STATUS_CSUMNOTREADY
#define TP_STATUS_CSUMNOTREADY BIT_U32(3)
#endif
#ifndef TP_STATUS_VLAN_VALID
#define TP_STATUS_VLAN_VALID BIT_U32(4)
#endif
#ifndef TP_STATUS_BLK_TMO
#define TP_STATUS_BLK_TMO BIT_U32(5)
#endif
#ifndef TP_STATUS_VLAN_TPID_VALID
#define TP_STATUS_VLAN_TPID_VALID BIT_U32(6)
#endif
#ifndef TP_STATUS_CSUM_VALID
#define TP_STATUS_CSUM_VALID BIT_U32(7)
#endif
#ifndef TP_STATUS_TS_SOFTWARE
#define TP_STATUS_TS_SOFTWARE BIT_U32(29)
#endif
#ifndef TP_STATUS_TS_SYS_HARDWARE
#define TP_STATUS_TS_SYS_HARDWARE BIT_U32(30) /* kernel comment says: "deprecated, never set" */
#endif
#ifndef TP_STATUS_TS_RAW_HARDWARE
#define TP_STATUS_TS_RAW_HARDWARE BIT_U32(31)
#endif
#ifndef TP_STATUS_USER_BUSY
/* HACK special setting in the tp_status field for frames we are
* still working on. This can happen in autofp mode where the
* capture thread goes around the ring and finds a frame that still
* hasn't been released by a worker thread.
*
* We use bits 29, 30, 31. 29 and 31 are software and hardware
* timestamps. 30 should not be set by the kernel at all. Combined
* they should never be set on the rx-ring together.
*
* The excessive casting is for handling the fact that the kernel
* defines almost all of these as int flags, not unsigned ints. */
#define TP_STATUS_USER_BUSY \
(uint32_t)((uint32_t)TP_STATUS_TS_SOFTWARE | (uint32_t)TP_STATUS_TS_SYS_HARDWARE | \
(uint32_t)TP_STATUS_TS_RAW_HARDWARE)
#endif
#define FRAME_BUSY(tp_status) \
(((uint32_t)(tp_status) & (uint32_t)TP_STATUS_USER_BUSY) == (uint32_t)TP_STATUS_USER_BUSY)
enum {
AFP_READ_OK,
AFP_READ_FAILURE,
/** Error during treatment by other functions of Suricata */
AFP_SURI_FAILURE,
AFP_KERNEL_DROP,
};
enum {
AFP_FATAL_ERROR = 1,
AFP_RECOVERABLE_ERROR,
};
union thdr {
struct tpacket2_hdr *h2;
#ifdef HAVE_TPACKET_V3
struct tpacket3_hdr *h3;
#endif
void *raw;
};
static int AFPBypassCallback(Packet *p);
static int AFPXDPBypassCallback(Packet *p);
#define MAX_MAPS 32
/**
* \brief Structure to hold thread specific variables.
*/
typedef struct AFPThreadVars_
{
union AFPRing {
union thdr **v2;
struct iovec *v3;
} ring;
/* counters */
uint64_t pkts;
ThreadVars *tv;
TmSlot *slot;
LiveDevice *livedev;
/* data link type for the thread */
uint32_t datalink;
#ifdef HAVE_PACKET_EBPF
/* File descriptor of the IPv4 flow bypass table maps */
int v4_map_fd;
/* File descriptor of the IPv6 flow bypass table maps */
int v6_map_fd;
#endif
unsigned int frame_offset;
ChecksumValidationMode checksum_mode;
/* references to packet and drop counters */
uint16_t capture_kernel_packets;
uint16_t capture_kernel_drops;
uint16_t capture_errors;
/* handle state */
uint8_t afp_state;
uint8_t copy_mode;
unsigned int flags;
/* IPS peer */
AFPPeer *mpeer;
/* no mmap mode */
uint8_t *data; /** Per function and thread data */
int datalen; /** Length of per function and thread data */
int cooked;
/*
* Init related members
*/
/* thread specific socket */
int socket;
int ring_size;
int block_size;
int block_timeout;
/* socket buffer size */
int buffer_size;
/* Filter */
const char *bpf_filter;
int ebpf_lb_fd;
int ebpf_filter_fd;
int promisc;
int down_count;
uint16_t cluster_id;
int cluster_type;
int threads;
union AFPTpacketReq {
struct tpacket_req v2;
#ifdef HAVE_TPACKET_V3
struct tpacket_req3 v3;
#endif
} req;
char iface[AFP_IFACE_NAME_LENGTH];
/* IPS output iface */
char out_iface[AFP_IFACE_NAME_LENGTH];
/* mmap'ed ring buffer */
unsigned int ring_buflen;
uint8_t *ring_buf;
uint8_t xdp_mode;
#ifdef HAVE_PACKET_EBPF
struct ebpf_timeout_config ebpf_t_config;
#endif
} AFPThreadVars;
static TmEcode ReceiveAFPThreadInit(ThreadVars *, const void *, void **);
static void ReceiveAFPThreadExitStats(ThreadVars *, void *);
static TmEcode ReceiveAFPThreadDeinit(ThreadVars *, void *);
static TmEcode ReceiveAFPLoop(ThreadVars *tv, void *data, void *slot);
static TmEcode DecodeAFPThreadInit(ThreadVars *, const void *, void **);
static TmEcode DecodeAFPThreadDeinit(ThreadVars *tv, void *data);
static TmEcode DecodeAFP(ThreadVars *, Packet *, void *);
static TmEcode AFPSetBPFFilter(AFPThreadVars *ptv);
static int AFPGetIfnumByDev(int fd, const char *ifname, int verbose);
static int AFPGetDevFlags(int fd, const char *ifname);
static int AFPDerefSocket(AFPPeer* peer);
static int AFPRefSocket(AFPPeer* peer);
/**
* \brief Registration Function for RecieveAFP.
* \todo Unit tests are needed for this module.
*/
void TmModuleReceiveAFPRegister (void)
{
tmm_modules[TMM_RECEIVEAFP].name = "ReceiveAFP";
tmm_modules[TMM_RECEIVEAFP].ThreadInit = ReceiveAFPThreadInit;
tmm_modules[TMM_RECEIVEAFP].Func = NULL;
tmm_modules[TMM_RECEIVEAFP].PktAcqLoop = ReceiveAFPLoop;
tmm_modules[TMM_RECEIVEAFP].PktAcqBreakLoop = NULL;
tmm_modules[TMM_RECEIVEAFP].ThreadExitPrintStats = ReceiveAFPThreadExitStats;
tmm_modules[TMM_RECEIVEAFP].ThreadDeinit = ReceiveAFPThreadDeinit;
tmm_modules[TMM_RECEIVEAFP].cap_flags = SC_CAP_NET_RAW;
tmm_modules[TMM_RECEIVEAFP].flags = TM_FLAG_RECEIVE_TM;
}
/**
* \defgroup afppeers AFP peers list
*
* AF_PACKET has an IPS mode were interface are peered: packet from
* on interface are sent the peered interface and the other way. The ::AFPPeer
* list is maitaining the list of peers. Each ::AFPPeer is storing the needed
* information to be able to send packet on the interface.
* A element of the list must not be destroyed during the run of Suricata as it
* is used by ::Packet and other threads.
*
* @{
*/
typedef struct AFPPeersList_ {
TAILQ_HEAD(, AFPPeer_) peers; /**< Head of list of fragments. */
int cnt;
int peered;
int turn; /**< Next value for initialisation order */
SC_ATOMIC_DECLARE(int, reached); /**< Counter used to synchronize start */
} AFPPeersList;
/**
* \brief Update the peer.
*
* Update the AFPPeer of a thread ie set new state, socket number
* or iface index.
*
*/
static void AFPPeerUpdate(AFPThreadVars *ptv)
{
if (ptv->mpeer == NULL) {
return;
}
(void)SC_ATOMIC_SET(ptv->mpeer->if_idx, AFPGetIfnumByDev(ptv->socket, ptv->iface, 0));
(void)SC_ATOMIC_SET(ptv->mpeer->socket, ptv->socket);
(void)SC_ATOMIC_SET(ptv->mpeer->state, ptv->afp_state);
}
/**
* \brief Clean and free ressource used by an ::AFPPeer
*/
static void AFPPeerClean(AFPPeer *peer)
{
if (peer->flags & AFP_SOCK_PROTECT)
SCMutexDestroy(&peer->sock_protect);
SCFree(peer);
}
AFPPeersList peerslist;
/**
* \brief Init the global list of ::AFPPeer
*/
TmEcode AFPPeersListInit(void)
{
SCEnter();
TAILQ_INIT(&peerslist.peers);
peerslist.peered = 0;
peerslist.cnt = 0;
peerslist.turn = 0;
SC_ATOMIC_INIT(peerslist.reached);
(void) SC_ATOMIC_SET(peerslist.reached, 0);
SCReturnInt(TM_ECODE_OK);
}
/**
* \brief Check that all ::AFPPeer got a peer
*
* \retval TM_ECODE_FAILED if some threads are not peered or TM_ECODE_OK else.
*/
TmEcode AFPPeersListCheck(void)
{
#define AFP_PEERS_MAX_TRY 4
#define AFP_PEERS_WAIT 20000
int try = 0;
SCEnter();
while (try < AFP_PEERS_MAX_TRY) {
if (peerslist.cnt != peerslist.peered) {
usleep(AFP_PEERS_WAIT);
} else {
SCReturnInt(TM_ECODE_OK);
}
try++;
}
SCLogError(SC_ERR_AFP_CREATE, "Threads number not equals");
SCReturnInt(TM_ECODE_FAILED);
}
/**
* \brief Declare a new AFP thread to AFP peers list.
*/
static TmEcode AFPPeersListAdd(AFPThreadVars *ptv)
{
SCEnter();
AFPPeer *peer = SCMalloc(sizeof(AFPPeer));
AFPPeer *pitem;
int mtu, out_mtu;
if (unlikely(peer == NULL)) {
SCReturnInt(TM_ECODE_FAILED);
}
memset(peer, 0, sizeof(AFPPeer));
SC_ATOMIC_INIT(peer->socket);
SC_ATOMIC_INIT(peer->sock_usage);
SC_ATOMIC_INIT(peer->if_idx);
SC_ATOMIC_INIT(peer->state);
peer->flags = ptv->flags;
peer->turn = peerslist.turn++;
if (peer->flags & AFP_SOCK_PROTECT) {
SCMutexInit(&peer->sock_protect, NULL);
}
(void)SC_ATOMIC_SET(peer->sock_usage, 0);
(void)SC_ATOMIC_SET(peer->state, AFP_STATE_DOWN);
strlcpy(peer->iface, ptv->iface, AFP_IFACE_NAME_LENGTH);
ptv->mpeer = peer;
/* add element to iface list */
TAILQ_INSERT_TAIL(&peerslist.peers, peer, next);
if (ptv->copy_mode != AFP_COPY_MODE_NONE) {
peerslist.cnt++;
/* Iter to find a peer */
TAILQ_FOREACH(pitem, &peerslist.peers, next) {
if (pitem->peer)
continue;
if (strcmp(pitem->iface, ptv->out_iface))
continue;
peer->peer = pitem;
pitem->peer = peer;
mtu = GetIfaceMTU(ptv->iface);
out_mtu = GetIfaceMTU(ptv->out_iface);
if (mtu != out_mtu) {
SCLogError(SC_ERR_AFP_CREATE,
"MTU on %s (%d) and %s (%d) are not equal, "
"transmission of packets bigger than %d will fail.",
ptv->iface, mtu,
ptv->out_iface, out_mtu,
(out_mtu > mtu) ? mtu : out_mtu);
}
peerslist.peered += 2;
break;
}
}
AFPPeerUpdate(ptv);
SCReturnInt(TM_ECODE_OK);
}
static int AFPPeersListWaitTurn(AFPPeer *peer)
{
/* If turn is zero, we already have started threads once */
if (peerslist.turn == 0)
return 0;
if (peer->turn == SC_ATOMIC_GET(peerslist.reached))
return 0;
return 1;
}
static void AFPPeersListReachedInc(void)
{
if (peerslist.turn == 0)
return;
if ((SC_ATOMIC_ADD(peerslist.reached, 1) + 1) == peerslist.turn) {
SCLogInfo("All AFP capture threads are running.");
(void)SC_ATOMIC_SET(peerslist.reached, 0);
/* Set turn to 0 to skip syncrhonization when ReceiveAFPLoop is
* restarted.
*/
peerslist.turn = 0;
}
}
static int AFPPeersListStarted(void)
{
return !peerslist.turn;
}
/**
* \brief Clean the global peers list.
*/
void AFPPeersListClean(void)
{
AFPPeer *pitem;
while ((pitem = TAILQ_FIRST(&peerslist.peers))) {
TAILQ_REMOVE(&peerslist.peers, pitem, next);
AFPPeerClean(pitem);
}
}
/**
* @}
*/
/**
* \brief Registration Function for DecodeAFP.
* \todo Unit tests are needed for this module.
*/
void TmModuleDecodeAFPRegister (void)
{
tmm_modules[TMM_DECODEAFP].name = "DecodeAFP";
tmm_modules[TMM_DECODEAFP].ThreadInit = DecodeAFPThreadInit;
tmm_modules[TMM_DECODEAFP].Func = DecodeAFP;
tmm_modules[TMM_DECODEAFP].ThreadExitPrintStats = NULL;
tmm_modules[TMM_DECODEAFP].ThreadDeinit = DecodeAFPThreadDeinit;
tmm_modules[TMM_DECODEAFP].cap_flags = 0;
tmm_modules[TMM_DECODEAFP].flags = TM_FLAG_DECODE_TM;
}
static int AFPCreateSocket(AFPThreadVars *ptv, char *devname, int verbose);
static inline void AFPDumpCounters(AFPThreadVars *ptv)
{
#ifdef PACKET_STATISTICS
struct tpacket_stats kstats;
socklen_t len = sizeof (struct tpacket_stats);
if (getsockopt(ptv->socket, SOL_PACKET, PACKET_STATISTICS,
&kstats, &len) > -1) {
SCLogDebug("(%s) Kernel: Packets %" PRIu32 ", dropped %" PRIu32 "",
ptv->tv->name,
kstats.tp_packets, kstats.tp_drops);
StatsAddUI64(ptv->tv, ptv->capture_kernel_packets, kstats.tp_packets);
StatsAddUI64(ptv->tv, ptv->capture_kernel_drops, kstats.tp_drops);
(void) SC_ATOMIC_ADD(ptv->livedev->drop, (uint64_t) kstats.tp_drops);
(void) SC_ATOMIC_ADD(ptv->livedev->pkts, (uint64_t) kstats.tp_packets);
}
#endif
}
/**
* \brief AF packet read function.
*
* This function fills
* From here the packets are picked up by the DecodeAFP thread.
*
* \param user pointer to AFPThreadVars
* \retval TM_ECODE_FAILED on failure and TM_ECODE_OK on success
*/
static int AFPRead(AFPThreadVars *ptv)
{
Packet *p = NULL;
/* XXX should try to use read that get directly to packet */
int offset = 0;
int caplen;
struct sockaddr_ll from;
struct iovec iov;
struct msghdr msg;
struct cmsghdr *cmsg;
union {
struct cmsghdr cmsg;
char buf[CMSG_SPACE(sizeof(struct tpacket_auxdata))];
} cmsg_buf;
unsigned char aux_checksum = 0;
msg.msg_name = &from;
msg.msg_namelen = sizeof(from);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = &cmsg_buf;
msg.msg_controllen = sizeof(cmsg_buf);
msg.msg_flags = 0;
if (ptv->cooked)
offset = SLL_HEADER_LEN;
else
offset = 0;
iov.iov_len = ptv->datalen - offset;
iov.iov_base = ptv->data + offset;
caplen = recvmsg(ptv->socket, &msg, MSG_TRUNC);
if (caplen < 0) {
SCLogWarning(SC_ERR_AFP_READ, "recvmsg failed with error code %" PRId32,
errno);
SCReturnInt(AFP_READ_FAILURE);
}
p = PacketGetFromQueueOrAlloc();
if (p == NULL) {
SCReturnInt(AFP_SURI_FAILURE);
}
PKT_SET_SRC(p, PKT_SRC_WIRE);
if (ptv->flags & AFP_BYPASS) {
p->BypassPacketsFlow = AFPBypassCallback;
#ifdef HAVE_PACKET_EBPF
p->afp_v.v4_map_fd = ptv->v4_map_fd;
p->afp_v.v6_map_fd = ptv->v6_map_fd;
p->afp_v.nr_cpus = ptv->ebpf_t_config.cpus_count;
#endif
}
if (ptv->flags & AFP_XDPBYPASS) {
p->BypassPacketsFlow = AFPXDPBypassCallback;
#ifdef HAVE_PACKET_EBPF
p->afp_v.v4_map_fd = ptv->v4_map_fd;
p->afp_v.v6_map_fd = ptv->v6_map_fd;
p->afp_v.nr_cpus = ptv->ebpf_t_config.cpus_count;
#endif
}
/* get timestamp of packet via ioctl */
if (ioctl(ptv->socket, SIOCGSTAMP, &p->ts) == -1) {
SCLogWarning(SC_ERR_AFP_READ, "recvmsg failed with error code %" PRId32,
errno);
TmqhOutputPacketpool(ptv->tv, p);
SCReturnInt(AFP_READ_FAILURE);
}
ptv->pkts++;
p->livedev = ptv->livedev;
/* add forged header */
if (ptv->cooked) {
SllHdr * hdrp = (SllHdr *)ptv->data;
/* XXX this is minimalist, but this seems enough */
hdrp->sll_protocol = from.sll_protocol;
}
p->datalink = ptv->datalink;
SET_PKT_LEN(p, caplen + offset);
if (PacketCopyData(p, ptv->data, GET_PKT_LEN(p)) == -1) {
TmqhOutputPacketpool(ptv->tv, p);
SCReturnInt(AFP_SURI_FAILURE);
}
SCLogDebug("pktlen: %" PRIu32 " (pkt %p, pkt data %p)",
GET_PKT_LEN(p), p, GET_PKT_DATA(p));
/* We only check for checksum disable */
if (ptv->checksum_mode == CHECKSUM_VALIDATION_DISABLE) {
p->flags |= PKT_IGNORE_CHECKSUM;
} else if (ptv->checksum_mode == CHECKSUM_VALIDATION_AUTO) {
if (ChecksumAutoModeCheck(ptv->pkts,
SC_ATOMIC_GET(ptv->livedev->pkts),
SC_ATOMIC_GET(ptv->livedev->invalid_checksums))) {
ptv->checksum_mode = CHECKSUM_VALIDATION_DISABLE;
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
aux_checksum = 1;
}
/* List is NULL if we don't have activated auxiliary data */
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg)) {
struct tpacket_auxdata *aux;
if (cmsg->cmsg_len < CMSG_LEN(sizeof(struct tpacket_auxdata)) ||
cmsg->cmsg_level != SOL_PACKET ||
cmsg->cmsg_type != PACKET_AUXDATA)
continue;
aux = (struct tpacket_auxdata *)CMSG_DATA(cmsg);
if (aux_checksum && (aux->tp_status & TP_STATUS_CSUMNOTREADY)) {
p->flags |= PKT_IGNORE_CHECKSUM;
}
break;
}
if (TmThreadsSlotProcessPkt(ptv->tv, ptv->slot, p) != TM_ECODE_OK) {
SCReturnInt(AFP_SURI_FAILURE);
}
SCReturnInt(AFP_READ_OK);
}
/**
* \brief AF packet write function.
*
* This function has to be called before the memory
* related to Packet in ring buffer is released.
*
* \param pointer to Packet
* \param version of capture: TPACKET_V2 or TPACKET_V3
* \retval TM_ECODE_FAILED on failure and TM_ECODE_OK on success
*
*/
static TmEcode AFPWritePacket(Packet *p, int version)
{
struct sockaddr_ll socket_address;
int socket;
uint8_t *pstart;
size_t plen;
union thdr h;
uint16_t vlan_tci = 0;
if (p->afp_v.copy_mode == AFP_COPY_MODE_IPS) {
if (PACKET_TEST_ACTION(p, ACTION_DROP)) {
return TM_ECODE_OK;
}
}
if (SC_ATOMIC_GET(p->afp_v.peer->state) == AFP_STATE_DOWN)
return TM_ECODE_OK;
if (p->ethh == NULL) {
SCLogWarning(SC_ERR_INVALID_VALUE, "Should have an Ethernet header");
return TM_ECODE_FAILED;
}
/* Index of the network device */
socket_address.sll_ifindex = SC_ATOMIC_GET(p->afp_v.peer->if_idx);
/* Address length*/
socket_address.sll_halen = ETH_ALEN;
/* Destination MAC */
memcpy(socket_address.sll_addr, p->ethh, 6);
/* Send packet, locking the socket if necessary */
if (p->afp_v.peer->flags & AFP_SOCK_PROTECT)
SCMutexLock(&p->afp_v.peer->sock_protect);
socket = SC_ATOMIC_GET(p->afp_v.peer->socket);
h.raw = p->afp_v.relptr;
if (version == TPACKET_V2) {
/* Copy VLAN header from ring memory. For post june 2011 kernel we test
* the flag. It is not defined for older kernel so we go best effort
* and test for non zero value of the TCI header. */
if (h.h2->tp_status & TP_STATUS_VLAN_VALID || h.h2->tp_vlan_tci) {
vlan_tci = h.h2->tp_vlan_tci;
}
} else {
#ifdef HAVE_TPACKET_V3
if (h.h3->tp_status & TP_STATUS_VLAN_VALID || h.h3->hv1.tp_vlan_tci) {
vlan_tci = h.h3->hv1.tp_vlan_tci;
}
#else
/* Should not get here */
BUG_ON(1);
#endif
}
if (vlan_tci != 0) {
pstart = GET_PKT_DATA(p) - VLAN_HEADER_LEN;
plen = GET_PKT_LEN(p) + VLAN_HEADER_LEN;
/* move ethernet addresses */
memmove(pstart, GET_PKT_DATA(p), 2 * ETH_ALEN);
/* write vlan info */
*(uint16_t *)(pstart + 2 * ETH_ALEN) = htons(0x8100);
*(uint16_t *)(pstart + 2 * ETH_ALEN + 2) = htons(vlan_tci);
} else {
pstart = GET_PKT_DATA(p);
plen = GET_PKT_LEN(p);
}
if (sendto(socket, pstart, plen, 0,
(struct sockaddr*) &socket_address,
sizeof(struct sockaddr_ll)) < 0) {
SCLogWarning(SC_ERR_SOCKET, "Sending packet failed on socket %d: %s",
socket,
strerror(errno));
if (p->afp_v.peer->flags & AFP_SOCK_PROTECT)
SCMutexUnlock(&p->afp_v.peer->sock_protect);
return TM_ECODE_FAILED;
}
if (p->afp_v.peer->flags & AFP_SOCK_PROTECT)
SCMutexUnlock(&p->afp_v.peer->sock_protect);
return TM_ECODE_OK;
}
static void AFPReleaseDataFromRing(Packet *p)
{
/* Need to be in copy mode and need to detect early release
where Ethernet header could not be set (and pseudo packet) */
if ((p->afp_v.copy_mode != AFP_COPY_MODE_NONE) && !PKT_IS_PSEUDOPKT(p)) {
AFPWritePacket(p, TPACKET_V2);
}
if (AFPDerefSocket(p->afp_v.mpeer) == 0)
goto cleanup;
if (p->afp_v.relptr) {
union thdr h;
h.raw = p->afp_v.relptr;
h.h2->tp_status = TP_STATUS_KERNEL;
}
cleanup:
AFPV_CLEANUP(&p->afp_v);
}
#ifdef HAVE_TPACKET_V3
static void AFPReleasePacketV3(Packet *p)
{
/* Need to be in copy mode and need to detect early release
where Ethernet header could not be set (and pseudo packet) */
if ((p->afp_v.copy_mode != AFP_COPY_MODE_NONE) && !PKT_IS_PSEUDOPKT(p)) {
AFPWritePacket(p, TPACKET_V3);
}
PacketFreeOrRelease(p);
}
#endif
static void AFPReleasePacket(Packet *p)
{
AFPReleaseDataFromRing(p);
PacketFreeOrRelease(p);
}
/** \internal
* \brief recoverable error - release packet and
* return AFP_SURI_FAILURE
*/
static inline int AFPSuriFailure(AFPThreadVars *ptv, union thdr h)
{
h.h2->tp_status = TP_STATUS_KERNEL;
if (++ptv->frame_offset >= ptv->req.v2.tp_frame_nr) {
ptv->frame_offset = 0;
}
SCReturnInt(AFP_SURI_FAILURE);
}
static inline void AFPReadApplyBypass(const AFPThreadVars *ptv, Packet *p)
{
if (ptv->flags & AFP_BYPASS) {
p->BypassPacketsFlow = AFPBypassCallback;
#ifdef HAVE_PACKET_EBPF
p->afp_v.v4_map_fd = ptv->v4_map_fd;
p->afp_v.v6_map_fd = ptv->v6_map_fd;
p->afp_v.nr_cpus = ptv->ebpf_t_config.cpus_count;
#endif
}
if (ptv->flags & AFP_XDPBYPASS) {
p->BypassPacketsFlow = AFPXDPBypassCallback;
#ifdef HAVE_PACKET_EBPF
p->afp_v.v4_map_fd = ptv->v4_map_fd;
p->afp_v.v6_map_fd = ptv->v6_map_fd;
p->afp_v.nr_cpus = ptv->ebpf_t_config.cpus_count;
#endif
}
}
/** \internal
* \brief setup packet for AFPReadFromRing
*/
static bool AFPReadFromRingSetupPacket(
AFPThreadVars *ptv, union thdr h, const unsigned int tp_status, Packet *p)
{
PKT_SET_SRC(p, PKT_SRC_WIRE);
/* flag the packet as TP_STATUS_USER_BUSY, which is ignore by the kernel, but
* acts as an indicator that we've reached a frame that is not yet released by
* us in autofp mode. It will be cleared when the frame gets released to the kernel. */
h.h2->tp_status |= TP_STATUS_USER_BUSY;
p->livedev = ptv->livedev;
p->datalink = ptv->datalink;
ptv->pkts++;
AFPReadApplyBypass(ptv, p);
if (h.h2->tp_len > h.h2->tp_snaplen) {
SCLogDebug("Packet length (%d) > snaplen (%d), truncating", h.h2->tp_len, h.h2->tp_snaplen);
}
/* get vlan id from header */
if ((ptv->flags & AFP_VLAN_IN_HEADER) &&
(tp_status & TP_STATUS_VLAN_VALID || h.h2->tp_vlan_tci)) {
p->vlan_id[0] = h.h2->tp_vlan_tci & 0x0fff;
p->vlan_idx = 1;
}
if (ptv->flags & AFP_ZERO_COPY) {
if (PacketSetData(p, (unsigned char *)h.raw + h.h2->tp_mac, h.h2->tp_snaplen) == -1) {
return false;
}
p->afp_v.relptr = h.raw;
p->ReleasePacket = AFPReleasePacket;
p->afp_v.mpeer = ptv->mpeer;
AFPRefSocket(ptv->mpeer);
p->afp_v.copy_mode = ptv->copy_mode;
if (p->afp_v.copy_mode != AFP_COPY_MODE_NONE) {
p->afp_v.peer = ptv->mpeer->peer;
} else {
p->afp_v.peer = NULL;
}
} else {
if (PacketCopyData(p, (unsigned char *)h.raw + h.h2->tp_mac, h.h2->tp_snaplen) == -1) {
return false;
}
}
/* Timestamp */
p->ts.tv_sec = h.h2->tp_sec;
p->ts.tv_usec = h.h2->tp_nsec / 1000;
SCLogDebug("pktlen: %" PRIu32 " (pkt %p, pkt data %p)", GET_PKT_LEN(p), p, GET_PKT_DATA(p));
/* We only check for checksum disable */
if (ptv->checksum_mode == CHECKSUM_VALIDATION_DISABLE) {
p->flags |= PKT_IGNORE_CHECKSUM;
} else if (ptv->checksum_mode == CHECKSUM_VALIDATION_AUTO) {
if (ChecksumAutoModeCheck(ptv->pkts, SC_ATOMIC_GET(ptv->livedev->pkts),
SC_ATOMIC_GET(ptv->livedev->invalid_checksums))) {
ptv->checksum_mode = CHECKSUM_VALIDATION_DISABLE;
p->flags |= PKT_IGNORE_CHECKSUM;
}
} else {
if (tp_status & TP_STATUS_CSUMNOTREADY) {
p->flags |= PKT_IGNORE_CHECKSUM;
}
}
return true;
}
static inline int AFPReadFromRingWaitForPacket(AFPThreadVars *ptv)
{
union thdr h;
struct timeval start_time;
gettimeofday(&start_time, NULL);
/* busy wait loop until we have packets available */