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