suricata
detect.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2017 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 Victor Julien <victor@inliniac.net>
22  *
23  * Basic detection engine
24  */
25 
26 #include "suricata-common.h"
27 #include "suricata.h"
28 #include "conf.h"
29 
30 #include "decode.h"
31 #include "flow.h"
32 #include "stream-tcp.h"
33 #include "app-layer.h"
34 #include "app-layer-parser.h"
35 
36 #include "detect.h"
37 #include "detect-engine.h"
38 #include "detect-engine-profile.h"
39 
40 #include "detect-engine-alert.h"
41 #include "detect-engine-siggroup.h"
42 #include "detect-engine-address.h"
43 #include "detect-engine-proto.h"
44 #include "detect-engine-port.h"
45 #include "detect-engine-mpm.h"
46 #include "detect-engine-iponly.h"
49 #include "detect-engine-state.h"
50 #include "detect-engine-analyzer.h"
51 
52 #include "detect-engine-payload.h"
53 #include "detect-engine-event.h"
54 
55 #include "detect-filestore.h"
56 #include "detect-flowvar.h"
57 #include "detect-replace.h"
58 
59 #include "util-validate.h"
60 #include "util-detect.h"
61 
62 typedef struct DetectRunScratchpad {
64  const uint8_t flow_flags; /* flow/state flags: STREAM_* */
65  const bool app_decoder_events;
66  const SigGroupHead *sgh;
69 
70 /* prototypes */
71 static DetectRunScratchpad DetectRunSetup(const DetectEngineCtx *de_ctx,
72  DetectEngineThreadCtx *det_ctx, Packet * const p, Flow * const pflow);
73 static void DetectRunInspectIPOnly(ThreadVars *tv, const DetectEngineCtx *de_ctx,
74  DetectEngineThreadCtx *det_ctx, Flow * const pflow, Packet * const p);
75 static inline void DetectRunGetRuleGroup(const DetectEngineCtx *de_ctx,
76  Packet * const p, Flow * const pflow, DetectRunScratchpad *scratch);
77 static inline void DetectRunPrefilterPkt(ThreadVars *tv,
78  DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p,
79  DetectRunScratchpad *scratch);
80 static inline void DetectRulePacketRules(ThreadVars * const tv,
81  DetectEngineCtx * const de_ctx, DetectEngineThreadCtx * const det_ctx,
82  Packet * const p, Flow * const pflow, const DetectRunScratchpad *scratch);
83 static void DetectRunTx(ThreadVars *tv, DetectEngineCtx *de_ctx,
84  DetectEngineThreadCtx *det_ctx, Packet *p,
85  Flow *f, DetectRunScratchpad *scratch);
86 static inline void DetectRunPostRules(ThreadVars *tv, DetectEngineCtx *de_ctx,
87  DetectEngineThreadCtx *det_ctx, Packet * const p, Flow * const pflow,
88  DetectRunScratchpad *scratch);
89 static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx,
90  Packet *p, Flow * const pflow);
91 
92 /** \internal
93  */
94 static void DetectRun(ThreadVars *th_v,
95  DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
96  Packet *p)
97 {
98  SCEnter();
99  SCLogDebug("pcap_cnt %"PRIu64, p->pcap_cnt);
100 
101  /* bail early if packet should not be inspected */
102  if (p->flags & PKT_NOPACKET_INSPECTION) {
103  /* nothing to do */
104  SCReturn;
105  }
106 
107  /* Load the Packet's flow early, even though it might not be needed.
108  * Mark as a constant pointer, although the flow itself can change. */
109  Flow * const pflow = p->flow;
110 
111  DetectRunScratchpad scratch = DetectRunSetup(de_ctx, det_ctx, p, pflow);
112 
113  /* run the IPonly engine */
114  DetectRunInspectIPOnly(th_v, de_ctx, det_ctx, pflow, p);
115 
116  /* get our rule group */
117  DetectRunGetRuleGroup(de_ctx, p, pflow, &scratch);
118  /* if we didn't get a sig group head, we
119  * have nothing to do.... */
120  if (scratch.sgh == NULL) {
121  SCLogDebug("no sgh for this packet, nothing to match against");
122  goto end;
123  }
124 
125  /* run the prefilters for packets */
126  DetectRunPrefilterPkt(th_v, de_ctx, det_ctx, p, &scratch);
127 
129  /* inspect the rules against the packet */
130  DetectRulePacketRules(th_v, de_ctx, det_ctx, p, pflow, &scratch);
132 
133  /* run tx/state inspection */
134  if (pflow && pflow->alstate) {
136  DetectRunTx(th_v, de_ctx, det_ctx, p, pflow, &scratch);
138  }
139 
140 end:
141  DetectRunPostRules(th_v, de_ctx, det_ctx, p, pflow, &scratch);
142 
143  DetectRunCleanup(det_ctx, p, pflow);
144  SCReturn;
145 }
146 
147 static void DetectRunPostMatch(ThreadVars *tv,
148  DetectEngineThreadCtx *det_ctx, Packet *p,
149  const Signature *s)
150 {
151  /* run the packet match functions */
153  if (smd != NULL) {
155 
156  SCLogDebug("running match functions, sm %p", smd);
157 
158  while (1) {
160  (void)sigmatch_table[smd->type].Match(tv, det_ctx, p, s, smd->ctx);
161  KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
162  if (smd->is_last)
163  break;
164  smd++;
165  }
166  }
167 }
168 
169 /**
170  * \brief Get the SigGroupHead for a packet.
171  *
172  * \param de_ctx detection engine context
173  * \param p packet
174  *
175  * \retval sgh the SigGroupHead or NULL if non applies to the packet
176  */
178  const Packet *p)
179 {
180  SCEnter();
181 
182  int f;
183  SigGroupHead *sgh = NULL;
184 
185  /* if the packet proto is 0 (not set), we're inspecting it against
186  * the decoder events sgh we have. */
187  if (p->proto == 0 && p->events.cnt > 0) {
188  SCReturnPtr(de_ctx->decoder_event_sgh, "SigGroupHead");
189  } else if (p->proto == 0) {
190  if (!(PKT_IS_IPV4(p) || PKT_IS_IPV6(p))) {
191  /* not IP, so nothing to do */
192  SCReturnPtr(NULL, "SigGroupHead");
193  }
194  }
195 
196  /* select the flow_gh */
197  if (p->flowflags & FLOW_PKT_TOCLIENT)
198  f = 0;
199  else
200  f = 1;
201 
202  int proto = IP_GET_IPPROTO(p);
203  if (proto == IPPROTO_TCP) {
204  DetectPort *list = de_ctx->flow_gh[f].tcp;
205  SCLogDebug("tcp toserver %p, tcp toclient %p: going to use %p",
206  de_ctx->flow_gh[1].tcp, de_ctx->flow_gh[0].tcp, de_ctx->flow_gh[f].tcp);
207  uint16_t port = f ? p->dp : p->sp;
208  SCLogDebug("tcp port %u -> %u:%u", port, p->sp, p->dp);
209  DetectPort *sghport = DetectPortLookupGroup(list, port);
210  if (sghport != NULL)
211  sgh = sghport->sh;
212  SCLogDebug("TCP list %p, port %u, direction %s, sghport %p, sgh %p",
213  list, port, f ? "toserver" : "toclient", sghport, sgh);
214  } else if (proto == IPPROTO_UDP) {
215  DetectPort *list = de_ctx->flow_gh[f].udp;
216  uint16_t port = f ? p->dp : p->sp;
217  DetectPort *sghport = DetectPortLookupGroup(list, port);
218  if (sghport != NULL)
219  sgh = sghport->sh;
220  SCLogDebug("UDP list %p, port %u, direction %s, sghport %p, sgh %p",
221  list, port, f ? "toserver" : "toclient", sghport, sgh);
222  } else {
223  sgh = de_ctx->flow_gh[f].sgh[proto];
224  }
225 
226  SCReturnPtr(sgh, "SigGroupHead");
227 }
228 
229 static inline void DetectPrefilterMergeSort(DetectEngineCtx *de_ctx,
230  DetectEngineThreadCtx *det_ctx)
231 {
232  SigIntId mpm, nonmpm;
233  SigIntId *mpm_ptr = det_ctx->pmq.rule_id_array;
234  SigIntId *nonmpm_ptr = det_ctx->non_pf_id_array;
235  uint32_t m_cnt = det_ctx->pmq.rule_id_array_cnt;
236  uint32_t n_cnt = det_ctx->non_pf_id_cnt;
237  SigIntId *final_ptr;
238  uint32_t final_cnt;
239  SigIntId id;
240  SigIntId previous_id = (SigIntId)-1;
241  Signature **sig_array = de_ctx->sig_array;
242  Signature **match_array = det_ctx->match_array;
243  Signature *s;
244 
245  SCLogDebug("PMQ rule id array count %d", det_ctx->pmq.rule_id_array_cnt);
246 
247  /* Load first values. */
248  if (likely(m_cnt)) {
249  mpm = *mpm_ptr;
250  } else {
251  /* mpm list is empty */
252  final_ptr = nonmpm_ptr;
253  final_cnt = n_cnt;
254  goto final;
255  }
256  if (likely(n_cnt)) {
257  nonmpm = *nonmpm_ptr;
258  } else {
259  /* non-mpm list is empty. */
260  final_ptr = mpm_ptr;
261  final_cnt = m_cnt;
262  goto final;
263  }
264  while (1) {
265  if (mpm < nonmpm) {
266  /* Take from mpm list */
267  id = mpm;
268 
269  s = sig_array[id];
270  /* As the mpm list can contain duplicates, check for that here. */
271  if (likely(id != previous_id)) {
272  *match_array++ = s;
273  previous_id = id;
274  }
275  if (unlikely(--m_cnt == 0)) {
276  /* mpm list is now empty */
277  final_ptr = nonmpm_ptr;
278  final_cnt = n_cnt;
279  goto final;
280  }
281  mpm_ptr++;
282  mpm = *mpm_ptr;
283  } else if (mpm > nonmpm) {
284  id = nonmpm;
285 
286  s = sig_array[id];
287  /* As the mpm list can contain duplicates, check for that here. */
288  if (likely(id != previous_id)) {
289  *match_array++ = s;
290  previous_id = id;
291  }
292  if (unlikely(--n_cnt == 0)) {
293  final_ptr = mpm_ptr;
294  final_cnt = m_cnt;
295  goto final;
296  }
297  nonmpm_ptr++;
298  nonmpm = *nonmpm_ptr;
299 
300  } else { /* implied mpm == nonmpm */
301  /* special case: if on both lists, it's a negated mpm pattern */
302 
303  /* mpm list may have dups, so skip past them here */
304  while (--m_cnt != 0) {
305  mpm_ptr++;
306  mpm = *mpm_ptr;
307  if (mpm != nonmpm)
308  break;
309  }
310  /* if mpm is done, update nonmpm_ptrs and jump to final */
311  if (unlikely(m_cnt == 0)) {
312  n_cnt--;
313 
314  /* mpm list is now empty */
315  final_ptr = ++nonmpm_ptr;
316  final_cnt = n_cnt;
317  goto final;
318  }
319  /* otherwise, if nonmpm is done jump to final for mpm
320  * mpm ptrs alrady updated */
321  if (unlikely(--n_cnt == 0)) {
322  final_ptr = mpm_ptr;
323  final_cnt = m_cnt;
324  goto final;
325  }
326 
327  /* not at end of the lists, update nonmpm. Mpm already
328  * updated in while loop above. */
329  nonmpm_ptr++;
330  nonmpm = *nonmpm_ptr;
331  }
332  }
333 
334  final: /* Only one list remaining. Just walk that list. */
335 
336  while (final_cnt-- > 0) {
337  id = *final_ptr++;
338  s = sig_array[id];
339 
340  /* As the mpm list can contain duplicates, check for that here. */
341  if (likely(id != previous_id)) {
342  *match_array++ = s;
343  previous_id = id;
344  }
345  }
346 
347  det_ctx->match_array_cnt = match_array - det_ctx->match_array;
348 
349  DEBUG_VALIDATE_BUG_ON((det_ctx->pmq.rule_id_array_cnt + det_ctx->non_pf_id_cnt) < det_ctx->match_array_cnt);
350 }
351 
352 static inline void
353 DetectPrefilterBuildNonPrefilterList(DetectEngineThreadCtx *det_ctx, SignatureMask mask, uint8_t alproto)
354 {
355  uint32_t x = 0;
356  for (x = 0; x < det_ctx->non_pf_store_cnt; x++) {
357  /* only if the mask matches this rule can possibly match,
358  * so build the non_mpm array only for match candidates */
359  const SignatureMask rule_mask = det_ctx->non_pf_store_ptr[x].mask;
360  const uint8_t rule_alproto = det_ctx->non_pf_store_ptr[x].alproto;
361  if ((rule_mask & mask) == rule_mask && (rule_alproto == 0 || rule_alproto == alproto)) {
362  det_ctx->non_pf_id_array[det_ctx->non_pf_id_cnt++] = det_ctx->non_pf_store_ptr[x].id;
363  }
364  }
365 }
366 
367 /** \internal
368  * \brief select non-mpm list
369  * Based on the packet properties, select the non-mpm list to use
370  * \todo move non_pf_store* into scratchpad */
371 static inline void
372 DetectPrefilterSetNonPrefilterList(const Packet *p, DetectEngineThreadCtx *det_ctx, DetectRunScratchpad *scratch)
373 {
374  if ((p->proto == IPPROTO_TCP) && (p->tcph != NULL) && (p->tcph->th_flags & TH_SYN)) {
375  det_ctx->non_pf_store_ptr = scratch->sgh->non_pf_syn_store_array;
376  det_ctx->non_pf_store_cnt = scratch->sgh->non_pf_syn_store_cnt;
377  } else {
378  det_ctx->non_pf_store_ptr = scratch->sgh->non_pf_other_store_array;
379  det_ctx->non_pf_store_cnt = scratch->sgh->non_pf_other_store_cnt;
380  }
381  SCLogDebug("sgh non_pf ptr %p cnt %u (syn %p/%u, other %p/%u)",
382  det_ctx->non_pf_store_ptr, det_ctx->non_pf_store_cnt,
383  scratch->sgh->non_pf_syn_store_array, scratch->sgh->non_pf_syn_store_cnt,
385 }
386 
387 /** \internal
388  * \brief update flow's file tracking flags based on the detection engine
389  */
390 static inline void
391 DetectPostInspectFileFlagsUpdate(Flow *pflow, const SigGroupHead *sgh, uint8_t direction)
392 {
393  /* see if this sgh requires us to consider file storing */
394  if (!FileForceFilestore() && (sgh == NULL ||
395  sgh->filestore_cnt == 0))
396  {
397  FileDisableStoring(pflow, direction);
398  }
399 #ifdef HAVE_MAGIC
400  /* see if this sgh requires us to consider file magic */
401  if (!FileForceMagic() && (sgh == NULL ||
402  !(sgh->flags & SIG_GROUP_HEAD_HAVEFILEMAGIC)))
403  {
404  SCLogDebug("disabling magic for flow");
405  FileDisableMagic(pflow, direction);
406  }
407 #endif
408  /* see if this sgh requires us to consider file md5 */
409  if (!FileForceMd5() && (sgh == NULL ||
411  {
412  SCLogDebug("disabling md5 for flow");
413  FileDisableMd5(pflow, direction);
414  }
415 
416  /* see if this sgh requires us to consider file sha1 */
417  if (!FileForceSha1() && (sgh == NULL ||
419  {
420  SCLogDebug("disabling sha1 for flow");
421  FileDisableSha1(pflow, direction);
422  }
423 
424  /* see if this sgh requires us to consider file sha256 */
425  if (!FileForceSha256() && (sgh == NULL ||
427  {
428  SCLogDebug("disabling sha256 for flow");
429  FileDisableSha256(pflow, direction);
430  }
431 
432  /* see if this sgh requires us to consider filesize */
433  if (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVEFILESIZE))
434  {
435  SCLogDebug("disabling filesize for flow");
436  FileDisableFilesize(pflow, direction);
437  }
438 }
439 
440 static inline void
441 DetectRunPostGetFirstRuleGroup(const Packet *p, Flow *pflow, const SigGroupHead *sgh)
442 {
443  if ((p->flowflags & FLOW_PKT_TOSERVER) && !(pflow->flags & FLOW_SGH_TOSERVER)) {
444  /* first time we see this toserver sgh, store it */
445  pflow->sgh_toserver = sgh;
446  pflow->flags |= FLOW_SGH_TOSERVER;
447 
448  if (p->proto == IPPROTO_TCP && (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVERAWSTREAM))) {
449  if (pflow->protoctx != NULL) {
450  TcpSession *ssn = pflow->protoctx;
451  SCLogDebug("STREAMTCP_STREAM_FLAG_DISABLE_RAW ssn.client");
453  }
454  }
455 
456  DetectPostInspectFileFlagsUpdate(pflow,
457  pflow->sgh_toserver, STREAM_TOSERVER);
458 
459  } else if ((p->flowflags & FLOW_PKT_TOCLIENT) && !(pflow->flags & FLOW_SGH_TOCLIENT)) {
460  pflow->sgh_toclient = sgh;
461  pflow->flags |= FLOW_SGH_TOCLIENT;
462 
463  if (p->proto == IPPROTO_TCP && (sgh == NULL || !(sgh->flags & SIG_GROUP_HEAD_HAVERAWSTREAM))) {
464  if (pflow->protoctx != NULL) {
465  TcpSession *ssn = pflow->protoctx;
466  SCLogDebug("STREAMTCP_STREAM_FLAG_DISABLE_RAW ssn.server");
468  }
469  }
470 
471  DetectPostInspectFileFlagsUpdate(pflow,
472  pflow->sgh_toclient, STREAM_TOCLIENT);
473  }
474 }
475 
476 static inline void DetectRunGetRuleGroup(
477  const DetectEngineCtx *de_ctx,
478  Packet * const p, Flow * const pflow,
479  DetectRunScratchpad *scratch)
480 {
481  const SigGroupHead *sgh = NULL;
482 
483  if (pflow) {
484  bool use_flow_sgh = false;
485  /* Get the stored sgh from the flow (if any). Make sure we're not using
486  * the sgh for icmp error packets part of the same stream. */
487  if (IP_GET_IPPROTO(p) == pflow->proto) { /* filter out icmp */
489  if ((p->flowflags & FLOW_PKT_TOSERVER) && (pflow->flags & FLOW_SGH_TOSERVER)) {
490  sgh = pflow->sgh_toserver;
491  SCLogDebug("sgh = pflow->sgh_toserver; => %p", sgh);
492  use_flow_sgh = true;
493  } else if ((p->flowflags & FLOW_PKT_TOCLIENT) && (pflow->flags & FLOW_SGH_TOCLIENT)) {
494  sgh = pflow->sgh_toclient;
495  SCLogDebug("sgh = pflow->sgh_toclient; => %p", sgh);
496  use_flow_sgh = true;
497  }
499  }
500 
501  if (!(use_flow_sgh)) {
503  sgh = SigMatchSignaturesGetSgh(de_ctx, p);
505 
506  /* HACK: prevent the wrong sgh (or NULL) from being stored in the
507  * flow's sgh pointers */
509  ; /* no-op */
510  } else {
511  /* store the found sgh (or NULL) in the flow to save us
512  * from looking it up again for the next packet.
513  * Also run other tasks */
514  DetectRunPostGetFirstRuleGroup(p, pflow, sgh);
515  }
516  }
517  } else { /* p->flags & PKT_HAS_FLOW */
518  /* no flow */
519 
521  sgh = SigMatchSignaturesGetSgh(de_ctx, p);
523  }
524 
525  scratch->sgh = sgh;
526 }
527 
528 static void DetectRunInspectIPOnly(ThreadVars *tv, const DetectEngineCtx *de_ctx,
529  DetectEngineThreadCtx *det_ctx,
530  Flow * const pflow, Packet * const p)
531 {
532  if (pflow) {
533  /* set the iponly stuff */
534  if (pflow->flags & FLOW_TOCLIENT_IPONLY_SET)
536  if (pflow->flags & FLOW_TOSERVER_IPONLY_SET)
538 
541  {
542  SCLogDebug("testing against \"ip-only\" signatures");
543 
545  IPOnlyMatchPacket(tv, de_ctx, det_ctx, &de_ctx->io_ctx, &det_ctx->io_ctx, p);
547 
548  /* save in the flow that we scanned this direction... */
549  FlowSetIPOnlyFlag(pflow, p->flowflags & FLOW_PKT_TOSERVER ? 1 : 0);
550 
551  } else if (((p->flowflags & FLOW_PKT_TOSERVER) &&
552  (pflow->flags & FLOW_TOSERVER_IPONLY_SET)) ||
553  ((p->flowflags & FLOW_PKT_TOCLIENT) &&
554  (pflow->flags & FLOW_TOCLIENT_IPONLY_SET)))
555  {
556  /* If we have a drop from IP only module,
557  * we will drop the rest of the flow packets
558  * This will apply only to inline/IPS */
559  if (pflow->flags & FLOW_ACTION_DROP) {
560  PACKET_DROP(p);
561  }
562  }
563  } else { /* p->flags & PKT_HAS_FLOW */
564  /* no flow */
565 
566  /* Even without flow we should match the packet src/dst */
568  IPOnlyMatchPacket(tv, de_ctx, det_ctx, &de_ctx->io_ctx,
569  &det_ctx->io_ctx, p);
571  }
572 }
573 
574 /* returns 0 if no match, 1 if match */
575 static inline int DetectRunInspectRuleHeader(
576  const Packet *p,
577  const Flow *f,
578  const Signature *s,
579  const uint32_t sflags,
580  const uint8_t s_proto_flags)
581 {
582  /* check if this signature has a requirement for flowvars of some type
583  * and if so, if we actually have any in the flow. If not, the sig
584  * can't match and we skip it. */
585  if ((p->flags & PKT_HAS_FLOW) && (sflags & SIG_FLAG_REQUIRE_FLOWVAR)) {
586  DEBUG_VALIDATE_BUG_ON(f == NULL);
587 
588  int m = f->flowvar ? 1 : 0;
589 
590  /* no flowvars? skip this sig */
591  if (m == 0) {
592  SCLogDebug("skipping sig as the flow has no flowvars and sig "
593  "has SIG_FLAG_REQUIRE_FLOWVAR flag set.");
594  return 0;
595  }
596  }
597 
598  if ((s_proto_flags & DETECT_PROTO_IPV4) && !PKT_IS_IPV4(p)) {
599  SCLogDebug("ip version didn't match");
600  return 0;
601  }
602  if ((s_proto_flags & DETECT_PROTO_IPV6) && !PKT_IS_IPV6(p)) {
603  SCLogDebug("ip version didn't match");
604  return 0;
605  }
606 
607  if (DetectProtoContainsProto(&s->proto, IP_GET_IPPROTO(p)) == 0) {
608  SCLogDebug("proto didn't match");
609  return 0;
610  }
611 
612  /* check the source & dst port in the sig */
613  if (p->proto == IPPROTO_TCP || p->proto == IPPROTO_UDP || p->proto == IPPROTO_SCTP) {
614  if (!(sflags & SIG_FLAG_DP_ANY)) {
615  if (p->flags & PKT_IS_FRAGMENT)
616  return 0;
617  DetectPort *dport = DetectPortLookupGroup(s->dp,p->dp);
618  if (dport == NULL) {
619  SCLogDebug("dport didn't match.");
620  return 0;
621  }
622  }
623  if (!(sflags & SIG_FLAG_SP_ANY)) {
624  if (p->flags & PKT_IS_FRAGMENT)
625  return 0;
626  DetectPort *sport = DetectPortLookupGroup(s->sp,p->sp);
627  if (sport == NULL) {
628  SCLogDebug("sport didn't match.");
629  return 0;
630  }
631  }
632  } else if ((sflags & (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) != (SIG_FLAG_DP_ANY|SIG_FLAG_SP_ANY)) {
633  SCLogDebug("port-less protocol and sig needs ports");
634  return 0;
635  }
636 
637  /* check the destination address */
638  if (!(sflags & SIG_FLAG_DST_ANY)) {
639  if (PKT_IS_IPV4(p)) {
641  return 0;
642  } else if (PKT_IS_IPV6(p)) {
644  return 0;
645  }
646  }
647  /* check the source address */
648  if (!(sflags & SIG_FLAG_SRC_ANY)) {
649  if (PKT_IS_IPV4(p)) {
651  return 0;
652  } else if (PKT_IS_IPV6(p)) {
654  return 0;
655  }
656  }
657 
658  return 1;
659 }
660 
661 /* returns 0 if no match, 1 if match */
662 static inline int DetectRunInspectRulePacketMatches(
663  ThreadVars *tv,
664  DetectEngineThreadCtx *det_ctx,
665  Packet *p,
666  const Flow *f,
667  const Signature *s)
668 {
669  /* run the packet match functions */
670  if (s->sm_arrays[DETECT_SM_LIST_MATCH] != NULL) {
673 
674  SCLogDebug("running match functions, sm %p", smd);
675  while (1) {
677  if (sigmatch_table[smd->type].Match(tv, det_ctx, p, s, smd->ctx) <= 0) {
678  KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
679  SCLogDebug("no match");
680  return 0;
681  }
682  KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
683  if (smd->is_last) {
684  SCLogDebug("match and is_last");
685  break;
686  }
687  smd++;
688  }
689  }
690  return 1;
691 }
692 
693 /** \internal
694  * \brief run packet/stream prefilter engines
695  */
696 static inline void DetectRunPrefilterPkt(
697  ThreadVars *tv,
698  DetectEngineCtx *de_ctx,
699  DetectEngineThreadCtx *det_ctx,
700  Packet *p,
701  DetectRunScratchpad *scratch
702 )
703 {
704  DetectPrefilterSetNonPrefilterList(p, det_ctx, scratch);
705 
706  /* create our prefilter mask */
707  PacketCreateMask(p, &scratch->pkt_mask, scratch->alproto, scratch->app_decoder_events);
708 
709  /* build and prefilter non_pf list against the mask of the packet */
711  det_ctx->non_pf_id_cnt = 0;
712  if (likely(det_ctx->non_pf_store_cnt > 0)) {
713  DetectPrefilterBuildNonPrefilterList(det_ctx, scratch->pkt_mask, scratch->alproto);
714  }
716 
717  /* run the prefilter engines */
718  Prefilter(det_ctx, scratch->sgh, p, scratch->flow_flags);
719  /* create match list if we have non-pf and/or pf */
720  if (det_ctx->non_pf_store_cnt || det_ctx->pmq.rule_id_array_cnt) {
722  DetectPrefilterMergeSort(de_ctx, det_ctx);
724  }
725 
726 #ifdef PROFILING
727  if (tv) {
728  StatsAddUI64(tv, det_ctx->counter_mpm_list,
729  (uint64_t)det_ctx->pmq.rule_id_array_cnt);
730  StatsAddUI64(tv, det_ctx->counter_nonmpm_list,
731  (uint64_t)det_ctx->non_pf_store_cnt);
732  /* non mpm sigs after mask prefilter */
733  StatsAddUI64(tv, det_ctx->counter_fnonmpm_list,
734  (uint64_t)det_ctx->non_pf_id_cnt);
735  }
736 #endif
737 }
738 
739 static inline void DetectRulePacketRules(
740  ThreadVars * const tv,
741  DetectEngineCtx * const de_ctx,
742  DetectEngineThreadCtx * const det_ctx,
743  Packet * const p,
744  Flow * const pflow,
745  const DetectRunScratchpad *scratch
746 )
747 {
748  const Signature *s = NULL;
749  const Signature *next_s = NULL;
750 
751  /* inspect the sigs against the packet */
752  /* Prefetch the next signature. */
753  SigIntId match_cnt = det_ctx->match_array_cnt;
754 #ifdef PROFILING
755  if (tv) {
756  StatsAddUI64(tv, det_ctx->counter_match_list,
757  (uint64_t)match_cnt);
758  }
759 #endif
760  Signature **match_array = det_ctx->match_array;
761 
762  SGH_PROFILING_RECORD(det_ctx, scratch->sgh);
763 #ifdef PROFILING
764 #ifdef HAVE_LIBJANSSON
765  if (match_cnt >= de_ctx->profile_match_logging_threshold)
766  RulesDumpMatchArray(det_ctx, scratch->sgh, p);
767 #endif
768 #endif
769 
770  uint32_t sflags, next_sflags = 0;
771  if (match_cnt) {
772  next_s = *match_array++;
773  next_sflags = next_s->flags;
774  }
775  while (match_cnt--) {
777  uint8_t alert_flags = 0;
778  bool state_alert = false;
779 #ifdef PROFILING
780  bool smatch = false; /* signature match */
781 #endif
782  s = next_s;
783  sflags = next_sflags;
784  if (match_cnt) {
785  next_s = *match_array++;
786  next_sflags = next_s->flags;
787  }
788  const uint8_t s_proto_flags = s->proto.flags;
789 
790  SCLogDebug("inspecting signature id %"PRIu32"", s->id);
791 
792  if (s->app_inspect != NULL) {
793  goto next; // handle sig in DetectRunTx
794  }
795 
796  /* don't run mask check for stateful rules.
797  * There we depend on prefilter */
798  if ((s->mask & scratch->pkt_mask) != s->mask) {
799  SCLogDebug("mask mismatch %x & %x != %x", s->mask, scratch->pkt_mask, s->mask);
800  goto next;
801  }
802 
803  if (unlikely(sflags & SIG_FLAG_DSIZE)) {
804  if (likely(p->payload_len < s->dsize_low || p->payload_len > s->dsize_high)) {
805  SCLogDebug("kicked out as p->payload_len %u, dsize low %u, hi %u",
806  p->payload_len, s->dsize_low, s->dsize_high);
807  goto next;
808  }
809  }
810 
811  /* if the sig has alproto and the session as well they should match */
812  if (likely(sflags & SIG_FLAG_APPLAYER)) {
813  if (s->alproto != ALPROTO_UNKNOWN && s->alproto != scratch->alproto) {
814  if (s->alproto == ALPROTO_DCERPC) {
815  if (scratch->alproto != ALPROTO_SMB) {
816  SCLogDebug("DCERPC sig, alproto not SMB");
817  goto next;
818  }
819  } else {
820  SCLogDebug("alproto mismatch");
821  goto next;
822  }
823  }
824  }
825 
826  if (DetectRunInspectRuleHeader(p, pflow, s, sflags, s_proto_flags) == 0) {
827  goto next;
828  }
829 
830  /* Check the payload keywords. If we are a MPM sig and we've made
831  * to here, we've had at least one of the patterns match */
832  if (s->sm_arrays[DETECT_SM_LIST_PMATCH] != NULL) {
834  /* if we have stream msgs, inspect against those first,
835  * but not for a "dsize" signature */
836  if (sflags & SIG_FLAG_REQUIRE_STREAM) {
837  int pmatch = 0;
838  if (p->flags & PKT_DETECT_HAS_STREAMDATA) {
839  pmatch = DetectEngineInspectStreamPayload(de_ctx, det_ctx, s, pflow, p);
840  if (pmatch) {
842  /* Tell the engine that this reassembled stream can drop the
843  * rest of the pkts with no further inspection */
844  if (s->action & ACTION_DROP)
845  alert_flags |= PACKET_ALERT_FLAG_DROP_FLOW;
846 
847  alert_flags |= PACKET_ALERT_FLAG_STREAM_MATCH;
848  }
849  }
850  /* no match? then inspect packet payload */
851  if (pmatch == 0) {
852  SCLogDebug("no match in stream, fall back to packet payload");
853 
854  /* skip if we don't have to inspect the packet and segment was
855  * added to stream */
856  if (!(sflags & SIG_FLAG_REQUIRE_PACKET) && (p->flags & PKT_STREAM_ADD)) {
857  goto next;
858  }
859 
860  if (DetectEngineInspectPacketPayload(de_ctx, det_ctx, s, pflow, p) != 1) {
861  goto next;
862  }
863  }
864  } else {
865  if (DetectEngineInspectPacketPayload(de_ctx, det_ctx, s, pflow, p) != 1) {
866  goto next;
867  }
868  }
869  }
870 
871  if (DetectRunInspectRulePacketMatches(tv, det_ctx, p, pflow, s) == 0)
872  goto next;
873 
874 #ifdef PROFILING
875  smatch = true;
876 #endif
877  DetectRunPostMatch(tv, det_ctx, p, s);
878 
879  if (!(sflags & SIG_FLAG_NOALERT)) {
880  /* stateful sigs call PacketAlertAppend from DeStateDetectStartDetection */
881  if (!state_alert)
882  PacketAlertAppend(det_ctx, s, p, 0, alert_flags);
883  } else {
884  /* apply actions even if not alerting */
885  DetectSignatureApplyActions(p, s, alert_flags);
886  }
887 next:
888  DetectVarProcessList(det_ctx, pflow, p);
889  DetectReplaceFree(det_ctx);
890  RULE_PROFILING_END(det_ctx, s, smatch, p);
891 
892  det_ctx->flags = 0;
893  continue;
894  }
895 }
896 
897 static DetectRunScratchpad DetectRunSetup(
898  const DetectEngineCtx *de_ctx,
899  DetectEngineThreadCtx *det_ctx,
900  Packet * const p, Flow * const pflow)
901 {
902  AppProto alproto = ALPROTO_UNKNOWN;
903  uint8_t flow_flags = 0; /* flow/state flags */
904  bool app_decoder_events = false;
905 
907 
908 #ifdef UNITTESTS
909  p->alerts.cnt = 0;
910 #endif
911  det_ctx->ticker++;
912  det_ctx->filestore_cnt = 0;
913  det_ctx->base64_decoded_len = 0;
914  det_ctx->raw_stream_progress = 0;
915  det_ctx->match_array_cnt = 0;
916 
917 #ifdef DEBUG
918  if (p->flags & PKT_STREAM_ADD) {
919  det_ctx->pkt_stream_add_cnt++;
920  }
921 #endif
922 
923  /* grab the protocol state we will detect on */
924  if (p->flags & PKT_HAS_FLOW) {
925  DEBUG_VALIDATE_BUG_ON(pflow == NULL);
926 
927  if (p->flowflags & FLOW_PKT_TOSERVER) {
928  flow_flags = STREAM_TOSERVER;
929  SCLogDebug("flag STREAM_TOSERVER set");
930  } else if (p->flowflags & FLOW_PKT_TOCLIENT) {
931  flow_flags = STREAM_TOCLIENT;
932  SCLogDebug("flag STREAM_TOCLIENT set");
933  }
934  SCLogDebug("p->flowflags 0x%02x", p->flowflags);
935 
936  if (p->flags & PKT_STREAM_EOF) {
937  flow_flags |= STREAM_EOF;
938  SCLogDebug("STREAM_EOF set");
939  }
940 
941  /* store tenant_id in the flow so that we can use it
942  * for creating pseudo packets */
943  if (p->tenant_id > 0 && pflow->tenant_id == 0) {
944  pflow->tenant_id = p->tenant_id;
945  }
946 
947  /* live ruleswap check for flow updates */
948  if (pflow->de_ctx_version == 0) {
949  /* first time this flow is inspected, set id */
950  pflow->de_ctx_version = de_ctx->version;
951  } else if (pflow->de_ctx_version != de_ctx->version) {
952  /* first time we inspect flow with this de_ctx, reset */
953  pflow->flags &= ~FLOW_SGH_TOSERVER;
954  pflow->flags &= ~FLOW_SGH_TOCLIENT;
955  pflow->sgh_toserver = NULL;
956  pflow->sgh_toclient = NULL;
957 
958  pflow->de_ctx_version = de_ctx->version;
959  GenericVarFree(pflow->flowvar);
960  pflow->flowvar = NULL;
961 
963  }
964 
965  /* Retrieve the app layer state and protocol and the tcp reassembled
966  * stream chunks. */
967  if ((p->proto == IPPROTO_TCP && (p->flags & PKT_STREAM_EST)) ||
968  (p->proto == IPPROTO_UDP) ||
969  (p->proto == IPPROTO_SCTP && (p->flowflags & FLOW_PKT_ESTABLISHED)))
970  {
971  /* update flow flags with knowledge on disruptions */
972  flow_flags = FlowGetDisruptionFlags(pflow, flow_flags);
973  alproto = FlowGetAppProtocol(pflow);
974  if (p->proto == IPPROTO_TCP && pflow->protoctx &&
977  flow_flags |= STREAM_FLUSH;
978  }
979  SCLogDebug("alproto %u", alproto);
980  } else {
981  SCLogDebug("packet doesn't have established flag set (proto %d)", p->proto);
982  }
983 
984  app_decoder_events = AppLayerParserHasDecoderEvents(pflow->alparser);
985  }
986 
989  return pad;
990 }
991 
992 static inline void DetectRunPostRules(
993  ThreadVars *tv,
994  DetectEngineCtx *de_ctx,
995  DetectEngineThreadCtx *det_ctx,
996  Packet * const p,
997  Flow * const pflow,
998  DetectRunScratchpad *scratch)
999 {
1000  /* see if we need to increment the inspect_id and reset the de_state */
1001  if (pflow && pflow->alstate && AppLayerParserProtocolSupportsTxs(p->proto, scratch->alproto)) {
1003  DeStateUpdateInspectTransactionId(pflow, scratch->flow_flags, (scratch->sgh == NULL));
1005  }
1006 
1007  /* so now let's iterate the alerts and remove the ones after a pass rule
1008  * matched (if any). This is done inside PacketAlertFinalize() */
1009  /* PR: installed "tag" keywords are handled after the threshold inspection */
1010 
1012  PacketAlertFinalize(de_ctx, det_ctx, p);
1013  if (p->alerts.cnt > 0) {
1014  StatsAddUI64(tv, det_ctx->counter_alerts, (uint64_t)p->alerts.cnt);
1015  }
1017 }
1018 
1019 static void DetectRunCleanup(DetectEngineThreadCtx *det_ctx,
1020  Packet *p, Flow * const pflow)
1021 {
1023  /* cleanup pkt specific part of the patternmatcher */
1024  PacketPatternCleanup(det_ctx);
1025 
1026  if (pflow != NULL) {
1027  /* update inspected tracker for raw reassembly */
1028  if (p->proto == IPPROTO_TCP && pflow->protoctx != NULL &&
1029  (p->flags & PKT_STREAM_EST))
1030  {
1032  det_ctx->raw_stream_progress);
1033  }
1034  }
1036  SCReturn;
1037 }
1038 
1040 {
1042  det_ctx->tx_candidates = SCCalloc(size, sizeof(RuleMatchCandidateTx));
1043  if (det_ctx->tx_candidates == NULL) {
1044  FatalError(SC_ERR_MEM_ALLOC, "failed to allocate %"PRIu64" bytes",
1045  (uint64_t)(size * sizeof(RuleMatchCandidateTx)));
1046  }
1047  det_ctx->tx_candidates_size = size;
1048  SCLogDebug("array initialized to %u elements (%"PRIu64" bytes)",
1049  size, (uint64_t)(size * sizeof(RuleMatchCandidateTx)));
1050 }
1051 
1053 {
1054  SCFree(det_ctx->tx_candidates);
1055  det_ctx->tx_candidates_size = 0;
1056 }
1057 
1058 /* if size >= cur_space */
1059 static inline bool RuleMatchCandidateTxArrayHasSpace(const DetectEngineThreadCtx *det_ctx,
1060  const uint32_t need)
1061 {
1062  if (det_ctx->tx_candidates_size >= need)
1063  return 1;
1064  return 0;
1065 }
1066 
1067 /* realloc */
1068 static int RuleMatchCandidateTxArrayExpand(DetectEngineThreadCtx *det_ctx, const uint32_t needed)
1069 {
1070  const uint32_t old_size = det_ctx->tx_candidates_size;
1071  uint32_t new_size = needed;
1072  void *ptmp = SCRealloc(det_ctx->tx_candidates, (new_size * sizeof(RuleMatchCandidateTx)));
1073  if (ptmp == NULL) {
1074  FatalError(SC_ERR_MEM_ALLOC, "failed to expand to %"PRIu64" bytes",
1075  (uint64_t)(new_size * sizeof(RuleMatchCandidateTx)));
1076  // TODO can this be handled more gracefully?
1077  }
1078  det_ctx->tx_candidates = ptmp;
1079  det_ctx->tx_candidates_size = new_size;
1080  SCLogDebug("array expanded from %u to %u elements (%"PRIu64" bytes -> %"PRIu64" bytes)",
1081  old_size, new_size, (uint64_t)(old_size * sizeof(RuleMatchCandidateTx)),
1082  (uint64_t)(new_size * sizeof(RuleMatchCandidateTx))); (void)old_size;
1083  return 1;
1084 }
1085 
1086 
1087 /* TODO maybe let one with flags win if equal? */
1088 static int
1089 DetectRunTxSortHelper(const void *a, const void *b)
1090 {
1091  const RuleMatchCandidateTx *s0 = a;
1092  const RuleMatchCandidateTx *s1 = b;
1093  if (s1->id == s0->id)
1094  return 0;
1095  else
1096  return s0->id > s1->id ? -1 : 1;
1097 }
1098 
1099 #if 0
1100 #define TRACE_SID_TXS(sid,txs,...) \
1101  do { \
1102  char _trace_buf[2048]; \
1103  snprintf(_trace_buf, sizeof(_trace_buf), __VA_ARGS__); \
1104  SCLogNotice("%p/%"PRIu64"/%u: %s", txs->tx_ptr, txs->tx_id, sid, _trace_buf); \
1105  } while(0)
1106 #else
1107 #define TRACE_SID_TXS(sid,txs,...)
1108 #endif
1109 
1110 /** \internal
1111  * \brief inspect a rule against a transaction
1112  *
1113  * Inspect a rule. New detection or continued stateful
1114  * detection.
1115  *
1116  * \param stored_flags pointer to stored flags or NULL.
1117  * If stored_flags is set it means we're continueing
1118  * inspection from an earlier run.
1119  *
1120  * \retval bool true sig matched, false didn't match
1121  */
1122 static bool DetectRunTxInspectRule(ThreadVars *tv,
1123  DetectEngineCtx *de_ctx,
1124  DetectEngineThreadCtx *det_ctx,
1125  Packet *p,
1126  Flow *f,
1127  const uint8_t in_flow_flags, // direction, EOF, etc
1128  void *alstate,
1129  DetectTransaction *tx,
1130  const Signature *s,
1131  uint32_t *stored_flags,
1132  RuleMatchCandidateTx *can,
1133  DetectRunScratchpad *scratch)
1134 {
1135  uint8_t flow_flags = in_flow_flags;
1136  const int direction = (flow_flags & STREAM_TOSERVER) ? 0 : 1;
1137  uint32_t inspect_flags = stored_flags ? *stored_flags : 0;
1138  int total_matches = 0;
1139  int file_no_match = 0;
1140  bool retval = false;
1141  bool mpm_before_progress = false; // is mpm engine before progress?
1142  bool mpm_in_progress = false; // is mpm engine in a buffer we will revisit?
1143 
1144  /* see if we want to pass on the FLUSH flag */
1145  if ((s->flags & SIG_FLAG_FLUSH) == 0)
1146  flow_flags &=~ STREAM_FLUSH;
1147 
1148  TRACE_SID_TXS(s->id, tx, "starting %s", direction ? "toclient" : "toserver");
1149 
1150  /* for a new inspection we inspect pkt header and packet matches */
1151  if (likely(stored_flags == NULL)) {
1152  TRACE_SID_TXS(s->id, tx, "first inspect, run packet matches");
1153  if (DetectRunInspectRuleHeader(p, f, s, s->flags, s->proto.flags) == 0) {
1154  TRACE_SID_TXS(s->id, tx, "DetectRunInspectRuleHeader() no match");
1155  return false;
1156  }
1157  if (DetectRunInspectRulePacketMatches(tv, det_ctx, p, f, s) == 0) {
1158  TRACE_SID_TXS(s->id, tx, "DetectRunInspectRulePacketMatches no match");
1159  return false;
1160  }
1161  /* stream mpm and negated mpm sigs can end up here with wrong proto */
1162  if (!(f->alproto == s->alproto || s->alproto == ALPROTO_UNKNOWN)) {
1163  TRACE_SID_TXS(s->id, tx, "alproto mismatch");
1164  return false;
1165  }
1166  }
1167 
1168  const DetectEngineAppInspectionEngine *engine = s->app_inspect;
1169  while (engine != NULL) { // TODO could be do {} while as s->app_inspect cannot be null
1170  TRACE_SID_TXS(s->id, tx, "engine %p inspect_flags %x", engine, inspect_flags);
1171  if (!(inspect_flags & BIT_U32(engine->id)) &&
1172  direction == engine->dir)
1173  {
1174  const bool skip_engine = (engine->alproto != 0 && engine->alproto != f->alproto);
1175  /* special case: file_data on 'alert tcp' will have engines
1176  * in the list that are not for us. */
1177  if (unlikely(skip_engine)) {
1178  engine = engine->next;
1179  continue;
1180  }
1181 
1182  /* engines are sorted per progress, except that the one with
1183  * mpm/prefilter enabled is first */
1184  if (tx->tx_progress < engine->progress) {
1185  SCLogDebug("tx progress %d < engine progress %d",
1186  tx->tx_progress, engine->progress);
1187  break;
1188  }
1189  if (engine->mpm) {
1190  if (tx->tx_progress > engine->progress) {
1191  mpm_before_progress = true;
1192  } else if (tx->tx_progress == engine->progress) {
1193  mpm_in_progress = true;
1194  }
1195  }
1196 
1197  /* run callback: but bypass stream callback if we can */
1198  int match;
1199  if (unlikely(engine->stream && can->stream_stored)) {
1200  match = can->stream_result;
1201  TRACE_SID_TXS(s->id, tx, "stream skipped, stored result %d used instead", match);
1202  } else {
1203  KEYWORD_PROFILING_SET_LIST(det_ctx, engine->sm_list);
1204  if (engine->Callback) {
1205  match = engine->Callback(tv, de_ctx, det_ctx,
1206  s, engine->smd, f, flow_flags, alstate, tx->tx_ptr, tx->tx_id);
1207  } else {
1208  BUG_ON(engine->v2.Callback == NULL);
1209  match = engine->v2.Callback(de_ctx, det_ctx, engine,
1210  s, f, flow_flags, alstate, tx->tx_ptr, tx->tx_id);
1211  }
1212  TRACE_SID_TXS(s->id, tx, "engine %p match %d", engine, match);
1213  if (engine->stream) {
1214  can->stream_stored = true;
1215  can->stream_result = match;
1216  TRACE_SID_TXS(s->id, tx, "stream ran, store result %d for next tx (if any)", match);
1217  }
1218  }
1219  if (match == DETECT_ENGINE_INSPECT_SIG_MATCH) {
1220  inspect_flags |= BIT_U32(engine->id);
1221  engine = engine->next;
1222  total_matches++;
1223  continue;
1224  } else if (match == DETECT_ENGINE_INSPECT_SIG_MATCH_MORE_FILES) {
1225  /* if the file engine matched, but indicated more
1226  * files are still in progress, we don't set inspect
1227  * flags as these would end inspection for this tx */
1228  engine = engine->next;
1229  total_matches++;
1230  continue;
1231  } else if (match == DETECT_ENGINE_INSPECT_SIG_CANT_MATCH) {
1232  inspect_flags |= DE_STATE_FLAG_SIG_CANT_MATCH;
1233  inspect_flags |= BIT_U32(engine->id);
1234  } else if (match == DETECT_ENGINE_INSPECT_SIG_CANT_MATCH_FILESTORE) {
1235  inspect_flags |= DE_STATE_FLAG_SIG_CANT_MATCH;
1236  inspect_flags |= BIT_U32(engine->id);
1237  file_no_match = 1;
1238  }
1239  /* implied DETECT_ENGINE_INSPECT_SIG_NO_MATCH */
1240  if (engine->mpm && mpm_before_progress) {
1241  inspect_flags |= DE_STATE_FLAG_SIG_CANT_MATCH;
1242  inspect_flags |= BIT_U32(engine->id);
1243  }
1244  break;
1245  }
1246  engine = engine->next;
1247  }
1248  TRACE_SID_TXS(s->id, tx, "inspect_flags %x, total_matches %u, engine %p",
1249  inspect_flags, total_matches, engine);
1250 
1251  if (engine == NULL && total_matches) {
1252  inspect_flags |= DE_STATE_FLAG_FULL_INSPECT;
1253  TRACE_SID_TXS(s->id, tx, "MATCH");
1254  retval = true;
1255  }
1256 
1257  if (stored_flags) {
1258  *stored_flags = inspect_flags;
1259  TRACE_SID_TXS(s->id, tx, "continue inspect flags %08x", inspect_flags);
1260  } else {
1261  // store... or? If tx is done we might not want to come back to this tx
1262 
1263  // also... if mpmid tracking is enabled, we won't do a sig again for this tx...
1264  TRACE_SID_TXS(s->id, tx, "start inspect flags %08x", inspect_flags);
1265  if (inspect_flags & DE_STATE_FLAG_SIG_CANT_MATCH) {
1266  if (file_no_match) {
1267  /* if we have a mismatch on a file sig, we need to keep state.
1268  * We may get another file on the same tx (for http and smtp
1269  * at least), so for a new file we need to re-eval the sig.
1270  * Thoughts / TODO:
1271  * - not for some protos that have 1 file per tx (e.g. nfs)
1272  * - maybe we only need this for file sigs that mix with
1273  * other matches? E.g. 'POST + filename', is different than
1274  * just 'filename'.
1275  */
1276  DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s,
1277  inspect_flags, flow_flags, file_no_match);
1278  }
1279  } else if ((inspect_flags & DE_STATE_FLAG_FULL_INSPECT) && mpm_before_progress) {
1280  TRACE_SID_TXS(s->id, tx, "no need to store match sig, "
1281  "mpm won't trigger for it anymore");
1282 
1283  if (inspect_flags & DE_STATE_FLAG_FILE_INSPECT) {
1284  TRACE_SID_TXS(s->id, tx, "except that for new files, "
1285  "we may have to revisit anyway");
1286  DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s,
1287  inspect_flags, flow_flags, file_no_match);
1288  }
1289  } else if ((inspect_flags & DE_STATE_FLAG_FULL_INSPECT) == 0 && mpm_in_progress) {
1290  TRACE_SID_TXS(s->id, tx, "no need to store no-match sig, "
1291  "mpm will revisit it");
1292  } else {
1293  TRACE_SID_TXS(s->id, tx, "storing state: flags %08x", inspect_flags);
1294  DetectRunStoreStateTx(scratch->sgh, f, tx->tx_ptr, tx->tx_id, s,
1295  inspect_flags, flow_flags, file_no_match);
1296  }
1297  }
1298 
1299  return retval;
1300 }
1301 
1302 /** \internal
1303  * \brief get a DetectTransaction object
1304  * \retval struct filled with relevant info or all nulls/0s
1305  */
1306 static DetectTransaction GetDetectTx(const uint8_t ipproto, const AppProto alproto,
1307  void *alstate, const uint64_t tx_id, void *tx_ptr, const int tx_end_state,
1308  const uint8_t flow_flags)
1309 {
1310  const uint64_t detect_flags = AppLayerParserGetTxDetectFlags(ipproto, alproto, tx_ptr, flow_flags);
1311  if (detect_flags & APP_LAYER_TX_INSPECTED_FLAG) {
1312  SCLogDebug("%"PRIu64" tx already fully inspected for %s. Flags %016"PRIx64,
1313  tx_id, flow_flags & STREAM_TOSERVER ? "toserver" : "toclient",
1314  detect_flags);
1315  DetectTransaction no_tx = { NULL, 0, NULL, 0, 0, 0, 0, 0, };
1316  return no_tx;
1317  }
1318 
1319  const int tx_progress = AppLayerParserGetStateProgress(ipproto, alproto, tx_ptr, flow_flags);
1320  const int dir_int = (flow_flags & STREAM_TOSERVER) ? 0 : 1;
1321  DetectEngineState *tx_de_state = AppLayerParserGetTxDetectState(ipproto, alproto, tx_ptr);
1322  DetectEngineStateDirection *tx_dir_state = tx_de_state ? &tx_de_state->dir_state[dir_int] : NULL;
1323  uint64_t prefilter_flags = detect_flags & APP_LAYER_TX_PREFILTER_MASK;
1324 
1325  DetectTransaction tx = {
1326  .tx_ptr = tx_ptr,
1327  .tx_id = tx_id,
1328  .de_state = tx_dir_state,
1329  .detect_flags = detect_flags,
1330  .prefilter_flags = prefilter_flags,
1331  .prefilter_flags_orig = prefilter_flags,
1332  .tx_progress = tx_progress,
1333  .tx_end_state = tx_end_state,
1334  };
1335  return tx;
1336 }
1337 
1338 static void DetectRunTx(ThreadVars *tv,
1339  DetectEngineCtx *de_ctx,
1340  DetectEngineThreadCtx *det_ctx,
1341  Packet *p,
1342  Flow *f,
1343  DetectRunScratchpad *scratch)
1344 {
1345  const uint8_t flow_flags = scratch->flow_flags;
1346  const SigGroupHead * const sgh = scratch->sgh;
1347  void * const alstate = f->alstate;
1348  const uint8_t ipproto = f->proto;
1349  const AppProto alproto = f->alproto;
1350 
1351  const uint64_t total_txs = AppLayerParserGetTxCnt(f, alstate);
1352  uint64_t tx_id_min = AppLayerParserGetTransactionInspectId(f->alparser, flow_flags);
1353  const int tx_end_state = AppLayerParserGetStateProgressCompletionStatus(alproto, flow_flags);
1354 
1355  AppLayerGetTxIteratorFunc IterFunc = AppLayerGetTxIterator(ipproto, alproto);
1356  AppLayerGetTxIterState state;
1357  memset(&state, 0, sizeof(state));
1358 
1359  while (1) {
1360  AppLayerGetTxIterTuple ires = IterFunc(ipproto, alproto, alstate, tx_id_min, total_txs, &state);
1361  if (ires.tx_ptr == NULL)
1362  break;
1363 
1364  DetectTransaction tx = GetDetectTx(ipproto, alproto,
1365  alstate, ires.tx_id, ires.tx_ptr, tx_end_state, flow_flags);
1366  if (tx.tx_ptr == NULL) {
1367  SCLogDebug("%p/%"PRIu64" no transaction to inspect",
1368  tx.tx_ptr, tx_id_min);
1369 
1370  tx_id_min++; // next (if any) run look for +1
1371  goto next;
1372  }
1373  tx_id_min = tx.tx_id + 1; // next look for cur + 1
1374 
1375  uint32_t array_idx = 0;
1376  uint32_t total_rules = det_ctx->match_array_cnt;
1377  total_rules += (tx.de_state ? tx.de_state->cnt : 0);
1378 
1379  /* run prefilter engines and merge results into a candidates array */
1380  if (sgh->tx_engines) {
1382  DetectRunPrefilterTx(det_ctx, sgh, p, ipproto, flow_flags, alproto,
1383  alstate, &tx);
1385  SCLogDebug("%p/%"PRIu64" rules added from prefilter: %u candidates",
1386  tx.tx_ptr, tx.tx_id, det_ctx->pmq.rule_id_array_cnt);
1387 
1388  total_rules += det_ctx->pmq.rule_id_array_cnt;
1389  if (!(RuleMatchCandidateTxArrayHasSpace(det_ctx, total_rules))) {
1390  RuleMatchCandidateTxArrayExpand(det_ctx, total_rules);
1391  }
1392 
1393  for (uint32_t i = 0; i < det_ctx->pmq.rule_id_array_cnt; i++) {
1394  const Signature *s = de_ctx->sig_array[det_ctx->pmq.rule_id_array[i]];
1395  const SigIntId id = s->num;
1396  det_ctx->tx_candidates[array_idx].s = s;
1397  det_ctx->tx_candidates[array_idx].id = id;
1398  det_ctx->tx_candidates[array_idx].flags = NULL;
1399  det_ctx->tx_candidates[array_idx].stream_reset = 0;
1400  array_idx++;
1401  }
1402  } else {
1403  if (!(RuleMatchCandidateTxArrayHasSpace(det_ctx, total_rules))) {
1404  RuleMatchCandidateTxArrayExpand(det_ctx, total_rules);
1405  }
1406  }
1407 
1408  /* merge 'state' rules from the regular prefilter */
1409  uint32_t x = array_idx;
1410  for (uint32_t i = 0; i < det_ctx->match_array_cnt; i++) {
1411  const Signature *s = det_ctx->match_array[i];
1412  if (s->app_inspect != NULL) {
1413  const SigIntId id = s->num;
1414  det_ctx->tx_candidates[array_idx].s = s;
1415  det_ctx->tx_candidates[array_idx].id = id;
1416  det_ctx->tx_candidates[array_idx].flags = NULL;
1417  det_ctx->tx_candidates[array_idx].stream_reset = 0;
1418  array_idx++;
1419 
1420  SCLogDebug("%p/%"PRIu64" rule %u (%u) added from 'match' list",
1421  tx.tx_ptr, tx.tx_id, s->id, id);
1422  }
1423  }
1424  SCLogDebug("%p/%"PRIu64" rules added from 'match' list: %u",
1425  tx.tx_ptr, tx.tx_id, array_idx - x); (void)x;
1426 
1427  /* merge stored state into results */
1428  if (tx.de_state != NULL) {
1429  const uint32_t old = array_idx;
1430 
1431  /* if tx.de_state->flags has 'new file' set and sig below has
1432  * 'file inspected' flag, reset the file part of the state */
1433  const bool have_new_file = (tx.de_state->flags & DETECT_ENGINE_STATE_FLAG_FILE_NEW);
1434  if (have_new_file) {
1435  SCLogDebug("%p/%"PRIu64" destate: need to consider new file",
1436  tx.tx_ptr, tx.tx_id);
1438  }
1439 
1440  SigIntId state_cnt = 0;
1441  DeStateStore *tx_store = tx.de_state->head;
1442  for (; tx_store != NULL; tx_store = tx_store->next) {
1443  SCLogDebug("tx_store %p", tx_store);
1444 
1445  SigIntId store_cnt = 0;
1446  for (store_cnt = 0;
1447  store_cnt < DE_STATE_CHUNK_SIZE && state_cnt < tx.de_state->cnt;
1448  store_cnt++, state_cnt++)
1449  {
1450  DeStateStoreItem *item = &tx_store->store[store_cnt];
1451  SCLogDebug("rule id %u, inspect_flags %u", item->sid, item->flags);
1452  if (have_new_file && (item->flags & DE_STATE_FLAG_FILE_INSPECT)) {
1453  /* remove part of the state. File inspect engine will now
1454  * be able to run again */
1456  SCLogDebug("rule id %u, post file reset inspect_flags %u", item->sid, item->flags);
1457  }
1458  det_ctx->tx_candidates[array_idx].s = de_ctx->sig_array[item->sid];
1459  det_ctx->tx_candidates[array_idx].id = item->sid;
1460  det_ctx->tx_candidates[array_idx].flags = &item->flags;
1461  det_ctx->tx_candidates[array_idx].stream_reset = 0;
1462  array_idx++;
1463  }
1464  }
1465  if (old && old != array_idx) {
1466  qsort(det_ctx->tx_candidates, array_idx, sizeof(RuleMatchCandidateTx),
1467  DetectRunTxSortHelper);
1468 
1469  SCLogDebug("%p/%"PRIu64" rules added from 'continue' list: %u",
1470  tx.tx_ptr, tx.tx_id, array_idx - old);
1471  }
1472  }
1473 
1474  det_ctx->tx_id = tx.tx_id;
1475  det_ctx->tx_id_set = 1;
1476  det_ctx->p = p;
1477 
1478  /* run rules: inspect the match candidates */
1479  for (uint32_t i = 0; i < array_idx; i++) {
1480  RuleMatchCandidateTx *can = &det_ctx->tx_candidates[i];
1481  const Signature *s = det_ctx->tx_candidates[i].s;
1482  uint32_t *inspect_flags = det_ctx->tx_candidates[i].flags;
1483 
1484  /* deduplicate: rules_array is sorted, but not deduplicated:
1485  * both mpm and stored state could give us the same sid.
1486  * As they are back to back in that case we can check for it
1487  * here. We select the stored state one. */
1488  if ((i + 1) < array_idx) {
1489  if (det_ctx->tx_candidates[i].s == det_ctx->tx_candidates[i+1].s) {
1490  if (det_ctx->tx_candidates[i].flags != NULL) {
1491  i++;
1492  SCLogDebug("%p/%"PRIu64" inspecting SKIP NEXT: sid %u (%u), flags %08x",
1493  tx.tx_ptr, tx.tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
1494  } else if (det_ctx->tx_candidates[i+1].flags != NULL) {
1495  SCLogDebug("%p/%"PRIu64" inspecting SKIP CURRENT: sid %u (%u), flags %08x",
1496  tx.tx_ptr, tx.tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
1497  continue;
1498  } else {
1499  // if it's all the same, inspect the current one and skip next.
1500  i++;
1501  SCLogDebug("%p/%"PRIu64" inspecting SKIP NEXT: sid %u (%u), flags %08x",
1502  tx.tx_ptr, tx.tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
1503  }
1504  }
1505  }
1506 
1507  SCLogDebug("%p/%"PRIu64" inspecting: sid %u (%u), flags %08x",
1508  tx.tx_ptr, tx.tx_id, s->id, s->num, inspect_flags ? *inspect_flags : 0);
1509 
1510  if (inspect_flags) {
1512  SCLogDebug("%p/%"PRIu64" inspecting: sid %u (%u), flags %08x ALREADY COMPLETE",
1513  tx.tx_ptr, tx.tx_id, s->id, s->num, *inspect_flags);
1514  continue;
1515  }
1516  }
1517 
1518  if (inspect_flags) {
1519  /* continue previous inspection */
1520  SCLogDebug("%p/%"PRIu64" Continueing sid %u", tx.tx_ptr, tx.tx_id, s->id);
1521  } else {
1522  /* start new inspection */
1523  SCLogDebug("%p/%"PRIu64" Start sid %u", tx.tx_ptr, tx.tx_id, s->id);
1524  }
1525 
1526  /* call individual rule inspection */
1528  const int r = DetectRunTxInspectRule(tv, de_ctx, det_ctx, p, f, flow_flags,
1529  alstate, &tx, s, inspect_flags, can, scratch);
1530  if (r == 1) {
1531  /* match */
1532  DetectRunPostMatch(tv, det_ctx, p, s);
1533 
1534  uint8_t alert_flags = (PACKET_ALERT_FLAG_STATE_MATCH|PACKET_ALERT_FLAG_TX);
1535  if (s->action & ACTION_DROP)
1536  alert_flags |= PACKET_ALERT_FLAG_DROP_FLOW;
1537 
1538  SCLogDebug("%p/%"PRIu64" sig %u (%u) matched", tx.tx_ptr, tx.tx_id, s->id, s->num);
1539  if (!(s->flags & SIG_FLAG_NOALERT)) {
1540  PacketAlertAppend(det_ctx, s, p, tx.tx_id, alert_flags);
1541  } else {
1542  DetectSignatureApplyActions(p, s, alert_flags);
1543  }
1544  }
1545  DetectVarProcessList(det_ctx, p->flow, p);
1546  RULE_PROFILING_END(det_ctx, s, r, p);
1547  }
1548 
1549  det_ctx->tx_id = 0;
1550  det_ctx->tx_id_set = 0;
1551  det_ctx->p = NULL;
1552 
1553  /* see if we have any updated state to store in the tx */
1554 
1555  uint64_t new_detect_flags = 0;
1556  /* this side of the tx is done */
1557  if (tx.tx_progress >= tx.tx_end_state) {
1558  new_detect_flags |= APP_LAYER_TX_INSPECTED_FLAG;
1559  SCLogDebug("%p/%"PRIu64" tx is done for direction %s. Flag %016"PRIx64,
1560  tx.tx_ptr, tx.tx_id,
1561  flow_flags & STREAM_TOSERVER ? "toserver" : "toclient",
1562  new_detect_flags);
1563  }
1564  if (tx.prefilter_flags != tx.prefilter_flags_orig) {
1565  new_detect_flags |= tx.prefilter_flags;
1566  SCLogDebug("%p/%"PRIu64" updated prefilter flags %016"PRIx64" "
1567  "(was: %016"PRIx64") for direction %s. Flag %016"PRIx64,
1569  flow_flags & STREAM_TOSERVER ? "toserver" : "toclient",
1570  new_detect_flags);
1571  }
1572  if (new_detect_flags != 0 &&
1573  (new_detect_flags | tx.detect_flags) != tx.detect_flags)
1574  {
1575  new_detect_flags |= tx.detect_flags;
1576  SCLogDebug("%p/%"PRIu64" Storing new flags %016"PRIx64" (was %016"PRIx64")",
1577  tx.tx_ptr, tx.tx_id, new_detect_flags, tx.detect_flags);
1578  AppLayerParserSetTxDetectFlags(ipproto, alproto, tx.tx_ptr,
1579  flow_flags, new_detect_flags);
1580  }
1581 next:
1582  InspectionBufferClean(det_ctx);
1583 
1584  if (!ires.has_next)
1585  break;
1586  }
1587 }
1588 
1589 /** \brief Apply action(s) and Set 'drop' sig info,
1590  * if applicable */
1592  const Signature *s, const uint8_t alert_flags)
1593 {
1595 
1596  if (s->action & ACTION_DROP) {
1597  if (p->alerts.drop.action == 0) {
1598  p->alerts.drop.num = s->num;
1599  p->alerts.drop.action = s->action;
1600  p->alerts.drop.s = (Signature *)s;
1601  }
1602  } else if (s->action & ACTION_PASS) {
1603  /* if an stream/app-layer match we enforce the pass for the flow */
1604  if ((p->flow != NULL) &&
1606  {
1607  FlowSetNoPacketInspectionFlag(p->flow);
1608  }
1609 
1610  }
1611 }
1612 
1613 static DetectEngineThreadCtx *GetTenantById(HashTable *h, uint32_t id)
1614 {
1615  /* technically we need to pass a DetectEngineThreadCtx struct with the
1616  * tentant_id member. But as that member is the first in the struct, we
1617  * can use the id directly. */
1618  return HashTableLookup(h, &id, 0);
1619 }
1620 
1621 static void DetectFlow(ThreadVars *tv,
1622  DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
1623  Packet *p)
1624 {
1625  if (p->flags & PKT_NOPACKET_INSPECTION) {
1626  /* hack: if we are in pass the entire flow mode, we need to still
1627  * update the inspect_id forward. So test for the condition here,
1628  * and call the update code if necessary. */
1629  const int pass = ((p->flow->flags & FLOW_NOPACKET_INSPECTION));
1630  const AppProto alproto = FlowGetAppProtocol(p->flow);
1631  if (pass && AppLayerParserProtocolSupportsTxs(p->proto, alproto)) {
1632  uint8_t flags;
1633  if (p->flowflags & FLOW_PKT_TOSERVER) {
1634  flags = STREAM_TOSERVER;
1635  } else {
1636  flags = STREAM_TOCLIENT;
1637  }
1638  flags = FlowGetDisruptionFlags(p->flow, flags);
1639  DeStateUpdateInspectTransactionId(p->flow, flags, true);
1640  }
1641  SCLogDebug("p->pcap %"PRIu64": no detection on packet, "
1642  "PKT_NOPACKET_INSPECTION is set", p->pcap_cnt);
1643  return;
1644  }
1645 
1646  /* see if the packet matches one or more of the sigs */
1647  (void)DetectRun(tv, de_ctx, det_ctx, p);
1648 }
1649 
1650 
1651 static void DetectNoFlow(ThreadVars *tv,
1652  DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
1653  Packet *p)
1654 {
1655  /* No need to perform any detection on this packet, if the the given flag is set.*/
1656  if ((p->flags & PKT_NOPACKET_INSPECTION) ||
1658  {
1659  return;
1660  }
1661 
1662  /* see if the packet matches one or more of the sigs */
1663  DetectRun(tv, de_ctx, det_ctx, p);
1664  return;
1665 }
1666 
1667 /** \brief Detection engine thread wrapper.
1668  * \param tv thread vars
1669  * \param p packet to inspect
1670  * \param data thread specific data
1671  * \param pq packet queue
1672  * \retval TM_ECODE_FAILED error
1673  * \retval TM_ECODE_OK ok
1674  */
1675 TmEcode Detect(ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
1676 {
1678 
1679  DetectEngineCtx *de_ctx = NULL;
1680  DetectEngineThreadCtx *det_ctx = (DetectEngineThreadCtx *)data;
1681  if (det_ctx == NULL) {
1682  printf("ERROR: Detect has no thread ctx\n");
1683  goto error;
1684  }
1685 
1686  if (unlikely(SC_ATOMIC_GET(det_ctx->so_far_used_by_detect) == 0)) {
1687  (void)SC_ATOMIC_SET(det_ctx->so_far_used_by_detect, 1);
1688  SCLogDebug("Detect Engine using new det_ctx - %p",
1689  det_ctx);
1690  }
1691 
1692  /* if in MT mode _and_ we have tenants registered, use
1693  * MT logic. */
1694  if (det_ctx->mt_det_ctxs_cnt > 0 && det_ctx->TenantGetId != NULL)
1695  {
1696  uint32_t tenant_id = p->tenant_id;
1697  if (tenant_id == 0)
1698  tenant_id = det_ctx->TenantGetId(det_ctx, p);
1699  if (tenant_id > 0 && tenant_id < det_ctx->mt_det_ctxs_cnt) {
1700  p->tenant_id = tenant_id;
1701  det_ctx = GetTenantById(det_ctx->mt_det_ctxs_hash, tenant_id);
1702  if (det_ctx == NULL)
1703  return TM_ECODE_OK;
1704  de_ctx = det_ctx->de_ctx;
1705  if (de_ctx == NULL)
1706  return TM_ECODE_OK;
1707 
1708  if (unlikely(SC_ATOMIC_GET(det_ctx->so_far_used_by_detect) == 0)) {
1709  (void)SC_ATOMIC_SET(det_ctx->so_far_used_by_detect, 1);
1710  SCLogDebug("MT de_ctx %p det_ctx %p (tenant %u)", de_ctx, det_ctx, tenant_id);
1711  }
1712  } else {
1713  /* use default if no tenants are registered for this packet */
1714  de_ctx = det_ctx->de_ctx;
1715  }
1716  } else {
1717  de_ctx = det_ctx->de_ctx;
1718  }
1719 
1720  if (p->flow) {
1721  DetectFlow(tv, de_ctx, det_ctx, p);
1722  } else {
1723  DetectNoFlow(tv, de_ctx, det_ctx, p);
1724  }
1725  return TM_ECODE_OK;
1726 error:
1727  return TM_ECODE_FAILED;
1728 }
1729 
1730 /** \brief disable file features we don't need
1731  * Called if we have no detection engine.
1732  */
1734 {
1735  DetectPostInspectFileFlagsUpdate(f, NULL /* no sgh */, STREAM_TOSERVER);
1736  DetectPostInspectFileFlagsUpdate(f, NULL /* no sgh */, STREAM_TOCLIENT);
1737 }
1738 
1739 #ifdef UNITTESTS
1740 /**
1741  * \brief wrapper for old tests
1742  */
1744  DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
1745  Packet *p)
1746 {
1747  DetectRun(th_v, de_ctx, det_ctx, p);
1748 }
1749 #endif
1750 
1751 /*
1752  * TESTS
1753  */
1754 
1755 #ifdef UNITTESTS
1756 #include "tests/detect.c"
1757 #endif
1758 
void RuleMatchCandidateTxArrayInit(DetectEngineThreadCtx *det_ctx, uint32_t size)
Definition: detect.c:1039
uint16_t filestore_cnt
Definition: detect.h:1314
#define PACKET_ALERT_FLAG_STREAM_MATCH
Definition: decode.h:282
SigTableElmt sigmatch_table[DETECT_TBLSIZE]
Definition: detect.h:1406
SignatureNonPrefilterStore * non_pf_syn_store_array
Definition: detect.h:1310
DetectProto proto
Definition: detect.h:512
uint16_t flags
#define DETECT_PROTO_IPV6
#define SCLogDebug(...)
Definition: util-debug.h:335
Signature ** sig_array
Definition: detect.h:738
uint32_t tx_candidates_size
Definition: detect.h:1053
struct Flow_ * flow
Definition: decode.h:443
#define KEYWORD_PROFILING_END(ctx, type, m)
#define SignatureMask
Definition: detect.h:282
void PacketPatternCleanup(DetectEngineThreadCtx *det_ctx)
cleans up the mpm instance after a match
struct HtpBodyChunk_ * next
#define PACKET_ALERT_FLAG_TX
Definition: decode.h:284
const struct SigGroupHead_ * sgh_toclient
Definition: flow.h:437
const Signature * s
Definition: detect.h:959
#define KEYWORD_PROFILING_SET_LIST(ctx, list)
uint16_t dsize_high
Definition: detect.h:502
int FileForceSha256(void)
Definition: util-file.c:145
#define BUG_ON(x)
uint32_t non_pf_store_cnt
Definition: detect.h:1056
#define PACKET_TEST_ACTION(p, a)
Definition: decode.h:860
uint32_t flags
Definition: detect.h:496
uint8_t proto
Definition: flow.h:343
int AppLayerParserGetStateProgressCompletionStatus(AppProto alproto, uint8_t direction)
uint32_t id
Definition: detect.h:528
#define ICMPV4_DEST_UNREACH_IS_VALID(p)
struct SigGroupHead_ * sh
Definition: detect.h:207
#define DE_STATE_FLAG_SIG_CANT_MATCH
int DetectEngineInspectStreamPayload(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const Signature *s, Flow *f, Packet *p)
Do the content inspection & validation for a signature on the raw stream.
int AppLayerParserGetStateProgress(uint8_t ipproto, AppProto alproto, void *alstate, uint8_t flags)
get the progress value for a tx/protocol
#define DETECT_ENGINE_THREAD_CTX_STREAM_CONTENT_MATCH
Definition: detect.h:284
uint32_t non_pf_other_store_cnt
Definition: detect.h:1306
uint16_t counter_fnonmpm_list
Definition: detect.h:1006
#define unlikely(expr)
Definition: util-optimize.h:35
#define SIG_GROUP_HEAD_HAVEFILEMD5
Definition: detect.h:1195
uint8_t is_last
Definition: detect.h:333
Port sp
Definition: decode.h:413
uint64_t AppLayerParserGetTxCnt(const Flow *f, void *alstate)
void StreamReassembleRawUpdateProgress(TcpSession *ssn, Packet *p, uint64_t progress)
update stream engine after detection
void FlowSetIPOnlyFlag(Flow *f, int direction)
Set the IPOnly scanned flag for &#39;direction&#39;.
Definition: flow.c:186
#define FLOW_TOCLIENT_IPONLY_SET
Definition: flow.h:55
void RuleMatchCandidateTxArrayFree(DetectEngineThreadCtx *det_ctx)
Definition: detect.c:1052
void FileDisableFilesize(Flow *f, uint8_t direction)
disable file size tracking for this flow
Definition: util-file.c:1184
void PacketCreateMask(Packet *p, SignatureMask *mask, AppProto alproto, bool app_decoder_events)
#define PKT_IS_FRAGMENT
Definition: decode.h:1107
uint32_t tenant_id
Definition: flow.h:369
DetectEngineStateDirection dir_state[2]
Port dp
Definition: decode.h:421
void FileDisableSha1(Flow *f, uint8_t direction)
disable file sha1 calc for this flow
Definition: util-file.c:1106
void FileDisableMd5(Flow *f, uint8_t direction)
disable file md5 calc for this flow
Definition: util-file.c:1067
uint8_t action
Definition: decode.h:269
#define FLOW_ACTION_DROP
Definition: flow.h:63
#define SIG_GROUP_HEAD_HAVEFILESHA256
Definition: detect.h:1198
RuleMatchCandidateTx * tx_candidates
Definition: detect.h:1052
#define SIG_FLAG_REQUIRE_STREAM
Definition: detect.h:229
SigIntId * non_pf_id_array
Definition: detect.h:976
uint16_t pad
Address dst
Definition: decode.h:411
DetectEngineStateDirection * de_state
#define FLOW_PKT_ESTABLISHED
Definition: flow.h:202
#define PKT_IS_IPV6(p)
Definition: decode.h:250
void RulesDumpMatchArray(const DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, const Packet *p)
Data needed for Match()
Definition: detect.h:331
Container for matching data for a signature group.
Definition: detect.h:1298
bool StreamReassembleRawHasDataReady(TcpSession *ssn, Packet *p)
does the stream engine have data to inspect?
uint64_t pcap_cnt
Definition: decode.h:561
#define SIG_FLAG_REQUIRE_FLOWVAR
Definition: detect.h:237
AppLayerGetTxIteratorFunc AppLayerGetTxIterator(const uint8_t ipproto, const AppProto alproto)
#define SIG_FLAG_REQUIRE_PACKET
Definition: detect.h:228
#define FLOW_TOSERVER_IPONLY_SET
Definition: flow.h:53
AppProto FlowGetAppProtocol(const Flow *f)
Definition: flow.c:1060
uint32_t non_pf_syn_store_cnt
Definition: detect.h:1307
uint16_t AppProto
TCPHdr * tcph
Definition: decode.h:520
#define PACKET_ALERT_FLAG_DROP_FLOW
Definition: decode.h:278
Signature container.
Definition: detect.h:495
#define DEBUG_VALIDATE_PACKET(p)
uint8_t action
Definition: detect.h:508
uint16_t addr_src_match6_cnt
Definition: detect.h:521
void IPOnlyMatchPacket(ThreadVars *tv, const DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const DetectEngineIPOnlyCtx *io_ctx, DetectEngineIPOnlyThreadCtx *io_tctx, Packet *p)
Match a packet against the IP Only detection engine contexts.
uint8_t FlowGetDisruptionFlags(const Flow *f, uint8_t flags)
get &#39;disruption&#39; flags: GAP/DEPTH/PASS
Definition: flow.c:1077
#define SIG_FLAG_APPLAYER
Definition: detect.h:223
void DetectRunStoreStateTx(const SigGroupHead *sgh, Flow *f, void *tx, uint64_t tx_id, const Signature *s, uint32_t inspect_flags, uint8_t flow_flags, const uint16_t file_no_match)
struct SigGroupHead_ * decoder_event_sgh
Definition: detect.h:821
#define PKT_IS_IPV4(p)
Definition: decode.h:249
void * protoctx
Definition: flow.h:395
SigIntId num
Definition: decode.h:268
struct DeStateStore_ * next
struct DetectEngineAppInspectionEngine_::@92 v2
DetectMatchAddressIPv6 * addr_dst_match6
Definition: detect.h:525
SigIntId num
Definition: detect.h:505
uint64_t AppLayerParserGetTransactionInspectId(AppLayerParserState *pstate, uint8_t direction)
int FileForceMd5(void)
Definition: util-file.c:135
main detection engine ctx
Definition: detect.h:723
uint16_t addr_src_match4_cnt
Definition: detect.h:519
PrefilterEngine * tx_engines
Definition: detect.h:1320
const uint8_t flow_flags
Definition: detect.c:64
const uint64_t prefilter_flags_orig
int DetectAddressMatchIPv6(const DetectMatchAddressIPv6 *addrs, uint16_t addrs_cnt, const Address *a)
Match a packets address against a signatures addrs array.
const struct Signature_ * s
Definition: decode.h:271
DetectPort * udp
Definition: detect.h:662
#define SIG_FLAG_DST_ANY
Definition: detect.h:217
void * alstate
Definition: flow.h:433
#define APP_LAYER_TX_INSPECTED_FLAG
DetectMatchAddressIPv4 * addr_dst_match4
Definition: detect.h:522
int DetectEngineInspectPacketPayload(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const Signature *s, Flow *f, Packet *p)
Do the content inspection & validation for a signature.
#define KEYWORD_PROFILING_START
const bool app_decoder_events
Definition: detect.c:65
#define FLOW_NOPACKET_INSPECTION
Definition: flow.h:58
#define SCCalloc(nm, a)
Definition: util-mem.h:197
DetectMatchAddressIPv6 * addr_src_match6
Definition: detect.h:526
DetectPort * dp
Definition: detect.h:534
#define SIG_FLAG_SP_ANY
Definition: detect.h:218
DetectPort * tcp
Definition: detect.h:661
void DetectRunPrefilterTx(DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, Packet *p, const uint8_t ipproto, const uint8_t flow_flags, const AppProto alproto, void *alstate, DetectTransaction *tx)
run prefilter engines on a transaction
uint8_t proto
Definition: decode.h:428
struct SigGroupHead_ * sgh[256]
Definition: detect.h:663
#define DETECT_ENGINE_INSPECT_SIG_MATCH
DetectPort * DetectPortLookupGroup(DetectPort *dp, uint16_t port)
Function that find the group matching address in a group head.
uint16_t filestore_cnt
Definition: detect.h:999
Data structures and function prototypes for keeping state for the detection engine.
void FileDisableMagic(Flow *f, uint8_t direction)
disable file magic lookups for this flow
Definition: util-file.c:1036
struct DetectEngineAppInspectionEngine_ * next
Definition: detect.h:424
#define PKT_DETECT_HAS_STREAMDATA
Definition: decode.h:1122
#define SIG_FLAG_FLUSH
Definition: detect.h:233
uint16_t counter_alerts
Definition: detect.h:1002
uint32_t(* TenantGetId)(const void *, const Packet *p)
Definition: detect.h:986
void Prefilter(DetectEngineThreadCtx *det_ctx, const SigGroupHead *sgh, Packet *p, const uint8_t flags)
DetectMatchAddressIPv4 * addr_src_match4
Definition: detect.h:523
#define STREAM_EOF
Definition: stream.h:30
#define APP_LAYER_TX_PREFILTER_MASK
void DeStateUpdateInspectTransactionId(Flow *f, const uint8_t flags, const bool tag_txs_as_inspected)
update flow&#39;s inspection id&#39;s
void SigMatchSignatures(ThreadVars *th_v, DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, Packet *p)
wrapper for old tests
Definition: detect.c:1743
#define SCEnter(...)
Definition: util-debug.h:337
PrefilterRuleStore pmq
Definition: detect.h:1064
uint32_t profile_match_logging_threshold
Definition: detect.h:848
uint8_t flowflags
Definition: decode.h:437
uint16_t counter_match_list
Definition: detect.h:1007
PacketEngineEvents events
Definition: decode.h:565
SigMatchData * sm_arrays[DETECT_SM_LIST_MAX]
Definition: detect.h:547
uint16_t addr_dst_match6_cnt
Definition: detect.h:520
#define FLOW_SGH_TOCLIENT
Definition: flow.h:68
#define STREAM_TOCLIENT
Definition: stream.h:32
#define PACKET_PROFILING_DETECT_END(p, id)
#define FLOW_PKT_TOSERVER
Definition: flow.h:200
HashTable * mt_det_ctxs_hash
Definition: detect.h:981
SigIntId match_array_cnt
Definition: detect.h:1050
AppProto alproto
Definition: detect.h:499
#define SIG_GROUP_HEAD_HAVEFILESHA1
Definition: detect.h:1197
void DetectSignatureApplyActions(Packet *p, const Signature *s, const uint8_t alert_flags)
Apply action(s) and Set &#39;drop&#39; sig info, if applicable.
Definition: detect.c:1591
SigIntId * rule_id_array
#define DETECT_ENGINE_STATE_FLAG_FILE_NEW
uint32_t flags
Definition: detect.h:1299
void FileDisableStoring(Flow *f, uint8_t direction)
disable file storage for a flow
Definition: util-file.c:1004
uint8_t proto
uint32_t stream_reset
Definition: detect.h:956
const AppProto alproto
Definition: detect.c:63
InspectEngineFuncPtr Callback
Definition: detect.h:413
#define RULE_PROFILING_START(p)
DetectEngineIPOnlyCtx io_ctx
Definition: detect.h:769
GenericVar * flowvar
Definition: flow.h:443
#define PACKET_UPDATE_ACTION(p, a)
Definition: decode.h:865
const uint64_t detect_flags
#define SIG_GROUP_HEAD_HAVERAWSTREAM
Definition: detect.h:1191
#define DETECT_PROTO_IPV4
void DetectEngineStateResetTxs(Flow *f)
Reset de state for active tx&#39; To be used on detect engine reload.
#define SCRealloc(x, a)
Definition: util-mem.h:182
#define STREAMTCP_STREAM_FLAG_DISABLE_RAW
const SigGroupHead * SigMatchSignaturesGetSgh(const DetectEngineCtx *de_ctx, const Packet *p)
Get the SigGroupHead for a packet.
Definition: detect.c:177
uint32_t version
Definition: detect.h:817
int FileForceFilestore(void)
Definition: util-file.c:111
int FileForceMagic(void)
Definition: util-file.c:130
SignatureMask pkt_mask
Definition: detect.c:67
void DisableDetectFlowFileFlags(Flow *f)
disable file features we don&#39;t need Called if we have no detection engine.
Definition: detect.c:1733
DeStateStoreItem store[DE_STATE_CHUNK_SIZE]
#define PACKET_DROP(p)
Definition: decode.h:850
#define DETECT_ENGINE_INSPECT_SIG_CANT_MATCH
#define SC_ATOMIC_SET(name, val)
Set the value for the atomic variable.
Definition: util-atomic.h:207
void * HashTableLookup(HashTable *ht, void *data, uint16_t datalen)
Definition: util-hash.c:193
DetectEngineCtx * de_ctx
Definition: detect.h:1089
const SigGroupHead * sgh
Definition: detect.c:66
uint16_t counter_nonmpm_list
Definition: detect.h:1005
uint64_t raw_stream_progress
Definition: detect.h:990
struct DetectRunScratchpad DetectRunScratchpad
uint8_t type
Definition: detect.h:332
#define TH_SYN
Definition: decode-tcp.h:36
#define SCFree(a)
Definition: util-mem.h:228
#define DETECT_ENGINE_INSPECT_SIG_MATCH_MORE_FILES
#define PKT_STREAM_EOF
Definition: decode.h:1091
#define SIG_FLAG_NOALERT
Definition: detect.h:221
DetectPort * sp
Definition: detect.h:534
uint16_t addr_dst_match4_cnt
Definition: detect.h:518
uint16_t tx_id
#define FLOW_PKT_TOSERVER_IPONLY_SET
Definition: flow.h:203
#define SIG_FLAG_DSIZE
Definition: detect.h:222
void PacketAlertFinalize(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...
#define STREAM_FLUSH
Definition: stream.h:36
PacketAlert drop
Definition: decode.h:295
void GenericVarFree(GenericVar *gv)
Definition: util-var.c:47
#define PKT_NOPACKET_INSPECTION
Definition: decode.h:1085
DetectEngineAppInspectionEngine * app_inspect
Definition: detect.h:543
int(* Match)(ThreadVars *, DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *)
Definition: detect.h:1132
const struct SigGroupHead_ * sgh_toserver
Definition: flow.h:440
void InspectionBufferClean(DetectEngineThreadCtx *det_ctx)
#define DETECT_ENGINE_INSPECT_SIG_CANT_MATCH_FILESTORE
#define PKT_IS_ICMPV4(p)
Definition: decode.h:253
#define FatalError(x,...)
Definition: util-debug.h:539
uint32_t rule_id_array_cnt
#define PKT_STREAM_ADD
Definition: decode.h:1089
#define STREAM_TOSERVER
Definition: stream.h:31
#define IP_GET_IPPROTO(p)
Definition: decode.h:261
#define SCReturnPtr(x, type)
Definition: util-debug.h:353
SCMutex m
Definition: flow-hash.h:105
#define PACKET_PROFILING_DETECT_START(p, id)
TmEcode Detect(ThreadVars *tv, Packet *p, void *data, PacketQueue *pq, PacketQueue *postpq)
Detection engine thread wrapper.
Definition: detect.c:1675
#define SC_ATOMIC_GET(name)
Get the value from the atomic variable.
Definition: util-atomic.h:192
PacketAlerts alerts
Definition: decode.h:555
#define TRACE_SID_TXS(sid, txs,...)
Definition: detect.c:1107
int DetectAddressMatchIPv4(const DetectMatchAddressIPv4 *addrs, uint16_t addrs_cnt, const Address *a)
Match a packets address against a signatures addrs array.
Signature ** match_array
Definition: detect.h:1045
SignatureMask mask
Definition: detect.h:943
int FileForceSha1(void)
Definition: util-file.c:140
#define PKT_HAS_FLOW
Definition: decode.h:1092
SignatureNonPrefilterStore * non_pf_store_ptr
Definition: detect.h:1055
int PacketAlertAppend(DetectEngineThreadCtx *det_ctx, const Signature *s, Packet *p, uint64_t tx_id, uint8_t flags)
append a signature match to a packet
#define PACKET_ALERT_FLAG_STATE_MATCH
Definition: decode.h:280
#define BIT_U32(n)
uint32_t de_ctx_version
Definition: flow.h:418
uint32_t * flags
Definition: detect.h:950
#define SIG_FLAG_DP_ANY
Definition: detect.h:219
DetectEngineIPOnlyThreadCtx io_ctx
Definition: detect.h:1071
DetectEngineLookupFlow flow_gh[FLOW_STATES]
Definition: detect.h:757
#define ACTION_PASS
uint8_t stream_result
Definition: detect.h:954
uint16_t cnt
Definition: decode.h:291
SignatureNonPrefilterStore * non_pf_other_store_array
Definition: detect.h:1308
#define SCReturn
Definition: util-debug.h:339
uint32_t tenant_id
Definition: decode.h:594
Per thread variable structure.
Definition: threadvars.h:57
void FileDisableSha256(Flow *f, uint8_t direction)
disable file sha256 calc for this flow
Definition: util-file.c:1145
#define FLOW_PKT_TOCLIENT_IPONLY_SET
Definition: flow.h:204
SignatureMask mask
Definition: detect.h:504
#define FLOW_PKT_TOCLIENT
Definition: flow.h:201
AppProto alproto
application level protocol
Definition: flow.h:404
uint16_t counter_mpm_list
Definition: detect.h:1004
#define ACTION_DROP
uint32_t flags
Definition: decode.h:441
DetectEngineState * AppLayerParserGetTxDetectState(uint8_t ipproto, AppProto alproto, void *tx)
void AppLayerParserSetTxDetectFlags(uint8_t ipproto, AppProto alproto, void *tx, uint8_t dir, uint64_t flags)
uint16_t payload_len
Definition: decode.h:541
void StatsAddUI64(ThreadVars *tv, uint16_t id, uint64_t x)
Adds a value of type uint64_t to the local counter.
Definition: counters.c:142
#define likely(expr)
Definition: util-optimize.h:32
uint32_t non_pf_id_cnt
Definition: detect.h:977
#define DE_STATE_FLAG_FULL_INSPECT
#define SIG_FLAG_SRC_ANY
Definition: detect.h:216
uint16_t dsize_low
Definition: detect.h:501
bool AppLayerParserHasDecoderEvents(AppLayerParserState *pstate)
#define FLOW_SGH_TOSERVER
Definition: flow.h:66
#define DE_STATE_FLAG_FILE_INSPECT
Flow data structure.
Definition: flow.h:324
uint32_t mt_det_ctxs_cnt
Definition: detect.h:979
int DetectProtoContainsProto(const DetectProto *dp, int proto)
see if a DetectProto contains a certain proto
#define SigIntId
uint32_t flags
Definition: flow.h:374
int AppLayerParserProtocolSupportsTxs(uint8_t ipproto, AppProto alproto)
#define RULE_PROFILING_END(ctx, r, m, p)
#define PKT_STREAM_EST
Definition: decode.h:1090
Port structure for detection engine.
Definition: detect.h:196
#define SIG_GROUP_HEAD_HAVEFILESIZE
Definition: detect.h:1196
AppLayerParserState * alparser
Definition: flow.h:432
Address src
Definition: decode.h:410
SigMatchCtx * ctx
Definition: detect.h:334
uint64_t AppLayerParserGetTxDetectFlags(uint8_t ipproto, AppProto alproto, void *tx, uint8_t dir)
#define DE_STATE_CHUNK_SIZE
#define DEBUG_VALIDATE_BUG_ON(exp)
#define SGH_PROFILING_RECORD(det_ctx, sgh)
AppLayerGetTxIterTuple(* AppLayerGetTxIteratorFunc)(const uint8_t ipproto, const AppProto alproto, void *alstate, uint64_t min_tx_id, uint64_t max_tx_id, AppLayerGetTxIterState *state)
tx iterator prototype