suricata
detect-engine-alert.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2026 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 #include "suricata-common.h"
19 #include "suricata.h"
20 
21 #include "detect.h"
22 #include "detect-parse.h"
23 #include "detect-engine-alert.h"
25 #include "detect-engine-tag.h"
26 
27 #include "decode.h"
28 #include "packet.h"
29 
30 #include "flow.h"
31 #include "flow-private.h"
32 
33 #ifdef QA_SIMULATION
34 #include "util-exception-policy.h"
35 #endif
36 
37 #include "util-profiling.h"
38 #include "util-validate.h"
39 
40 #include "action-globals.h"
41 #include "capture-hooks.h"
42 
43 /** tag signature we use for tag alerts */
44 static Signature g_tag_signature;
45 /** tag packet alert structure for tag alerts */
46 static PacketAlert g_tag_pa;
47 
49 {
50  memset(&g_tag_signature, 0x00, sizeof(g_tag_signature));
51 
52  g_tag_signature.id = TAG_SIG_ID;
53  g_tag_signature.gid = TAG_SIG_GEN;
54  g_tag_signature.iid = TAG_SIG_ID;
55  g_tag_signature.rev = 1;
56  g_tag_signature.prio = 2;
57 
58  memset(&g_tag_pa, 0x00, sizeof(g_tag_pa));
59 
60  g_tag_pa.action = ACTION_ALERT;
61  g_tag_pa.s = &g_tag_signature;
62 }
63 
64 /**
65  * \brief Handle a packet and check if needs a threshold logic
66  * Also apply rule action if necessary.
67  *
68  * \param de_ctx Detection Context
69  * \param sig Signature pointer
70  * \param p Packet structure
71  *
72  * \retval 1 alert is not suppressed
73  * \retval 0 alert is suppressed
74  */
75 static int PacketAlertHandle(const DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
76  const Signature *s, Packet *p, PacketAlert *pa)
77 {
78  SCEnter();
79  int ret = 1;
80  const DetectThresholdData *td = NULL;
81  const SigMatchData *smd;
82 
83  if (!(PacketIsIPv4(p) || PacketIsIPv6(p))) {
84  SCReturnInt(1);
85  }
86 
87  /* handle suppressions first */
88  if (s->sm_arrays[DETECT_SM_LIST_SUPPRESS] != NULL) {
90  smd = NULL;
91  do {
93  if (td != NULL) {
94  SCLogDebug("td %p", td);
95 
96  /* PacketAlertThreshold returns 2 if the alert is suppressed but
97  * we do need to apply rule actions to the packet. */
99  ret = PacketAlertThreshold(de_ctx, det_ctx, td, p, s, pa);
100  if (ret == 0 || ret == 2) {
102  /* It doesn't match threshold, remove it */
103  SCReturnInt(ret);
104  }
106  }
107  } while (smd != NULL);
108  }
109 
110  /* if we're still here, consider thresholding */
111  if (s->sm_arrays[DETECT_SM_LIST_THRESHOLD] != NULL) {
113  smd = NULL;
114  do {
116  if (td != NULL) {
117  SCLogDebug("td %p", td);
118 
119  /* PacketAlertThreshold returns 2 if the alert is suppressed but
120  * we do need to apply rule actions to the packet. */
122  ret = PacketAlertThreshold(de_ctx, det_ctx, td, p, s, pa);
123  if (ret == 0 || ret == 2) {
125  /* It doesn't match threshold, remove it */
126  SCReturnInt(ret);
127  }
129  }
130  } while (smd != NULL);
131  }
132  SCReturnInt(1);
133 }
134 
135 #ifdef UNITTESTS
136 /**
137  * \brief Check if a certain sid alerted, this is used in the test functions
138  *
139  * \param p Packet on which we want to check if the signature alerted or not
140  * \param sid Signature id of the signature that has to be checked for a match
141  *
142  * \retval match A value > 0 on a match; 0 on no match
143  */
144 int PacketAlertCheck(Packet *p, uint32_t sid)
145 {
146  int match = 0;
147 
148  for (uint16_t i = 0; i < p->alerts.cnt; i++) {
149  BUG_ON(p->alerts.alerts[i].s == NULL);
150  if (p->alerts.alerts[i].s->id == sid)
151  match++;
152  }
153 
154  return match;
155 }
156 #endif
157 
158 static inline void RuleActionToFlow(const uint8_t action, Flow *f, const bool fw_rule)
159 {
160  if (action & ACTION_ACCEPT) {
161  DEBUG_VALIDATE_BUG_ON(!fw_rule);
163  SCLogDebug("setting flow action accept");
164  }
165 
166  /* pass:flow can be set if accept:flow is present */
167  if (action & ACTION_PASS) {
169  /* drop or pass already set. First to set wins. */
170  SCLogDebug("not setting %s flow already set to %s",
171  (action & ACTION_PASS) ? "pass" : "drop",
172  (f->flags & FLOW_ACTION_DROP) ? "drop" : "pass");
173  } else {
175  SCLogDebug("setting flow action pass");
176  }
177 
178  // TODO firewall drop:flow should override FLOW_ACTION_PASS
179  } else if (action & (ACTION_DROP | ACTION_REJECT_ANY)) {
180  /* drop:flow from TD rules will override a accept:flow from
181  * firewall rules. */
182  if (f->flags & FLOW_ACTION_ACCEPT) {
184  FlowSetDropAction(f, fw_rule ? FLOW_ACTION_BY_FIREWALL : 0);
185  SCLogDebug("replaced FLOW_ACTION_ACCEPT with FLOW_ACTION_DROP");
186  }
188  /* drop or pass already set. First to set wins. */
189  SCLogDebug("not setting %s flow already set to %s",
190  (action & ACTION_PASS) ? "pass" : "drop",
191  (f->flags & FLOW_ACTION_DROP) ? "drop" : "pass");
192  } else {
193  FlowSetDropAction(f, 0);
194  SCLogDebug("setting flow action drop");
195  }
196  }
197 
198  if (fw_rule) {
200  }
201 }
202 
203 /** \brief Apply action(s) and Set 'drop' sig info,
204  * if applicable
205  * \param p packet
206  * \param s signature -- for id, sig pointer, not actions
207  * \param pa packet alert struct -- match, including actions after thresholding (rate_filter) */
208 static void PacketApplySignatureActions(Packet *p, const Signature *s, const PacketAlert *pa)
209 {
210  SCLogDebug("packet %" PRIu64 ", sid %u: action %02x alert_flags %02x", PcapPacketCntGet(p),
211  s->id, pa->action, pa->flags);
212 
213  const bool is_fw_rule = s->flags & SIG_FLAG_FIREWALL ? true : false;
214  /* REJECT also sets ACTION_DROP, just make it more visible with this check */
215  if (pa->action & ACTION_DROP_REJECT) {
216  uint8_t drop_reason = is_fw_rule ? PKT_DROP_REASON_FW_RULES : PKT_DROP_REASON_RULES;
217  if (is_fw_rule) {
220  } else if (s->detect_table == DETECT_TABLE_PACKET_PRE_FLOW) {
221  drop_reason = PKT_DROP_REASON_FW_FLOW_PRE_HOOK;
222  }
223  }
224  /* PacketDrop will update the packet action, too */
225  PacketDrop(p, pa->action,
228  : drop_reason);
229  SCLogDebug("[packet %p][DROP sid %u]", p, s->id);
230 
231  if (p->alerts.drop.action == 0) {
232  p->alerts.drop.iid = s->iid;
233  p->alerts.drop.action = pa->action;
234  p->alerts.drop.s = (Signature *)s;
235  }
236  if ((p->flow != NULL) && (pa->flags & PACKET_ALERT_FLAG_APPLY_ACTION_TO_FLOW)) {
237  RuleActionToFlow(pa->action, p->flow, is_fw_rule);
238  }
239 
241  } else {
242  if (pa->action & ACTION_ACCEPT) {
243  const enum ActionScope as = pa->s->action_scope;
244  SCLogDebug("packet %" PRIu64 ": ACCEPT %u as:%u flags:%02x", PcapPacketCntGet(p), s->id,
245  as, pa->flags);
246  if (as == ACTION_SCOPE_PACKET || as == ACTION_SCOPE_FLOW ||
248  SCLogDebug("packet %" PRIu64 ": sid:%u ACCEPT", PcapPacketCntGet(p), s->id);
249  p->action |= ACTION_ACCEPT;
250  }
251  } else if (pa->action & (ACTION_ALERT | ACTION_CONFIG)) {
252  // nothing to set in the packet
253  } else if (pa->action & ACTION_PASS) {
254  SCLogDebug("[packet %p][PASS sid %u]", p, s->id);
255  // nothing to set in the packet
256  } else if (pa->action != 0) {
257  DEBUG_VALIDATE_BUG_ON(1); // should be unreachable
258  }
259 
260  if ((pa->action & (ACTION_PASS | ACTION_ACCEPT)) && (p->flow != NULL) &&
262  RuleActionToFlow(pa->action, p->flow, is_fw_rule);
263  }
264  }
265 }
266 
268 {
269  det_ctx->alert_queue_size = 0;
270  det_ctx->alert_queue = SCCalloc(packet_alert_max, sizeof(PacketAlert));
271  if (det_ctx->alert_queue == NULL) {
272  FatalError("failed to allocate %" PRIu64 " bytes for the alert queue",
273  (uint64_t)(packet_alert_max * sizeof(PacketAlert)));
274  }
276  SCLogDebug("alert queue initialized to %u elements (%" PRIu64 " bytes)", packet_alert_max,
277  (uint64_t)(packet_alert_max * sizeof(PacketAlert)));
278 }
279 
281 {
282  SCFree(det_ctx->alert_queue);
283  det_ctx->alert_queue_capacity = 0;
284 }
285 
286 static inline uint16_t AlertQueueExpandDo(DetectEngineThreadCtx *det_ctx, uint16_t new_cap)
287 {
288  DEBUG_VALIDATE_BUG_ON(det_ctx->alert_queue_capacity >= new_cap);
289 
290  void *tmp_queue = SCRealloc(det_ctx->alert_queue, new_cap * sizeof(PacketAlert));
291  if (unlikely(tmp_queue == NULL)) {
292  /* queue capacity didn't change */
293  return det_ctx->alert_queue_capacity;
294  }
295  det_ctx->alert_queue = tmp_queue;
296  det_ctx->alert_queue_capacity = new_cap;
297  SCLogDebug("Alert queue size expanded: %u elements, bytes: %" PRIuMAX "",
298  det_ctx->alert_queue_capacity, (uintmax_t)(new_cap * sizeof(PacketAlert)));
299  return new_cap;
300 }
301 
302 /** \internal
303  * \retval the new capacity
304  */
305 static uint16_t AlertQueueExpand(DetectEngineThreadCtx *det_ctx)
306 {
307 #ifdef QA_SIMULATION
308  if (unlikely(g_eps_is_alert_queue_fail_mode))
309  return det_ctx->alert_queue_capacity;
310 #endif
311  if (det_ctx->alert_queue_capacity == UINT16_MAX) {
312  return det_ctx->alert_queue_capacity;
313  }
314 
315  uint16_t new_cap;
316  if (det_ctx->alert_queue_capacity > (UINT16_MAX / 2)) {
317  new_cap = UINT16_MAX;
318  } else {
319  new_cap = det_ctx->alert_queue_capacity * 2;
320  }
321  return AlertQueueExpandDo(det_ctx, new_cap);
322 }
323 
324 static inline int PacketAlertSetContext(
325  DetectEngineThreadCtx *det_ctx, PacketAlert *pa, const Signature *s)
326 {
327  pa->json_info = NULL;
328  if (det_ctx->json_content_len) {
329  /* We have some JSON attached in the current detection so let's try
330  to see if some need to be used for current signature. */
331  struct PacketContextData *current_json = NULL;
332  for (uint8_t i = 0; i < det_ctx->json_content_len; i++) {
333  if (s == det_ctx->json_content[i].id) {
334  SCLogDebug("signature %p, content index %u", s, i);
335  if (current_json == NULL) {
336  /* Allocate the first one */
337  current_json = SCCalloc(1, sizeof(struct PacketContextData));
338  if (current_json == NULL) {
339  /* Allocation error, let's return now */
340  return -1;
341  }
342  if (pa->json_info == NULL) {
343  /* If this is the first one, set it */
344  pa->json_info = current_json;
345  }
346  current_json->next = NULL;
347  } else {
348  /* Allocate the next one */
349  struct PacketContextData *next_json =
350  SCCalloc(1, sizeof(struct PacketContextData));
351  if (next_json) {
352  current_json->next = next_json;
353  current_json = next_json;
354  current_json->next = NULL;
355  } else {
356  /* Allocation error, let's return now */
357  return -1;
358  }
359  }
360  current_json->json_string = SCStrdup(det_ctx->json_content[i].json_content);
361  if (current_json->json_string == NULL) {
362  return -1;
363  }
364  SCLogDebug("json content %u, value '%s' (%p)", (unsigned int)i,
365  current_json->json_string, s);
366  }
367  }
368  }
369 
370  return 0;
371 }
372 
373 /** \internal
374  */
375 static inline PacketAlert PacketAlertSet(DetectEngineThreadCtx *det_ctx, const Signature *s,
376  uint64_t tx_id, const uint8_t sub_state, uint8_t alert_flags)
377 {
378  PacketAlert pa;
379  pa.iid = s->iid;
380  pa.action = s->action;
381  pa.s = (Signature *)s;
382  pa.flags = alert_flags;
383  /* Set tx_id if the frame has it */
384  pa.tx_id = tx_id;
385  pa.sub_state = sub_state;
386  pa.frame_id = (alert_flags & PACKET_ALERT_FLAG_FRAME) ? det_ctx->frame_id : 0;
387  PacketAlertSetContext(det_ctx, &pa, s);
388  return pa;
389 }
390 
391 /**
392  * \brief Append signature to local packet alert queue for later preprocessing
393  */
394 static void AlertQueueAppend(DetectEngineThreadCtx *det_ctx, const Signature *s, Packet *p,
395  const uint64_t tx_id, const uint8_t sub_state, uint8_t alert_flags)
396 {
397  /* first time we see a drop action signature, set that in the packet */
398  /* we do that even before inserting into the queue, so we save it even if appending fails */
399  if (p->alerts.drop.action == 0 && s->action & ACTION_DROP) {
400  p->alerts.drop = PacketAlertSet(det_ctx, s, tx_id, sub_state, alert_flags);
401  SCLogDebug("sid %u: set PacketAlert drop action. s->iid %" PRIu32 "", s->id, s->iid);
402  }
403 
404  uint16_t pos = det_ctx->alert_queue_size;
405  if (pos == det_ctx->alert_queue_capacity) {
406  /* we must grow the alert queue */
407  if (pos == AlertQueueExpand(det_ctx)) {
408  /* this means we failed to expand the queue */
409  p->alerts.discarded++;
410  return;
411  }
412  }
413  det_ctx->alert_queue[pos] = PacketAlertSet(det_ctx, s, tx_id, sub_state, alert_flags);
414 
415  SCLogDebug("packet %" PRIu64 ": appending sid %" PRIu32 ", s->iid %" PRIu32 " to alert queue",
416  PcapPacketCntGet(p), s->id, s->iid);
417  det_ctx->alert_queue_size++;
418 }
419 
420 /**
421  * \brief Append signature to local packet alert queue for later preprocessing
422  */
424  uint64_t tx_id, uint8_t sub_state, uint8_t alert_flags)
425 {
427  return AlertQueueAppend(det_ctx, s, p, tx_id, sub_state, alert_flags);
428 }
429 
430 /**
431  * \brief Append signature to local packet alert queue for later preprocessing
432  * This does not automatically set PACKET_ALERT_FLAG_STATE_MATCH as this
433  * comes from the packet alert path.
434  */
436  uint64_t tx_id, const uint8_t sub_state, uint8_t alert_flags)
437 {
438  alert_flags |= PACKET_ALERT_FLAG_TX;
439  return AlertQueueAppend(det_ctx, s, p, tx_id, sub_state, alert_flags);
440 }
441 
442 /**
443  * \brief Append signature to local packet alert queue for later preprocessing
444  */
446  DetectEngineThreadCtx *det_ctx, const Signature *s, Packet *p, uint8_t alert_flags)
447 {
448  return AlertQueueAppend(det_ctx, s, p, PACKET_ALERT_NOTX, 0, alert_flags);
449 }
450 
451 /** \internal
452  * \brief sort helper for sorting alerts by priority
453  *
454  * Sorting is done first based on num and then using tx_id, if nums are equal.
455  * The Signature::num field is set based on internal priority. Higher priority
456  * rules have lower nums.
457  */
458 static int AlertQueueSortHelperFirewall(const void *a, const void *b)
459 {
460  const PacketAlert *pa0 = a;
461  const PacketAlert *pa1 = b;
462  if (pa0->s->detect_table == pa1->s->detect_table) {
463  if (pa1->iid == pa0->iid) {
464  if (pa1->tx_id == PACKET_ALERT_NOTX) {
465  return -1;
466  } else if (pa0->tx_id == PACKET_ALERT_NOTX) {
467  return 1;
468  }
469  return pa0->tx_id < pa1->tx_id ? 1 : -1;
470  } else {
471  return pa0->iid < pa1->iid ? -1 : 1;
472  }
473  }
474  return pa0->s->detect_table < pa1->s->detect_table ? -1 : 1;
475 }
476 
477 static int AlertQueueSortHelper(const void *a, const void *b)
478 {
479  const PacketAlert *pa0 = a;
480  const PacketAlert *pa1 = b;
481  if (pa1->iid == pa0->iid) {
482  if (pa1->tx_id == PACKET_ALERT_NOTX) {
483  return -1;
484  } else if (pa0->tx_id == PACKET_ALERT_NOTX) {
485  return 1;
486  }
487  return pa0->tx_id < pa1->tx_id ? 1 : -1;
488  } else {
489  return pa0->iid < pa1->iid ? -1 : 1;
490  }
491 }
492 
493 /** \internal
494  * \brief Check if Signature action should be applied to flow and apply
495  *
496  */
497 static inline void FlowApplySignatureActions(
498  Packet *p, PacketAlert *pa, const Signature *s, uint8_t alert_flags)
499 {
500  /* For DROP and PASS sigs we need to apply the action to the flow if
501  * - sig is IP or PD only
502  * - match is in applayer
503  * - match is in stream */
504  if (pa->action & (ACTION_DROP | ACTION_PASS | ACTION_ACCEPT)) {
507 
508  if (s->action_scope == ACTION_SCOPE_FLOW) {
510  } else if (s->action_scope == ACTION_SCOPE_AUTO) {
511  enum SignaturePropertyFlowAction flow_action =
513  if (flow_action == SIG_PROP_FLOW_ACTION_FLOW) {
515  } else if (flow_action == SIG_PROP_FLOW_ACTION_FLOW_IF_STATEFUL) {
518  }
519  }
520  }
521 
523  SCLogDebug("packet %" PRIu64 " sid %u action %02x alert_flags %02x (set "
524  "PACKET_ALERT_FLAG_APPLY_ACTION_TO_FLOW)",
525  PcapPacketCntGet(p), s->id, s->action, pa->flags);
526  }
527  }
528 }
529 
530 /** \internal
531  * \brief handle immediate actions for a firewall rule match
532  *
533  * Delayed action (accept) is handled after TD has also run, as TD drop
534  * can overrule a FW accept. So returning `accept` here means "will accept if TD agrees".
535  *
536  * \retval pol firewall policy with action that is (drop) or should possibly be (accept)
537  * applied to the packet and flow.
538  */
539 static struct DetectFirewallPolicy HandleFirewallRule(
541 {
542  const Signature *s = pa->s;
543  struct DetectFirewallPolicy pol = { .action = 0, .action_scope = 0 };
544  int res = PacketAlertHandle(de_ctx, det_ctx, s, p, pa);
545  SCLogDebug("packet %" PRIu64 ": fw sid %u: res %d", PcapPacketCntGet(p), s->id, res);
546  if (res > 0) {
547  /* Now, if we have an alert, we have to check if we want
548  * to tag this session or src/dst host */
549  if (s->sm_arrays[DETECT_SM_LIST_TMATCH] != NULL) {
552  while (1) {
553  /* tags are set only for alerts */
555  sigmatch_table[smd->type].Match(det_ctx, p, (Signature *)s, smd->ctx);
556  KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
557  if (smd->is_last)
558  break;
559  smd++;
560  }
561  }
562  /* if this is a terminating action, pass the action to the caller. */
563  if (s->action_scope != ACTION_SCOPE_HOOK ||
565  pol.action = s->action;
566  pol.action_scope = s->action_scope;
567  if (pol.action & ACTION_DROP) {
568  uint8_t drop_reason = PKT_DROP_REASON_FW_RULES;
571  } else if (s->detect_table == DETECT_TABLE_PACKET_PRE_FLOW) {
572  drop_reason = PKT_DROP_REASON_FW_FLOW_PRE_HOOK;
573  }
574  PacketDrop(p, pol.action, drop_reason);
575  if (p->flow && pol.action_scope == ACTION_SCOPE_FLOW) {
576  FlowSetDropAction(p->flow, FLOW_ACTION_BY_FIREWALL);
577  SCLogDebug("packet %" PRIu64 ": FLOW_ACTION_DROP set by firewall by sid %u",
578  PcapPacketCntGet(p), s->id);
579  }
580  }
581  if (pol.action & ACTION_PASS) {
582  if (p->flow && pol.action_scope == ACTION_SCOPE_FLOW) {
584  SCLogDebug("packet %" PRIu64 ": FLOW_ACTION_PASS set by firewall by sid %u",
585  PcapPacketCntGet(p), s->id);
586  }
587  }
588  }
589  /* add the alert for logging if required. */
590  if (s->action & ACTION_ALERT) {
591  if (p->alerts.cnt < packet_alert_max) {
592  p->alerts.alerts[p->alerts.cnt++] = *pa;
593  } else {
595  }
596  }
597  }
598  return pol;
599 }
600 
601 /*
602  * Queue order after sorting:
603  *
604  * Firewall use case: rules are sorted by Signature::detect_table, Signature::iid (which reflects
605  * order in the rule file(s)) This means:
606  * - pre_flow
607  * - pre_stream
608  * - packet:filter (firewall)
609  * - packet:td (IDS/IPS rules)
610  * - app:filter (firewall)
611  * - app:td (IDS/IPS rules)
612  *
613  * Firewall DROPs are immediate.
614  * Firewall ACCEPTs depend on TD not dropping.
615  * Firewall rules are not affected by PASS.
616  * TD rules are affected by PASS, both set by Firewall and TD rules.
617  *
618  * Non-Firewall use case: rules are sorted by Signature::iid (which reflect order based on flowbits,
619  * action-order, priority, etc)
620  */
621 static inline void PacketAlertFinalizeProcessQueue(
623 {
624  const bool have_fw_rules = EngineModeIsFirewall();
625 
626  if (det_ctx->alert_queue_size > 1) {
627  /* sort the alert queue before thresholding and appending to Packet */
628  qsort(det_ctx->alert_queue, det_ctx->alert_queue_size, sizeof(PacketAlert),
629  have_fw_rules ? AlertQueueSortHelperFirewall : AlertQueueSortHelper);
630  }
631 
632  bool alerted = false;
633  bool dropped = false;
634  bool skip_td = false;
635  bool skip_fw = false;
636  bool fw_accept_packet = false; // same as skip_fw?
637  bool fw_accept_flow = false;
638 
639 #ifdef DEBUG
640  SCLogDebug("packet %" PRIu64 ": starting alert event queue", PcapPacketCntGet(p));
641  for (uint16_t x = 0; x < det_ctx->alert_queue_size; x++) {
642  const PacketAlert *pa = &det_ctx->alert_queue[x];
643  const Signature *s = pa->s;
644  SCLogDebug("(list) %s sid %u: action %02x scope %u iid %u detect_table %u",
645  (s->flags & SIG_FLAG_FIREWALL) ? "fw" : "td", s->id, s->action, s->action_scope,
646  s->iid, s->detect_table);
647  }
648 #endif /* DEBUG */
649  uint8_t skip_table_id = 0;
650  bool skip_table = false;
651  for (uint16_t i = 0; i < det_ctx->alert_queue_size; i++) {
652  PacketAlert *pa = &det_ctx->alert_queue[i];
653  const Signature *s = pa->s;
654 
655  if (s->flags & SIG_FLAG_FIREWALL) {
656  if (skip_fw) {
657  continue;
658  }
659  /* skip for this table, but not for later. Mostly for showing
660  * alerts for both packet:filter and app:filter together. */
661  if (skip_table) {
662  if (s->detect_table <= skip_table_id)
663  continue;
664  skip_table = false;
665  }
666 
667  if (dropped) {
668  SCLogDebug("Skipping firewall signature after a drop.");
669  continue;
670  }
671 
672  const uint16_t pre_alert_cnt = p->alerts.cnt;
673  struct DetectFirewallPolicy pol = HandleFirewallRule(de_ctx, det_ctx, p, pa);
674  /* drop is immediate */
675  if (pol.action & ACTION_DROP) {
676  dropped = true;
677  } else if (pol.action & ACTION_ACCEPT) {
678  SCLogDebug("fw sid %u setting skip_fw for action %02x scope %s", s->id, pol.action,
680  /* see if we want to skip other alerts for this table */
681  if (pol.action_scope == ACTION_SCOPE_HOOK) {
682  skip_table_id = s->detect_table;
683  skip_table = true;
684  } else {
685  skip_fw = true;
686  }
687  fw_accept_packet = true;
688  if (pol.action_scope == ACTION_SCOPE_FLOW)
689  fw_accept_flow = true;
690  }
691  if (pol.action & ACTION_PASS) {
692  skip_td = true;
693  }
694  if (pre_alert_cnt < p->alerts.cnt)
695  alerted = true;
696  if (dropped)
697  goto fw_dropped;
698 
699  continue;
700  }
701 
702  SCLogDebug("sid: %u, action %02x, firewall? %s", s->id, pa->action,
704 
705  /* if a firewall rule told us to skip, we don't count the skipped
706  * alerts. */
707  if (have_fw_rules && skip_td) {
708  continue;
709  }
710 
711  int res = PacketAlertHandle(de_ctx, det_ctx, s, p, pa);
712  SCLogDebug("sid %u: res %d", pa->s->id, res);
713  if (res > 0) {
714  /* Now, if we have an alert, we have to check if we want
715  * to tag this session or src/dst host */
716  if (s->sm_arrays[DETECT_SM_LIST_TMATCH] != NULL) {
719  while (1) {
720  /* tags are set only for alerts */
722  sigmatch_table[smd->type].Match(det_ctx, p, (Signature *)s, smd->ctx);
723  KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
724  if (smd->is_last)
725  break;
726  smd++;
727  }
728  }
729 
730  bool skip_action_set = false;
731  if ((p->action & (ACTION_DROP | ACTION_ACCEPT)) != 0) {
732  if (p->action & ACTION_DROP) {
733  if (pa->action & (ACTION_PASS | ACTION_ACCEPT)) {
734  skip_action_set = true;
735  }
736  } else {
737  if (pa->action & (ACTION_DROP)) {
738  skip_action_set = true;
739  }
740  }
741  }
742  SCLogDebug("packet %" PRIu64 ": i:%u sid:%u skip_action_set %s", PcapPacketCntGet(p), i,
743  s->id, BOOL2STR(skip_action_set));
744  if (!skip_action_set) {
745  /* set actions on the flow */
746  FlowApplySignatureActions(p, pa, s, pa->flags);
747 
748  SCLogDebug("sid %u: action %02x (DROP %s, PASS %s)", pa->s->id, pa->action,
750 
751  /* set actions on packet */
752  PacketApplySignatureActions(p, s, pa);
753  }
754  }
755 
756  /* Thresholding removes this alert */
757  if (res == 0 || res == 2 || (s->action & (ACTION_ALERT | ACTION_PASS)) == 0) {
758  SCLogDebug("sid:%u: skipping alert because of thresholding (res=%d) or NOALERT (%02x)",
759  s->id, res, s->action);
760  /* we will not copy this to the AlertQueue */
761  p->alerts.suppressed++;
762  } else if (p->alerts.cnt < packet_alert_max) {
763  p->alerts.alerts[p->alerts.cnt++] = *pa;
764  SCLogDebug("appending sid %" PRIu32 " alert to Packet::alerts at pos %u; action:%02x",
765  s->id, i, pa->action);
766 
767  if (pa->action & ACTION_ALERT) {
768  alerted = true;
769  }
770  /* pass with alert, we're done. Alert is logged. */
771  if (pa->action & ACTION_PASS) {
772  SCLogDebug("sid:%u: is a pass rule, so break out of loop", s->id);
773  if (!have_fw_rules)
774  break;
775  SCLogDebug("skipping td");
776  skip_td = true;
777  continue;
778  }
779  } else {
780  p->alerts.discarded++;
781  }
782 
783  if (s->action & ACTION_DROP) {
784  dropped = true;
785  }
786  }
787 
788 fw_dropped:
789  /* after threat detection has been handled, see if the fw intended to accept (drop is handled
790  * immediately by the fw), as fw accept can be overruled by td drop. */
791  if (have_fw_rules) {
792  if (p->action & ACTION_DROP) {
793  SCLogDebug("packet %" PRIu64 ": dropped by TD", PcapPacketCntGet(p));
794  } else if (fw_accept_packet) {
795  p->action |= ACTION_ACCEPT;
796  if (p->flow && fw_accept_flow) {
798  SCLogDebug("packet %" PRIu64 ": FLOW_ACTION_ACCEPT set from firewall",
800  }
801  }
802  }
803 
804  /* Set flag on flow to indicate that it has alerts. We use the bool to
805  * exclude pass-only entries in `Packet::alerts` */
806  if (alerted && p->flow != NULL) {
807  if (!FlowHasAlerts(p->flow)) {
810  }
811  }
812 
813  /* Notify capture layer about packets with real alerts (not pass-only),
814  * so capture impl can update per-capture context (e.g. pcap-file alert counts). */
815  if (alerted) {
817  }
818 }
819 
820 /**
821  * \brief Check the threshold of the sigs that match, set actions, break on pass action
822  * This function iterate the packet alerts array, removing those that didn't match
823  * the threshold, and those that match after a signature with the action "pass".
824  * The array is sorted by action priority/order
825  * \param de_ctx detection engine context
826  * \param det_ctx detection engine thread context
827  * \param p pointer to the packet
828  */
830 {
831  SCEnter();
832 
833  if (det_ctx->alert_queue_size > 0) {
834  PacketAlertFinalizeProcessQueue(de_ctx, det_ctx, p);
835  if (det_ctx->json_content_len)
837  }
838 
839  /* At this point, we should have all the new alerts. Now check the tag
840  * keyword context for sessions and hosts */
841  if (!(p->flags & PKT_PSEUDO_STREAM_END))
842  TagHandlePacket(de_ctx, det_ctx, p);
843 }
844 
845 #ifdef UNITTESTS
847 #endif
PacketCheckAction
bool PacketCheckAction(const Packet *p, const uint8_t a)
Definition: packet.c:50
PKT_DROP_REASON_RULES_THRESHOLD
@ PKT_DROP_REASON_RULES_THRESHOLD
Definition: decode.h:394
DetectEngineThreadCtx_::alert_queue_size
uint16_t alert_queue_size
Definition: detect.h:1401
FlowSetHasAlertsFlag
void FlowSetHasAlertsFlag(Flow *f)
Set flag to indicate that flow has alerts.
Definition: flow.c:151
PacketAlerts_::firewall_discarded
uint16_t firewall_discarded
Definition: decode.h:291
FLOW_ACTION_BY_FIREWALL
#define FLOW_ACTION_BY_FIREWALL
Definition: flow.h:125
PacketAlert_::s
const struct Signature_ * s
Definition: decode.h:254
AlertQueueFree
void AlertQueueFree(DetectEngineThreadCtx *det_ctx)
Definition: detect-engine-alert.c:280
Flow_::flags
uint64_t flags
Definition: flow.h:408
sigmatch_table
SigTableElmt * sigmatch_table
Definition: detect-parse.c:78
PACKET_ALERT_FLAG_STATE_MATCH
#define PACKET_ALERT_FLAG_STATE_MATCH
Definition: decode.h:270
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
ACTION_PASS
#define ACTION_PASS
Definition: action-globals.h:34
PKT_DROP_REASON_FW_RULES
@ PKT_DROP_REASON_FW_RULES
Definition: decode.h:407
KEYWORD_PROFILING_SET_LIST
#define KEYWORD_PROFILING_SET_LIST(ctx, list)
Definition: util-profiling.h:46
PcapPacketCntGet
uint64_t PcapPacketCntGet(const Packet *p)
Definition: decode.c:1193
DETECT_TABLE_PACKET_PRE_STREAM
@ DETECT_TABLE_PACKET_PRE_STREAM
Definition: detect.h:567
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:282
SigMatchData_::is_last
bool is_last
Definition: detect.h:371
ActionScopeToString
const char * ActionScopeToString(enum ActionScope s)
Definition: detect-parse.c:4191
PacketAlerts_::cnt
uint16_t cnt
Definition: decode.h:289
PacketAlertCheck
int PacketAlertCheck(Packet *p, uint32_t sid)
Check if a certain sid alerted, this is used in the test functions.
Definition: detect-engine-alert.c:144
SigMatchData_::ctx
SigMatchCtx * ctx
Definition: detect.h:372
action-globals.h
Packet_::flags
uint32_t flags
Definition: decode.h:562
Packet_::action
uint8_t action
Definition: decode.h:624
flow-private.h
Flow_
Flow data structure.
Definition: flow.h:359
DETECT_SM_LIST_THRESHOLD
@ DETECT_SM_LIST_THRESHOLD
Definition: detect.h:134
TAG_SIG_ID
#define TAG_SIG_ID
Definition: detect-engine-tag.h:42
DetectEngineCtx_
main detection engine ctx
Definition: detect.h:995
PacketAlerts_::alerts
PacketAlert * alerts
Definition: decode.h:293
ACTION_SCOPE_FLOW
@ ACTION_SCOPE_FLOW
Definition: action-globals.h:45
ACTION_REJECT_ANY
#define ACTION_REJECT_ANY
Definition: action-globals.h:38
PacketAlerts_::drop
PacketAlert drop
Definition: decode.h:296
CaptureHooksOnPacketWithAlerts
void CaptureHooksOnPacketWithAlerts(const Packet *p)
Definition: capture-hooks.c:53
ACTION_DROP_REJECT
#define ACTION_DROP_REJECT
Definition: action-globals.h:40
FLOW_ACTION_DROP
#define FLOW_ACTION_DROP
Definition: flow.h:69
p
Packet * p
Definition: fuzz_dataset.c:30
Signature_::sm_arrays
SigMatchData * sm_arrays[DETECT_SM_LIST_MAX]
Definition: detect.h:759
EngineModeIsFirewall
bool EngineModeIsFirewall(void)
Definition: suricata.c:240
SigMatchData_
Data needed for Match()
Definition: detect.h:369
KEYWORD_PROFILING_START
#define KEYWORD_PROFILING_START
Definition: util-profiling.h:50
SigMatchData_::type
uint16_t type
Definition: detect.h:370
DetectFirewallPolicy::action
uint8_t action
Definition: detect.h:947
Packet_::alerts
PacketAlerts alerts
Definition: decode.h:637
KEYWORD_PROFILING_END
#define KEYWORD_PROFILING_END(ctx, type, m)
Definition: util-profiling.h:64
PacketAlert_::tx_id
uint64_t tx_id
Definition: decode.h:255
PacketAlert_::action
uint8_t action
Definition: decode.h:251
SIG_FLAG_FIREWALL
#define SIG_FLAG_FIREWALL
Definition: detect.h:249
AlertQueueInit
void AlertQueueInit(DetectEngineThreadCtx *det_ctx)
Definition: detect-engine-alert.c:267
Signature_::gid
uint32_t gid
Definition: detect.h:742
FLOW_ACTION_PASS
#define FLOW_ACTION_PASS
Definition: flow.h:116
SignaturePropertyFlowAction
SignaturePropertyFlowAction
Definition: detect.h:84
capture-hooks.h
PacketAlert_::json_info
struct PacketContextData * json_info
Definition: decode.h:257
decode.h
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:22
DetectEngineThreadCtx_
Definition: detect.h:1316
DETECT_THRESHOLD
@ DETECT_THRESHOLD
Definition: detect-engine-register.h:67
AlertQueueAppendAppTxFromPacket
void AlertQueueAppendAppTxFromPacket(DetectEngineThreadCtx *det_ctx, const Signature *s, Packet *p, uint64_t tx_id, const uint8_t sub_state, uint8_t alert_flags)
Append signature to local packet alert queue for later preprocessing This does not automatically set ...
Definition: detect-engine-alert.c:435
PKT_PSEUDO_STREAM_END
#define PKT_PSEUDO_STREAM_END
Definition: decode.h:1313
util-exception-policy.h
PKT_DROP_REASON_FW_FLOW_PRE_HOOK
@ PKT_DROP_REASON_FW_FLOW_PRE_HOOK
Definition: decode.h:411
BOOL2STR
#define BOOL2STR(b)
Definition: util-debug.h:542
SCEnter
#define SCEnter(...)
Definition: util-debug.h:284
detect.h
PacketContextData
Definition: decode.h:242
DETECT_TABLE_PACKET_PRE_FLOW
@ DETECT_TABLE_PACKET_PRE_FLOW
Definition: detect.h:566
PacketAlerts_::discarded
uint16_t discarded
Definition: decode.h:290
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:322
detect-engine-tag.h
PKT_DROP_REASON_RULES
@ PKT_DROP_REASON_RULES
Definition: decode.h:393
Signature_::action
uint8_t action
Definition: detect.h:707
util-profiling.h
PACKET_ALERT_FLAG_APPLY_ACTION_TO_FLOW
#define PACKET_ALERT_FLAG_APPLY_ACTION_TO_FLOW
Definition: decode.h:268
Signature_::flags
uint32_t flags
Definition: detect.h:693
PKT_ALERT_CTX_USED
#define PKT_ALERT_CTX_USED
Definition: decode.h:1300
ACTION_ALERT
#define ACTION_ALERT
Definition: action-globals.h:29
Packet_
Definition: decode.h:516
DetectEngineThreadCtx_::frame_id
int64_t frame_id
Definition: detect.h:1393
ACTION_SCOPE_AUTO
@ ACTION_SCOPE_AUTO
Definition: action-globals.h:43
detect-engine-alert.h
DetectEngineThreadCtx_::alert_queue_capacity
uint16_t alert_queue_capacity
Definition: detect.h:1402
SigTableElmt_::Match
int(* Match)(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *)
Definition: detect.h:1504
PacketAlert_::iid
SigIntId iid
Definition: decode.h:250
signature_properties
const struct SignatureProperties signature_properties[SIG_TYPE_MAX]
Definition: detect-engine.c:118
PACKET_ALERT_NOTX
#define PACKET_ALERT_NOTX
Definition: detect.h:56
SIG_TYPE_NOT_SET
@ SIG_TYPE_NOT_SET
Definition: detect.h:66
PACKET_ALERT_FLAG_APPLY_ACTION_TO_PACKET
#define PACKET_ALERT_FLAG_APPLY_ACTION_TO_PACKET
Definition: decode.h:282
PacketAlertFinalize
void PacketAlertFinalize(const DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p)
Check the threshold of the sigs that match, set actions, break on pass action This function iterate t...
Definition: detect-engine-alert.c:829
PACKET_ALERT_FLAG_STREAM_MATCH
#define PACKET_ALERT_FLAG_STREAM_MATCH
Definition: decode.h:272
TagHandlePacket
void TagHandlePacket(const DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p)
Search tags for src and dst. Update entries of the tag, remove if necessary.
Definition: detect-engine-tag.c:520
PACKET_ALERT_FLAG_FRAME
#define PACKET_ALERT_FLAG_FRAME
Definition: decode.h:278
SCRealloc
#define SCRealloc(ptr, sz)
Definition: util-mem.h:50
PacketAlert_::frame_id
int64_t frame_id
Definition: decode.h:256
PacketAlert_::flags
uint8_t flags
Definition: decode.h:252
PacketAlert_::sub_state
uint8_t sub_state
Definition: decode.h:253
Packet_::flow
struct Flow_ * flow
Definition: decode.h:564
suricata-common.h
SIG_PROP_FLOW_ACTION_FLOW_IF_STATEFUL
@ SIG_PROP_FLOW_ACTION_FLOW_IF_STATEFUL
Definition: detect.h:87
ActionScope
ActionScope
Definition: action-globals.h:42
DetectThresholdData_
Definition: detect-threshold.h:62
ACTION_SCOPE_HOOK
@ ACTION_SCOPE_HOOK
Definition: action-globals.h:46
Signature_::action_scope
uint8_t action_scope
Definition: detect.h:714
packet.h
ACTION_DROP
#define ACTION_DROP
Definition: action-globals.h:30
Signature_::rev
uint32_t rev
Definition: detect.h:743
SCStrdup
#define SCStrdup(s)
Definition: util-mem.h:56
FatalError
#define FatalError(...)
Definition: util-debug.h:517
ACTION_CONFIG
#define ACTION_CONFIG
Definition: action-globals.h:35
PacketContextData::next
struct PacketContextData * next
Definition: decode.h:244
DETECT_SM_LIST_TMATCH
@ DETECT_SM_LIST_TMATCH
Definition: detect.h:130
PKT_DROP_REASON_FW_STREAM_PRE_HOOK
@ PKT_DROP_REASON_FW_STREAM_PRE_HOOK
Definition: decode.h:410
SIG_TYPE_MAX
@ SIG_TYPE_MAX
Definition: detect.h:80
Signature_::prio
int prio
Definition: detect.h:744
AlertQueueAppendPacket
void AlertQueueAppendPacket(DetectEngineThreadCtx *det_ctx, const Signature *s, Packet *p, uint8_t alert_flags)
Append signature to local packet alert queue for later preprocessing.
Definition: detect-engine-alert.c:445
SigGetThresholdTypeIter
const DetectThresholdData * SigGetThresholdTypeIter(const Signature *sig, const SigMatchData **psm, int list)
Return next DetectThresholdData for signature.
Definition: detect-engine-threshold.c:750
FLOW_ACTION_ACCEPT
#define FLOW_ACTION_ACCEPT
Definition: flow.h:63
util-validate.h
DetectEngineThreadCtx_::alert_queue
PacketAlert * alert_queue
Definition: detect.h:1403
PACKET_ALERT_FLAG_RATE_FILTER_MODIFIED
#define PACKET_ALERT_FLAG_RATE_FILTER_MODIFIED
Definition: decode.h:276
DetectEngineThreadCtx_::json_content
SigJsonContent * json_content
Definition: detect.h:1353
PacketAlerts_::suppressed
uint16_t suppressed
Definition: decode.h:292
DetectFirewallPolicy
Definition: detect.h:946
Signature_::iid
SigIntId iid
Definition: detect.h:704
SCFree
#define SCFree(p)
Definition: util-mem.h:61
detect-engine-alert.c
Signature_::id
uint32_t id
Definition: detect.h:741
ACTION_SCOPE_PACKET
@ ACTION_SCOPE_PACKET
Definition: action-globals.h:44
detect-parse.h
Signature_
Signature container.
Definition: detect.h:692
PACKET_ALERT_FLAG_TX
#define PACKET_ALERT_FLAG_TX
Definition: decode.h:274
PacketAlertTagInit
void PacketAlertTagInit(void)
Definition: detect-engine-alert.c:48
PacketDrop
void PacketDrop(Packet *p, const uint8_t action, enum PacketDropReason r)
issue drop action
Definition: packet.c:34
ACTION_ACCEPT
#define ACTION_ACCEPT
Definition: action-globals.h:36
suricata.h
PacketAlert_
Definition: decode.h:249
Signature_::detect_table
uint8_t detect_table
Definition: detect.h:726
FlowHasAlerts
int FlowHasAlerts(const Flow *f)
Check if flow has alerts.
Definition: flow.c:162
packet_alert_max
uint16_t packet_alert_max
Definition: decode.c:82
DetectEngineThreadCtx_::json_content_len
uint8_t json_content_len
Definition: detect.h:1355
TAG_SIG_GEN
#define TAG_SIG_GEN
Definition: detect-engine-tag.h:41
PacketContextData::json_string
char * json_string
Definition: decode.h:243
SIG_PROP_FLOW_ACTION_FLOW
@ SIG_PROP_FLOW_ACTION_FLOW
Definition: detect.h:86
PacketAlertThreshold
int PacketAlertThreshold(const DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const DetectThresholdData *td, Packet *p, const Signature *s, PacketAlert *pa)
Make the threshold logic for signatures.
Definition: detect-engine-threshold.c:1270
flow.h
PKT_FIRST_ALERTS
#define PKT_FIRST_ALERTS
Definition: decode.h:1360
DetectFirewallPolicy::action_scope
uint8_t action_scope
Definition: detect.h:948
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
AlertQueueAppendAppTx
void AlertQueueAppendAppTx(DetectEngineThreadCtx *det_ctx, const Signature *s, Packet *p, uint64_t tx_id, uint8_t sub_state, uint8_t alert_flags)
Append signature to local packet alert queue for later preprocessing.
Definition: detect-engine-alert.c:423
SCReturnInt
#define SCReturnInt(x)
Definition: util-debug.h:288
Signature_::type
enum SignatureType type
Definition: detect.h:695
DETECT_SM_LIST_SUPPRESS
@ DETECT_SM_LIST_SUPPRESS
Definition: detect.h:133
DEBUG_VALIDATE_BUG_ON
#define DEBUG_VALIDATE_BUG_ON(exp)
Definition: util-validate.h:109
SignatureProperties::flow_action
enum SignaturePropertyFlowAction flow_action
Definition: detect.h:91
SigJsonContent::json_content
char json_content[SIG_JSON_CONTENT_ITEM_LEN]
Definition: detect.h:1310
SigJsonContent::id
void * id
Definition: detect.h:1309
detect-engine-threshold.h
f
Flow f
Definition: fuzz_dataset.c:32