suricata
source-windivert.c
Go to the documentation of this file.
1 /* Copyright (C) 2018 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \file
20  *
21  * \author Jacob Masen-Smith <jacob@evengx.com>
22  *
23  * WinDivert emulation of netfilter_queue functionality to hook into Suricata's
24  * IPS mode. Supported solely on Windows.
25  *
26  */
27 
28 #include "suricata-common.h"
29 #include "suricata.h"
30 #include "tm-threads.h"
31 
32 #include "util-byte.h"
33 #include "util-debug.h"
34 #include "util-device.h"
35 #include "util-error.h"
36 #include "util-ioctl.h"
37 #include "util-privs.h"
38 #include "util-unittest.h"
39 
40 #include "runmodes.h"
41 
42 #include "queue.h"
43 
45 #include "source-windivert.h"
46 
47 #ifdef WINDIVERT
48 // clang-format off
49 #include <winsock2.h>
50 #include <windows.h>
51 #include <iptypes.h>
52 #include <winerror.h>
53 // clang-format on
54 #endif
55 
56 #ifndef WINDIVERT
57 /* Gracefully handle the case where no WinDivert support is compiled in */
58 
59 TmEcode NoWinDivertSupportExit(ThreadVars *, const void *, void **);
60 
62 {
63  tmm_modules[TMM_RECEIVEWINDIVERT].name = "ReceiveWinDivert";
66 }
67 
69 {
70  tmm_modules[TMM_VERDICTWINDIVERT].name = "VerdictWinDivert";
72 }
73 
75 {
76  tmm_modules[TMM_DECODEWINDIVERT].name = "DecodeWinDivert";
79 }
80 
82  void **data)
83 {
84  SCLogError(
86  "Error creating thread %s: you do not have support for WinDivert "
87  "enabled; please recompile with --enable-windivert",
88  tv->name);
89  exit(EXIT_FAILURE);
90 }
91 
92 #else /* implied we do have WinDivert support */
93 
94 typedef struct WinDivertThreadVars_ {
95  WinDivertHandle filter_handle;
96 
97  int thread_num;
98  CaptureStats stats;
99  int64_t qpc_start_time;
100  int64_t qpc_start_count;
101  int64_t qpc_freq_usec;
102 
103  TmSlot *slot;
104 
105  bool offload_enabled;
106 
107  TAILQ_HEAD(, LiveDevice_) live_devices;
108 } WinDivertThreadVars;
109 
110 #define WINDIVERT_MAX_QUEUE 16
111 static WinDivertThreadVars g_wd_tv[WINDIVERT_MAX_QUEUE];
112 static WinDivertQueueVars g_wd_qv[WINDIVERT_MAX_QUEUE];
113 static uint16_t g_wd_num = 0;
114 static SCMutex g_wd_init_lock = SCMUTEX_INITIALIZER;
115 
116 void *WinDivertGetThread(int n)
117 {
118  if (n >= g_wd_num) {
119  return NULL;
120  }
121  return (void *)&g_wd_tv[n];
122 }
123 
124 void *WinDivertGetQueue(int n)
125 {
126  if (n >= g_wd_num) {
127  return NULL;
128  }
129  return (void *)&g_wd_qv[n];
130 }
131 
132 // not defined in MinGW winerror.h
133 #define ERROR_INVALID_IMAGE_HASH 577L
134 #define ERROR_DATA_NOT_ACCEPTED 592L
135 
136 /**
137  * \brief return an error description for Win32 error values commonly returned
138  * by WinDivert
139  */
140 static const char *WinDivertGetErrorString(DWORD error_code)
141 {
142  switch (error_code) {
143  // WinDivertOpen errors
144  case ERROR_FILE_NOT_FOUND:
145  return "The driver files WinDivert32.sys or WinDivert64.sys were "
146  "not found.";
147  case ERROR_ACCESS_DENIED:
148  return "Suricata must be run with Administrator privileges.";
149  case ERROR_INVALID_PARAMETER:
150  return "The WinDivert packet filter string is invalid.";
151  case ERROR_INVALID_IMAGE_HASH:
152  return "The WinDivert32.sys or WinDivert64.sys driver does not "
153  "have a valid digital signature, or your copy of Windows is "
154  "not up-to-date. Windows 7 and Server 2008 users need to "
155  "run Windows Update or install the following patch from "
156  "Microsoft: http://support.microsoft.com/kb/2949927";
157  case ERROR_DRIVER_BLOCKED:
158  return "This error occurs for various reasons, including: "
159  "attempting to load the 32-bit WinDivert.sys driver on a "
160  "64-bit system (or vice versa); the WinDivert.sys driver is "
161  "blocked by security software; or you are using a "
162  "virtualization environment that does not support "
163  "drivers.";
164  case EPT_S_NOT_REGISTERED:
165  return "This error occurs when the Base Filtering Engine service "
166  "has been disabled.";
167  case ERROR_PROC_NOT_FOUND:
168  return "The error may occur for Windows Vista users. The "
169  "solution is to install the following patch from Microsoft: "
170  "http://support.microsoft.com/kb/2761494.";
171 
172  // WinDivertSend errors
173  case ERROR_HOST_UNREACHABLE:
174  return "This error occurs when an impostor packet (with "
175  "pAddr->Impostor set to 1) is injected and the ip.TTL or "
176  "ipv6.HopLimit field goes to zero. This is a defense of "
177  "last resort against infinite loops caused by impostor "
178  "packets.";
179  case ERROR_DATA_NOT_ACCEPTED:
180  return "This error is returned when the user application attempts "
181  "to inject a malformed packet. It may also be returned for "
182  "valid inbound packets, and the Windows TCP/IP stack "
183  "rejects the packet for some reason.";
184  case ERROR_RETRY:
185  return "The underlying cause of this error is unknown. However, "
186  "this error usually occurs when certain kinds of "
187  "anti-virus/firewall/security software is installed, and "
188  "the error message usually resolves once the offending "
189  "program is uninstalled. This suggests a software "
190  "compatibility problem.";
191  default:
192  return "";
193  }
194 }
195 
196 /**
197  * \brief logs a WinDivert error at Error level.
198  */
199 #define WinDivertLogError(err_code) \
200  do { \
201  const char *win_err_str = Win32GetErrorString((err_code), NULL); \
202  SCLogError(SC_ERR_WINDIVERT_GENERIC, \
203  "WinDivertOpen failed, error %" PRId32 " (0x%08" PRIx32 \
204  "): %s %s", \
205  (uint32_t)(err_code), (uint32_t)(err_code), win_err_str, \
206  WinDivertGetErrorString(err_code)); \
207  LocalFree((LPVOID)win_err_str); \
208  } while (0);
209 
210 /**
211  * \brief initializes QueryPerformanceCounter values so we can get
212  * absolute time from WinDivert timestamps.
213  */
214 static void WinDivertInitQPCValues(WinDivertThreadVars *wd_tv)
215 {
216  struct timeval now;
217 
218  TimeGet(&now);
219  (void)QueryPerformanceCounter((LARGE_INTEGER *)&wd_tv->qpc_start_count);
220 
221  wd_tv->qpc_start_time =
222  (uint64_t)now.tv_sec * (1000 * 1000) + (uint64_t)now.tv_usec;
223 
224  (void)QueryPerformanceFrequency((LARGE_INTEGER *)&wd_tv->qpc_freq_usec);
225  /* \bug: clock drift? */
226  wd_tv->qpc_freq_usec /= 1000 * 1000;
227 }
228 
229 /**
230  * \brief gets a timeval from a WinDivert timestamp
231  */
232 static struct timeval WinDivertTimestampToTimeval(WinDivertThreadVars *wd_tv,
233  INT64 timestamp_count)
234 {
235  struct timeval ts;
236 
237  int64_t qpc_delta = (int64_t)timestamp_count - wd_tv->qpc_start_count;
238  int64_t unix_usec =
239  wd_tv->qpc_start_time + (qpc_delta / wd_tv->qpc_freq_usec);
240 
241  ts.tv_sec = (long)(unix_usec / (1000 * 1000));
242  ts.tv_usec = (long)(unix_usec - (int64_t)ts.tv_sec * (1000 * 1000));
243 
244  return ts;
245 }
246 
247 /**
248  * \brief initialize a WinDivert filter
249  *
250  * \param filter a WinDivert filter string as defined at
251  * https://www.reqrypt.org/windivert-doc.html#filter_language
252  *
253  * \retval 0 on success
254  * \retval -1 on failure
255  */
256 int WinDivertRegisterQueue(bool forward, char *filter_str)
257 {
258  SCEnter();
259  int ret = 0;
260 
261  WINDIVERT_LAYER layer =
262  forward ? WINDIVERT_LAYER_NETWORK_FORWARD : WINDIVERT_LAYER_NETWORK;
263 
264  /* validate the filter string */
265  const char *error_str;
266  uint32_t error_pos;
267  bool valid = WinDivertHelperCheckFilter(filter_str, layer, &error_str,
268  &error_pos);
269  if (!valid) {
270  SCLogWarning(
272  "Invalid filter \"%s\" supplied to WinDivert: %s at position "
273  "%" PRId32 "",
274  filter_str, error_str, error_pos);
276  }
277 
278  /* initialize the queue */
279  SCMutexLock(&g_wd_init_lock);
280 
281  if (g_wd_num >= WINDIVERT_MAX_QUEUE) {
283  "Too many WinDivert queues specified %" PRId32 "", g_wd_num);
284  ret = -1;
285  goto unlock;
286  }
287  if (g_wd_num == 0) {
288  /* on first registration, zero-initialize all array structs */
289  memset(&g_wd_tv, 0, sizeof(g_wd_tv));
290  memset(&g_wd_qv, 0, sizeof(g_wd_qv));
291  }
292 
293  /* init thread vars */
294  WinDivertThreadVars *wd_tv = &g_wd_tv[g_wd_num];
295  wd_tv->thread_num = g_wd_num;
296 
297  /* init queue vars */
298  WinDivertQueueVars *wd_qv = &g_wd_qv[g_wd_num];
299  wd_qv->queue_num = g_wd_num;
300 
301  WinDivertInitQPCValues(wd_tv);
302 
303  /* copy filter to persistent storage */
304  size_t filter_len = strlen(filter_str);
305  size_t copy_len =
306  strlcpy(wd_qv->filter_str, filter_str, sizeof(wd_qv->filter_str));
307  if (filter_len > copy_len) {
309  "Queue length exceeds storage by %" PRId32 " bytes",
310  (int32_t)(filter_len - copy_len));
311  ret = -1;
312  goto unlock;
313  }
314 
315  wd_qv->layer = layer;
316  wd_qv->priority =
317  g_wd_num; /* priority set in the order filters are defined */
318  wd_qv->flags = 0; /* normal inline function */
319 
320  SCMutexInit(&wd_qv->filter_init_mutex, NULL);
321  SCMutexInit(&wd_qv->counters_mutex, NULL);
322 
323  g_wd_num++;
324 
325 unlock:
326  SCMutexUnlock(&g_wd_init_lock);
327 
328  if (ret == 0) {
329  // stringify queue index to use as thread name descriptor
330  char wd_num_str[6];
331  wd_num_str[sizeof(wd_num_str) - 1] = 0;
332  snprintf(wd_num_str, sizeof(wd_num_str), "%" PRId16 "", g_wd_num);
333 
334  LiveRegisterDevice(wd_num_str);
335 
336  SCLogDebug("Queue %" PRId16 " registered", wd_qv->queue_num);
337  }
338 
339  return ret;
340 }
341 
342 /* forward declarations of internal functions */
343 /* Receive functions */
344 TmEcode ReceiveWinDivertLoop(ThreadVars *, void *, void *);
345 TmEcode ReceiveWinDivertThreadInit(ThreadVars *, const void *, void **);
346 TmEcode ReceiveWinDivertThreadDeinit(ThreadVars *, void *);
347 void ReceiveWinDivertThreadExitStats(ThreadVars *, void *);
348 
349 /* Verdict functions */
350 TmEcode VerdictWinDivert(ThreadVars *, Packet *, void *);
351 TmEcode VerdictWinDivertThreadInit(ThreadVars *, const void *, void **);
352 TmEcode VerdictWinDivertThreadDeinit(ThreadVars *, void *);
353 
354 /* Decode functions */
355 TmEcode DecodeWinDivert(ThreadVars *, Packet *, void *);
356 TmEcode DecodeWinDivertThreadInit(ThreadVars *, const void *, void **);
357 TmEcode DecodeWinDivertThreadDeinit(ThreadVars *, void *);
358 
359 /* internal helper functions */
360 static TmEcode WinDivertRecvHelper(ThreadVars *tv, WinDivertThreadVars *);
361 static TmEcode WinDivertVerdictHelper(ThreadVars *tv, Packet *p);
362 static TmEcode WinDivertCloseHelper(WinDivertThreadVars *);
363 
364 static TmEcode WinDivertCollectFilterDevices(WinDivertThreadVars *,
365  WinDivertQueueVars *);
366 static bool WinDivertIfaceMatchFilter(const char *filter_string, int if_index);
367 static void WinDivertDisableOffloading(WinDivertThreadVars *);
368 static void WinDivertRestoreOffloading(WinDivertThreadVars *);
369 
371 {
373 
374  tm_ptr->name = "ReceiveWinDivert";
375  tm_ptr->ThreadInit = ReceiveWinDivertThreadInit;
376  tm_ptr->PktAcqLoop = ReceiveWinDivertLoop;
377  tm_ptr->ThreadExitPrintStats = ReceiveWinDivertThreadExitStats;
378  tm_ptr->ThreadDeinit = ReceiveWinDivertThreadDeinit;
379  tm_ptr->flags = TM_FLAG_RECEIVE_TM;
380 }
381 
383 {
385 
386  tm_ptr->name = "VerdictWinDivert";
387  tm_ptr->ThreadInit = VerdictWinDivertThreadInit;
388  tm_ptr->Func = VerdictWinDivert;
389  tm_ptr->ThreadDeinit = VerdictWinDivertThreadDeinit;
390 }
391 
393 {
395 
396  tm_ptr->name = "DecodeWinDivert";
397  tm_ptr->ThreadInit = DecodeWinDivertThreadInit;
398  tm_ptr->Func = DecodeWinDivert;
399  tm_ptr->ThreadDeinit = DecodeWinDivertThreadDeinit;
400  tm_ptr->flags = TM_FLAG_DECODE_TM;
401 }
402 
403 /**
404  * \brief Main WinDivert packet receive pump
405  */
406 TmEcode ReceiveWinDivertLoop(ThreadVars *tv, void *data, void *slot)
407 {
408  SCEnter();
409 
410  WinDivertThreadVars *wd_tv = (WinDivertThreadVars *)data;
411  wd_tv->slot = ((TmSlot *)slot)->slot_next;
412 
413  while (true) {
416  }
417 
418  if (unlikely(WinDivertRecvHelper(tv, wd_tv) != TM_ECODE_OK)) {
420  }
421 
423  }
424 
426 }
427 
428 static TmEcode WinDivertRecvHelper(ThreadVars *tv, WinDivertThreadVars *wd_tv)
429 {
430  SCEnter();
431 
432 #ifdef COUNTERS
433  WinDivertQueueVars *wd_qv = WinDivertGetQueue(wd_tv->thread_num);
434 #endif /* COUNTERS */
435 
436  /* make sure we have at least one packet in the packet pool, to prevent us
437  * from alloc'ing packets at line rate
438  */
439  PacketPoolWait();
440 
441  /* obtain a packet buffer */
443  if (unlikely(p == NULL)) {
444  SCLogDebug(
445  "PacketGetFromQueueOrAlloc() - failed to obtain Packet buffer");
447  }
449 
450  /* receive packet, depending on offload status. MTU is used as an estimator
451  * for direct data alloc size, and this is meaningless if large segments are
452  * coalesced before they reach WinDivert */
453  bool success = false;
454  uint32_t pktlen = 0;
455  if (wd_tv->offload_enabled) {
456  /* allocate external, if not already */
458 
459  success =
460  WinDivertRecv(wd_tv->filter_handle, p->ext_pkt,
461  MAX_PAYLOAD_SIZE, &p->windivert_v.addr, &pktlen);
462  } else {
463  success = WinDivertRecv(wd_tv->filter_handle, GET_PKT_DIRECT_DATA(p),
465  &p->windivert_v.addr, &pktlen);
466  }
467  SET_PKT_LEN(p, pktlen);
468 
469  if (!success) {
470 #ifdef COUNTERS
471  SCMutexLock(&wd_qv->counters_mutex);
472  wd_qv->errs++;
473  SCMutexUnlock(&wd_qv->counters_mutex);
474 #endif /* COUNTERS */
475 
476  /* ensure packet length is zero to trigger an error in packet decoding
477  */
478  SET_PKT_LEN(p, 0);
479 
480  SCLogInfo("WinDivertRecv failed: error %" PRIu32 "",
481  (uint32_t)(GetLastError()));
483  }
484  SCLogDebug("Packet received, length %" PRId32 "", GET_PKT_LEN(p));
485 
486  p->ts = WinDivertTimestampToTimeval(wd_tv, p->windivert_v.addr.Timestamp);
487  p->windivert_v.thread_num = wd_tv->thread_num;
488 
489 #ifdef COUNTERS
490  SCMutexLock(&wd_qv->counters_mutex);
491  wd_qv->pkts++;
492  wd_qv->bytes += GET_PKT_LEN(p);
493  SCMutexUnlock(&wd_qv->counters_mutex);
494 #endif /* COUNTERS */
495 
496  /* Do the packet processing by calling TmThreadsSlotProcessPkt, this will,
497  * depending on the running mode, pass the packet to the treatment functions
498  * or push it to a packet pool. So processing time can vary.
499  */
500  if (TmThreadsSlotProcessPkt(tv, wd_tv->slot, p) != TM_ECODE_OK) {
502  }
503 
505 }
506 
507 /**
508  * \brief Init function for ReceiveWinDivert
509  *
510  * ReceiveWinDivertThreadInit sets up receiving packets via WinDivert.
511  *
512  * \param tv pointer to generic thread vars
513  * \param initdata pointer to the interface passed from the user
514  * \param data out-pointer to the WinDivert-specific thread vars
515  */
516 TmEcode ReceiveWinDivertThreadInit(ThreadVars *tv, const void *initdata,
517  void **data)
518 {
519  SCEnter();
520  TmEcode ret = TM_ECODE_OK;
521 
522  WinDivertThreadVars *wd_tv = (WinDivertThreadVars *)initdata;
523 
524  if (wd_tv == NULL) {
525  SCLogError(SC_ERR_INVALID_ARGUMENT, "initdata == NULL");
527  }
528 
529  WinDivertQueueVars *wd_qv = WinDivertGetQueue(wd_tv->thread_num);
530 
531  if (wd_qv == NULL) {
532  SCLogError(SC_ERR_INVALID_ARGUMENT, "queue == NULL");
534  }
535 
536  SCMutexLock(&wd_qv->filter_init_mutex);
537  /* does the queue already have an active handle? */
538  if (wd_qv->filter_handle != NULL &&
539  wd_qv->filter_handle != INVALID_HANDLE_VALUE) {
540  goto unlock;
541  }
542 
543  TAILQ_INIT(&wd_tv->live_devices);
544 
545  if (WinDivertCollectFilterDevices(wd_tv, wd_qv) == TM_ECODE_OK) {
546  WinDivertDisableOffloading(wd_tv);
547  } else {
549  "Failed to obtain network devices for WinDivert filter");
550  }
551 
552  /* we open now so that we can immediately start handling packets,
553  * instead of losing however many would occur between registering the
554  * queue and starting a receive thread. */
555  wd_qv->filter_handle = WinDivertOpen(wd_qv->filter_str, wd_qv->layer,
556  wd_qv->priority, wd_qv->flags);
557  if (wd_qv->filter_handle == INVALID_HANDLE_VALUE) {
558  WinDivertLogError(GetLastError());
559  ret = TM_ECODE_FAILED;
560  goto unlock;
561  }
562 
563 unlock:
564  if (ret == 0) { /* success */
565  wd_tv->filter_handle = wd_qv->filter_handle;
566 
567  /* set our return context */
568  *data = wd_tv;
569  }
570 
571  SCMutexUnlock(&wd_qv->filter_init_mutex);
572  SCReturnInt(ret);
573 }
574 
575 /**
576  * \brief collect all devices covered by this filter in the thread vars'
577  * live devices list
578  *
579  * \param wd_tv pointer to WinDivert thread vars
580  * \param wd_qv pointer to WinDivert queue vars
581  */
582 static TmEcode WinDivertCollectFilterDevices(WinDivertThreadVars *wd_tv,
583  WinDivertQueueVars *wd_qv)
584 {
585  SCEnter();
586  TmEcode ret = TM_ECODE_OK;
587 
588  IP_ADAPTER_ADDRESSES *if_info_list;
589  DWORD err = (DWORD)Win32GetAdaptersAddresses(&if_info_list);
590  if (err != NO_ERROR) {
591  ret = TM_ECODE_FAILED;
592  goto release;
593  }
594 
595  for (IP_ADAPTER_ADDRESSES *if_info = if_info_list; if_info != NULL;
596  if_info = if_info->Next) {
597 
598  if (WinDivertIfaceMatchFilter(wd_qv->filter_str, if_info->IfIndex)) {
599  SCLogConfig("Found adapter %s matching WinDivert filter %s",
600  if_info->AdapterName, wd_qv->filter_str);
601 
602  LiveDevice *new_ldev = SCCalloc(1, sizeof(LiveDevice));
603  if (new_ldev == NULL) {
604  ret = TM_ECODE_FAILED;
605  goto release;
606  }
607  new_ldev->dev = SCStrdup(if_info->AdapterName);
608  if (new_ldev->dev == NULL) {
609  ret = TM_ECODE_FAILED;
610  goto release;
611  }
612  TAILQ_INSERT_TAIL(&wd_tv->live_devices, new_ldev, next);
613  } else {
614  SCLogDebug("Adapter %s does not match WinDivert filter %s",
615  if_info->AdapterName, wd_qv->filter_str);
616  }
617  }
618 
619 release:
620  SCFree(if_info_list);
621 
622  SCReturnInt(ret);
623 }
624 
625 /**
626  * \brief test if the specified interface index matches the filter
627  */
628 static bool WinDivertIfaceMatchFilter(const char *filter_string, int if_index)
629 {
630  bool match = false;
631 
632  WINDIVERT_ADDRESS if_addr = {};
633  if_addr.IfIdx = if_index;
634 
635  uint8_t dummy[4] = {4, 4, 4, 4};
636 
637  match = WinDivertHelperEvalFilter(filter_string, WINDIVERT_LAYER_NETWORK,
638  dummy, sizeof(dummy), &if_addr);
639  if (!match) {
640  int err = GetLastError();
641  if (err != 0) {
643  "Failed to evaluate filter: 0x%" PRIx32, err);
644  }
645  }
646 
647  return match;
648 }
649 
650 /**
651  * \brief disable offload status on devices for this filter
652  *
653  * \param wd_tv pointer to WinDivert thread vars
654  */
655 static void WinDivertDisableOffloading(WinDivertThreadVars *wd_tv)
656 {
657  for (LiveDevice *ldev = TAILQ_FIRST(&wd_tv->live_devices); ldev != NULL;
658  ldev = TAILQ_NEXT(ldev, next)) {
659 
660  if (LiveGetOffload() == 0) {
661  if (GetIfaceOffloading(ldev->dev, 1, 1) == 1) {
662  wd_tv->offload_enabled = true;
663  }
664  } else {
665  if (DisableIfaceOffloading(ldev, 1, 1) != 1) {
666  wd_tv->offload_enabled = true;
667  }
668  }
669  }
670 }
671 
672 /**
673  * \brief enable offload status on devices for this filter
674  *
675  * \param wd_tv pointer to WinDivert thread vars
676  */
677 static void WinDivertRestoreOffloading(WinDivertThreadVars *wd_tv)
678 {
679  for (LiveDevice *ldev = TAILQ_FIRST(&wd_tv->live_devices); ldev != NULL;
680  ldev = TAILQ_NEXT(ldev, next)) {
681 
683  }
684 }
685 
686 /**
687  * \brief Deinit function releases resources at exit.
688  *
689  * \param tv pointer to generic thread vars
690  * \param data pointer to WinDivert-specific thread vars
691  */
692 TmEcode ReceiveWinDivertThreadDeinit(ThreadVars *tv, void *data)
693 {
694  SCEnter();
695 
696  WinDivertThreadVars *wd_tv = (WinDivertThreadVars *)data;
697 
698  SCReturnCT(WinDivertCloseHelper(wd_tv), "TmEcode");
699 }
700 
701 /**
702  * \brief ExitStats prints stats to stdout at exit
703  *
704  *
705  * \param tv pointer to generic thread vars
706  * \param data pointer to WinDivert-specific thread vars
707  */
708 void ReceiveWinDivertThreadExitStats(ThreadVars *tv, void *data)
709 {
710  SCEnter();
711 
712  WinDivertThreadVars *wd_tv = (WinDivertThreadVars *)data;
713  WinDivertQueueVars *wd_qv = WinDivertGetQueue(wd_tv->thread_num);
714  if (wd_qv == NULL) {
715  SCLogError(SC_ERR_INVALID_ARGUMENT, "queue == NULL");
716  SCReturn;
717  }
718 
719  SCMutexLock(&wd_qv->counters_mutex);
720 
721  SCLogInfo("(%s) Packets %" PRIu32 ", Bytes %" PRIu64 ", Errors %" PRIu32 "",
722  tv->name, wd_qv->pkts, wd_qv->bytes, wd_qv->errs);
723  SCLogInfo("(%s) Verdict: Accepted %" PRIu32 ", Dropped %" PRIu32
724  ", Replaced %" PRIu32 "",
725  tv->name, wd_qv->accepted, wd_qv->dropped, wd_qv->replaced);
726 
727  SCMutexUnlock(&wd_qv->counters_mutex);
728  SCReturn;
729 }
730 
731 /**
732  * \brief WinDivert verdict module packet entry function
733  */
734 TmEcode VerdictWinDivert(ThreadVars *tv, Packet *p, void *data)
735 {
736  SCEnter();
737 
738  TmEcode ret = TM_ECODE_OK;
739 
740  ret = WinDivertVerdictHelper(tv, p);
741  if (ret != TM_ECODE_OK) {
742  SCReturnInt(ret);
743  }
744 
746 }
747 
748 /**
749  * \brief internal helper function to do the bulk of verdict work
750  */
751 static TmEcode WinDivertVerdictHelper(ThreadVars *tv, Packet *p)
752 {
753  SCEnter();
754  WinDivertThreadVars *wd_tv = WinDivertGetThread(p->windivert_v.thread_num);
755 
756  /* update counters */
757  CaptureStatsUpdate(tv, &wd_tv->stats, p);
758 
759 #ifdef COUNTERS
760  WinDivertQueueVars *wd_qv = WinDivertGetQueue(wd_tv->thread_num);
761 #endif /* COUNTERS */
762 
763  p->windivert_v.verdicted = true;
764 
765  /* can't verdict a "fake" packet */
766  if (PKT_IS_PSEUDOPKT(p)) {
768  }
769 
770  /* the handle has been closed and we can no longer use it */
771  if (wd_tv->filter_handle == INVALID_HANDLE_VALUE ||
772  wd_tv->filter_handle == NULL) {
774  }
775 
776  /* we can't verdict tunnel packets without ensuring all encapsulated
777  * packets are verdicted */
778  if (IS_TUNNEL_PKT(p)) {
779  bool finalVerdict = VerdictTunnelPacket(p);
780  if (!finalVerdict) {
782  }
783 
784  // the action needs to occur on the root packet.
785  if (p->root != NULL) {
786  p = p->root;
787  }
788  }
789 
790  /* DROP simply means we do nothing; the WinDivert driver does the rest.
791  */
793 #ifdef COUNTERS
794  SCMutexLock(&wd_qv->counters_mutex);
795  wd_qv->dropped++;
796  SCMutexUnlock(&wd_qv->counters_mutex);
797 #endif /* counters */
798 
800  }
801 
802  bool success = WinDivertSend(wd_tv->filter_handle, GET_PKT_DATA(p),
803  GET_PKT_LEN(p), &p->windivert_v.addr, NULL);
804 
805  if (unlikely(!success)) {
806  WinDivertLogError(GetLastError());
808  }
809 
810 #ifdef COUNTERS
811  SCMutexLock(&wd_qv->counters_mutex);
812  wd_qv->accepted++;
813  SCMutexUnlock(&wd_qv->counters_mutex);
814 #endif /* counters */
815 
817 }
818 
819 /**
820  * \brief init the verdict thread, which is piggybacked off the receive
821  * thread
822  */
823 TmEcode VerdictWinDivertThreadInit(ThreadVars *tv, const void *initdata,
824  void **data)
825 {
826  SCEnter();
827 
828  WinDivertThreadVars *wd_tv = (WinDivertThreadVars *)initdata;
829 
830  CaptureStatsSetup(tv, &wd_tv->stats);
831 
832  *data = wd_tv;
833 
835 }
836 
837 /**
838  * \brief deinit the verdict thread and shut down the WinDivert driver if
839  * it's still up.
840  */
841 TmEcode VerdictWinDivertThreadDeinit(ThreadVars *tv, void *data)
842 {
843  SCEnter();
844 
845  WinDivertThreadVars *wd_tv = (WinDivertThreadVars *)data;
846 
847  SCReturnCT(WinDivertCloseHelper(wd_tv), "TmEcode");
848 }
849 
850 /**
851  * \brief decode a raw packet submitted to suricata from the WinDivert
852  * driver
853  *
854  * All WinDivert packets are IPv4/v6, but do not include the network layer
855  * to differentiate the two, so instead we must check the version and go
856  * from there.
857  */
858 TmEcode DecodeWinDivert(ThreadVars *tv, Packet *p, void *data)
859 {
860  SCEnter();
861 
862  IPV4Hdr *ip4h = (IPV4Hdr *)GET_PKT_DATA(p);
863  IPV6Hdr *ip6h = (IPV6Hdr *)GET_PKT_DATA(p);
864  DecodeThreadVars *d_tv = (DecodeThreadVars *)data;
865 
867 
868  DecodeUpdatePacketCounters(tv, d_tv, p);
869 
870  if (IPV4_GET_RAW_VER(ip4h) == 4) {
871  SCLogDebug("IPv4 packet");
872  DecodeIPV4(tv, d_tv, p, GET_PKT_DATA(p), GET_PKT_LEN(p));
873  } else if (IPV6_GET_RAW_VER(ip6h) == 6) {
874  SCLogDebug("IPv6 packet");
875  DecodeIPV6(tv, d_tv, p, GET_PKT_DATA(p), GET_PKT_LEN(p));
876  } else {
877  SCLogDebug("packet unsupported by WinDivert, first byte: %02x",
878  *GET_PKT_DATA(p));
879  }
880 
881  PacketDecodeFinalize(tv, d_tv, p);
882 
884 }
885 
886 TmEcode DecodeWinDivertThreadInit(ThreadVars *tv, const void *initdata,
887  void **data)
888 {
889  SCEnter();
890 
892  if (d_tv == NULL) {
894  }
895 
897 
898  *data = d_tv;
899 
901 }
902 
903 TmEcode DecodeWinDivertThreadDeinit(ThreadVars *tv, void *data)
904 {
905  SCEnter();
906 
907  if (data != NULL) {
908  DecodeThreadVarsFree(tv, data);
909  }
910 
912 }
913 
914 /**
915  * \brief helper function for use with ThreadDeinit functions
916  */
917 static TmEcode WinDivertCloseHelper(WinDivertThreadVars *wd_tv)
918 {
919  SCEnter();
920  TmEcode ret = TM_ECODE_OK;
921 
922  WinDivertQueueVars *wd_qv = WinDivertGetQueue(wd_tv->thread_num);
923  if (wd_qv == NULL) {
924  SCLogDebug("No queue could be found for thread num %" PRId32 "",
925  wd_tv->thread_num);
927  }
928 
929  SCMutexLock(&wd_qv->filter_init_mutex);
930 
931  /* check if there's nothing to close */
932  if (wd_qv->filter_handle == INVALID_HANDLE_VALUE ||
933  wd_qv->filter_handle == NULL) {
934  goto unlock;
935  }
936 
937  if (!WinDivertClose(wd_qv->filter_handle)) {
938  SCLogError(SC_ERR_FATAL, "WinDivertClose failed: error %" PRIu32 "",
939  (uint32_t)(GetLastError()));
940  ret = TM_ECODE_FAILED;
941  goto unlock;
942  }
943 
944  (void)WinDivertRestoreOffloading(wd_tv);
945 
946  wd_qv->filter_handle = NULL;
947 
948 unlock:
949  SCMutexUnlock(&wd_qv->filter_init_mutex);
950 
951  if (ret == TM_ECODE_OK) {
952  SCMutexDestroy(&wd_qv->filter_init_mutex);
953  SCMutexDestroy(&wd_qv->counters_mutex);
954  }
955 
956  SCReturnInt(ret);
957 }
958 
959 #ifdef UNITTESTS
960 static int SourceWinDivertTestIfaceMatchFilter(void)
961 {
962  struct testdata {
963  const char *filter;
964  int if_index;
965  bool expected;
966  };
967 
968  struct testdata tests[] = {
969  {"true", 11, true},
970  {"ifIdx=11", 11, true},
971  {"ifIdx==11", 11, true},
972  {"ifIdx!=11", 1, true},
973  {"ifIdx!=11", 11, false},
974  {"ifIdx=3", 4, false},
975  {"ifIdx=11 || ifIdx=5", 5, true},
976  {"ifIdx=11 || ifIdx=4", 5, false},
977  {"ifIdx<3 || ifIdx>7", 8, true},
978  {"ifIdx<3 || ifIdx>7", 5, false},
979  {"ifIdx>3 or ifIdx<7", 5, true},
980  {"ifIdx>3 && ifIdx<7", 5, true},
981  {"ifIdx>3 && ifIdx<7", 1, false},
982  {"(ifIdx > 3 && ifIdx < 7) or ifIdx == 11", 11, true}};
983 
984  size_t count = (sizeof(tests) / sizeof(tests[0]));
985 
986  for (size_t i = 0; i < count; i++) {
987  struct testdata test = tests[i];
988 
989  bool actual = WinDivertIfaceMatchFilter(test.filter, test.if_index);
990  if (actual != test.expected) {
991  printf("WinDivertIfaceMatchFilter(\"%s\", %d) == %d, expected %d\n",
992  test.filter, test.if_index, actual, test.expected);
993  FAIL;
994  }
995  }
996  PASS;
997 }
998 #endif
999 
1000 /**
1001  * \brief this function registers unit tests for the WinDivert Source
1002  */
1003 void SourceWinDivertRegisterTests()
1004 {
1005 #ifdef UNITTESTS
1006  UtRegisterTest("SourceWinDivertTestIfaceMatchFilter",
1007  SourceWinDivertTestIfaceMatchFilter);
1008 #endif
1009 }
1010 
1011 #endif /* WINDIVERT */
util-byte.h
tm-threads.h
ts
uint64_t ts
Definition: source-erf-file.c:54
LiveRegisterDevice
int LiveRegisterDevice(const char *dev)
Add a pcap device for monitoring and create structure.
Definition: util-device.c:124
IPV6_GET_RAW_VER
#define IPV6_GET_RAW_VER(ip6h)
Definition: decode-ipv6.h:62
SC_ERR_WINDIVERT_NOSUPPORT
@ SC_ERR_WINDIVERT_NOSUPPORT
Definition: util-error.h:346
ThreadVars_::name
char name[16]
Definition: threadvars.h:65
TAILQ_INIT
#define TAILQ_INIT(head)
Definition: queue.h:370
TmModuleDecodeWinDivertRegister
void TmModuleDecodeWinDivertRegister(void)
Definition: source-windivert.c:74
PKT_IS_PSEUDOPKT
#define PKT_IS_PSEUDOPKT(p)
return 1 if the packet is a pseudo packet
Definition: decode.h:1125
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
UtRegisterTest
void UtRegisterTest(const char *name, int(*TestFn)(void))
Register unit test.
Definition: util-unittest.c:103
CaptureStats_
Definition: decode.h:687
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:298
LiveGetOffload
int LiveGetOffload(void)
Definition: util-device.c:79
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
SC_ERR_WINDIVERT_GENERIC
@ SC_ERR_WINDIVERT_GENERIC
Definition: util-error.h:345
LiveDevice_
Definition: util-device.h:40
source-windivert-prototypes.h
SURICATA_STOP
#define SURICATA_STOP
Definition: suricata.h:90
NoWinDivertSupportExit
TmEcode NoWinDivertSupportExit(ThreadVars *, const void *, void **)
Definition: source-windivert.c:81
SCMutexLock
#define SCMutexLock(mut)
Definition: threads-debug.h:117
TmModuleVerdictWinDivertRegister
void TmModuleVerdictWinDivertRegister(void)
Definition: source-windivert.c:68
util-privs.h
StatsSyncCountersIfSignalled
#define StatsSyncCountersIfSignalled(tv)
Definition: counters.h:137
SCMUTEX_INITIALIZER
#define SCMUTEX_INITIALIZER
Definition: threads-debug.h:121
TAILQ_INSERT_TAIL
#define TAILQ_INSERT_TAIL(head, elm, field)
Definition: queue.h:385
PacketDecodeFinalize
void PacketDecodeFinalize(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p)
Finalize decoding of a packet.
Definition: decode.c:118
TM_ECODE_FAILED
@ TM_ECODE_FAILED
Definition: tm-threads-common.h:79
GET_PKT_DIRECT_MAX_SIZE
#define GET_PKT_DIRECT_MAX_SIZE(p)
Definition: decode.h:230
util-unittest.h
TMM_DECODEWINDIVERT
@ TMM_DECODEWINDIVERT
Definition: tm-threads-common.h:64
TmModule_::PktAcqLoop
TmEcode(* PktAcqLoop)(ThreadVars *, void *, void *)
Definition: tm-modules.h:54
TM_ECODE_OK
@ TM_ECODE_OK
Definition: tm-threads-common.h:78
strlcpy
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: util-strlcpyu.c:43
TmModule_::ThreadDeinit
TmEcode(* ThreadDeinit)(ThreadVars *, void *)
Definition: tm-modules.h:49
SC_ERR_WINDIVERT_INVALID_FILTER
@ SC_ERR_WINDIVERT_INVALID_FILTER
Definition: util-error.h:347
PKT_SET_SRC
#define PKT_SET_SRC(p, src_val)
Definition: decode.h:1128
DecodeRegisterPerfCounters
void DecodeRegisterPerfCounters(DecodeThreadVars *dtv, ThreadVars *tv)
Definition: decode.c:478
SET_PKT_LEN
#define SET_PKT_LEN(p, len)
Definition: decode.h:232
util-device.h
util-debug.h
PKT_SRC_WIRE
@ PKT_SRC_WIRE
Definition: decode.h:50
TAILQ_FIRST
#define TAILQ_FIRST(head)
Definition: queue.h:339
PASS
#define PASS
Pass the test.
Definition: util-unittest.h:105
util-error.h
SC_ERR_WINDIVERT_TOOLONG_FILTER
@ SC_ERR_WINDIVERT_TOOLONG_FILTER
Definition: util-error.h:348
SCMutexUnlock
#define SCMutexUnlock(mut)
Definition: threads-debug.h:119
CaptureStatsSetup
void CaptureStatsSetup(ThreadVars *tv, CaptureStats *s)
Definition: decode.c:725
SCEnter
#define SCEnter(...)
Definition: util-debug.h:300
GET_PKT_DATA
#define GET_PKT_DATA(p)
Definition: decode.h:228
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:58
TmModule_::Func
TmEcode(* Func)(ThreadVars *, Packet *, void *)
Definition: tm-modules.h:52
RestoreIfaceOffloading
void RestoreIfaceOffloading(LiveDevice *dev)
Definition: util-ioctl.c:724
LiveDevice_::dev
char * dev
Definition: util-device.h:41
SC_ERR_INVALID_ARGUMENT
@ SC_ERR_INVALID_ARGUMENT
Definition: util-error.h:43
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:282
SC_ERR_SYSCALL
@ SC_ERR_SYSCALL
Definition: util-error.h:80
PacketCallocExtPkt
int PacketCallocExtPkt(Packet *p, int datalen)
Definition: decode.c:195
PacketPoolWait
void PacketPoolWait(void)
Definition: tmqh-packetpool.c:84
SCReturn
#define SCReturn
Definition: util-debug.h:302
IPV6Hdr_
Definition: decode-ipv6.h:32
Packet_
Definition: decode.h:411
TM_FLAG_DECODE_TM
#define TM_FLAG_DECODE_TM
Definition: tm-modules.h:32
tmm_modules
TmModule tmm_modules[TMM_SIZE]
Definition: tm-modules.c:33
DecodeIPV6
int DecodeIPV6(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len)
Definition: decode-ipv6.c:580
GET_PKT_LEN
#define GET_PKT_LEN(p)
Definition: decode.h:227
IPV4_GET_RAW_VER
#define IPV4_GET_RAW_VER(ip4h)
Definition: decode-ipv4.h:94
TmSlot_
Definition: tm-threads.h:52
TmEcode
TmEcode
Definition: tm-threads-common.h:77
source-windivert.h
GetIfaceOffloading
int GetIfaceOffloading(const char *dev, int csum, int other)
output offloading status of the link
Definition: util-ioctl.c:694
IS_TUNNEL_PKT
#define IS_TUNNEL_PKT(p)
Definition: decode.h:874
queue.h
DisableIfaceOffloading
int DisableIfaceOffloading(LiveDevice *dev, int csum, int other)
Definition: util-ioctl.c:707
TmModule_::name
const char * name
Definition: tm-modules.h:44
runmodes.h
SCLogInfo
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:217
SCMutexInit
#define SCMutexInit(mut, mutattrs)
Definition: threads-debug.h:116
TM_FLAG_RECEIVE_TM
#define TM_FLAG_RECEIVE_TM
Definition: tm-modules.h:31
TmModule_
Definition: tm-modules.h:43
IPV4Hdr_
Definition: decode-ipv4.h:71
DecodeThreadVarsFree
void DecodeThreadVarsFree(ThreadVars *tv, DecodeThreadVars *dtv)
Definition: decode.c:638
Packet_::ts
struct timeval ts
Definition: decode.h:454
suricata-common.h
TAILQ_NEXT
#define TAILQ_NEXT(elm, field)
Definition: queue.h:341
ACTION_DROP
#define ACTION_DROP
Definition: action-globals.h:30
Packet_::ext_pkt
uint8_t * ext_pkt
Definition: decode.h:553
SCLogError
#define SCLogError(err_code,...)
Macro used to log ERROR messages.
Definition: util-debug.h:257
TmModule_::ThreadInit
TmEcode(* ThreadInit)(ThreadVars *, const void *, void **)
Definition: tm-modules.h:47
SCStrdup
#define SCStrdup(s)
Definition: util-mem.h:56
CaptureStatsUpdate
void CaptureStatsUpdate(ThreadVars *tv, CaptureStats *s, const Packet *p)
Definition: decode.c:712
TMM_RECEIVEWINDIVERT
@ TMM_RECEIVEWINDIVERT
Definition: tm-threads-common.h:62
tv
ThreadVars * tv
Definition: fuzz_decodepcapfile.c:29
TmModule_::ThreadExitPrintStats
void(* ThreadExitPrintStats)(ThreadVars *, void *)
Definition: tm-modules.h:48
SCLogConfig
struct SCLogConfig_ SCLogConfig
Holds the config state used by the logging api.
Packet_::root
struct Packet_ * root
Definition: decode.h:580
SCLogWarning
#define SCLogWarning(err_code,...)
Macro used to log WARNING messages.
Definition: util-debug.h:244
SCFree
#define SCFree(p)
Definition: util-mem.h:61
DecodeThreadVars_
Structure to hold thread specific data for all decode modules.
Definition: decode.h:625
MAX_PAYLOAD_SIZE
#define MAX_PAYLOAD_SIZE
Definition: decode.h:619
SC_ERR_FATAL
@ SC_ERR_FATAL
Definition: util-error.h:203
util-ioctl.h
FAIL
#define FAIL
Fail a test.
Definition: util-unittest.h:60
DecodeThreadVarsAlloc
DecodeThreadVars * DecodeThreadVarsAlloc(ThreadVars *tv)
Alloc and setup DecodeThreadVars.
Definition: decode.c:619
TAILQ_HEAD
#define TAILQ_HEAD(name, type)
Definition: queue.h:321
GET_PKT_DIRECT_DATA
#define GET_PKT_DIRECT_DATA(p)
Definition: decode.h:229
TimeGet
void TimeGet(struct timeval *tv)
Definition: util-time.c:153
SCReturnCT
#define SCReturnCT(x, type)
Definition: util-debug.h:314
suricata.h
TMM_VERDICTWINDIVERT
@ TMM_VERDICTWINDIVERT
Definition: tm-threads-common.h:63
DecodeIPV4
int DecodeIPV4(ThreadVars *tv, DecodeThreadVars *dtv, Packet *p, const uint8_t *pkt, uint16_t len)
Definition: decode-ipv4.c:517
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
SCReturnInt
#define SCReturnInt(x)
Definition: util-debug.h:304
SCMutexDestroy
#define SCMutexDestroy
Definition: threads-debug.h:120
SCMutex
#define SCMutex
Definition: threads-debug.h:114
PacketGetFromQueueOrAlloc
Packet * PacketGetFromQueueOrAlloc(void)
Get a packet. We try to get a packet from the packetpool first, but if that is empty we alloc a packe...
Definition: decode.c:180
TmModule_::flags
uint8_t flags
Definition: tm-modules.h:70
DecodeUpdatePacketCounters
void DecodeUpdatePacketCounters(ThreadVars *tv, const DecodeThreadVars *dtv, const Packet *p)
Definition: decode.c:585
suricata_ctl_flags
volatile uint8_t suricata_ctl_flags
Definition: suricata.c:197
PACKET_TEST_ACTION
#define PACKET_TEST_ACTION(p, a)
Definition: decode.h:850
TmModuleReceiveWinDivertRegister
void TmModuleReceiveWinDivertRegister(void)
Definition: source-windivert.c:61