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