suricata
detect-engine-build.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2023 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 "detect.h"
20 #include "detect-engine.h"
21 #include "detect-parse.h"
22 #include "detect-content.h"
23 
24 #include "detect-engine-build.h"
25 #include "detect-engine-address.h"
26 #include "detect-engine-analyzer.h"
27 #include "detect-engine-iponly.h"
28 #include "detect-engine-mpm.h"
29 #include "detect-engine-siggroup.h"
30 #include "detect-engine-port.h"
32 #include "detect-engine-proto.h"
34 
35 #include "detect-dsize.h"
36 #include "detect-tcp-flags.h"
37 #include "detect-flow.h"
38 #include "detect-config.h"
39 #include "detect-flowbits.h"
40 #include "app-layer-events.h"
41 
43 #include "util-profiling.h"
44 #include "util-validate.h"
45 #include "util-var-name.h"
46 #include "util-conf.h"
47 
48 /* Magic numbers to make the rules of a certain order fall in the same group */
49 #define DETECT_PGSCORE_RULE_PORT_PRIORITIZED 111 /* Rule port group contains a priority port */
50 #define DETECT_PGSCORE_RULE_MPM_FAST_PATTERN 99 /* Rule contains an MPM fast pattern */
51 #define DETECT_PGSCORE_RULE_MPM_NEGATED 77 /* Rule contains a negated MPM */
52 #define DETECT_PGSCORE_RULE_NO_MPM 55 /* Rule does not contain MPM */
53 #define DETECT_PGSCORE_RULE_SYN_ONLY 33 /* Rule needs SYN check */
54 
56 {
57  if (de_ctx == NULL)
58  return;
59 
60  for (Signature *s = de_ctx->sig_list; s != NULL;) {
61  Signature *ns = s->next;
62  SigFree(de_ctx, s);
63  s = ns;
64  }
65  de_ctx->sig_list = NULL;
66 
68  de_ctx->sig_list = NULL;
69 }
70 
71 /** \brief Find a specific signature by sid and gid
72  * \param de_ctx detection engine ctx
73  * \param sid the signature id
74  * \param gid the signature group id
75  *
76  * \retval s sig found
77  * \retval NULL sig not found
78  */
80 {
81  if (de_ctx == NULL)
82  return NULL;
83 
84  for (Signature *s = de_ctx->sig_list; s != NULL; s = s->next) {
85  if (s->id == sid && s->gid == gid)
86  return s;
87  }
88 
89  return NULL;
90 }
91 
92 /**
93  * \brief Check if a signature contains the filestore keyword.
94  *
95  * \param s signature
96  *
97  * \retval 0 no
98  * \retval 1 yes
99  */
101 {
102  if (s == NULL)
103  return 0;
104 
105  if (s->flags & SIG_FLAG_FILESTORE)
106  return 1;
107 
108  return 0;
109 }
110 
111 /**
112  * \brief Check if a signature contains the filemagic keyword.
113  *
114  * \param s signature
115  *
116  * \retval 0 no
117  * \retval 1 yes
118  */
120 {
121  if (s == NULL)
122  return 0;
123 
125  return 1;
126 
127  return 0;
128 }
129 
130 /**
131  * \brief Check if a signature contains the filemd5 keyword.
132  *
133  * \param s signature
134  *
135  * \retval 0 no
136  * \retval 1 yes
137  */
139 {
140  if ((s != NULL) && (s->file_flags & FILE_SIG_NEED_MD5))
141  return 1;
142 
143  return 0;
144 }
145 
146 /**
147  * \brief Check if a signature contains the filesha1 keyword.
148  *
149  * \param s signature
150  *
151  * \retval 0 no
152  * \retval 1 yes
153  */
155 {
156  if ((s != NULL) && (s->file_flags & FILE_SIG_NEED_SHA1))
157  return 1;
158 
159  return 0;
160 }
161 
162 /**
163  * \brief Check if a signature contains the filesha256 keyword.
164  *
165  * \param s signature
166  *
167  * \retval 0 no
168  * \retval 1 yes
169  */
171 {
172  if ((s != NULL) && (s->file_flags & FILE_SIG_NEED_SHA256))
173  return 1;
174 
175  return 0;
176 }
177 
178 /**
179  * \brief Check if a signature contains the filesize keyword.
180  *
181  * \param s signature
182  *
183  * \retval 0 no
184  * \retval 1 yes
185  */
187 {
188  if (s == NULL)
189  return 0;
190 
192  return 1;
193 
194  return 0;
195 }
196 
197 static bool SignatureInspectsBuffers(const Signature *s)
198 {
199  return (s->init_data->buffer_index > 0);
200 }
201 
202 /** \brief Test is a initialized signature is IP only
203  * \param de_ctx detection engine ctx
204  * \param s the signature
205  * \retval 1 sig is ip only
206  * \retval 2 sig is like ip only
207  * \retval 0 sig is not ip only
208  */
210 {
211  if (s->alproto != ALPROTO_UNKNOWN)
212  return 0;
213 
214  if (s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL)
215  return 0;
216 
217  // may happen for 'config' keyword, postmatch
218  if (s->flags & SIG_FLAG_APPLAYER)
219  return 0;
220 
221  /* if flow dir is set we can't process it in ip-only */
222  if (!(((s->flags & (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) == 0) ||
225  return 0;
226 
227  /* for now assume that all registered buffer types are incompatible */
228  if (SignatureInspectsBuffers(s)) {
229  SCReturnInt(0);
230  }
231 
232  /* TMATCH list can be ignored, it contains TAGs and
233  * tags are compatible to IP-only. */
234 
236  for (; sm != NULL; sm = sm->next) {
238  return 0;
239  /* we have enabled flowbits to be compatible with ip only sigs, as long
240  * as the sig only has a "set" flowbits */
241  if (sm->type == DETECT_FLOWBITS &&
242  (((DetectFlowbitsData *)sm->ctx)->cmd != DETECT_FLOWBITS_CMD_SET)) {
243  return 0;
244  }
245  }
247  for ( ; sm != NULL; sm = sm->next) {
249  return 0;
250  /* we have enabled flowbits to be compatible with ip only sigs, as long
251  * as the sig only has a "set" flowbits */
252  if (sm->type == DETECT_FLOWBITS &&
253  (((DetectFlowbitsData *)sm->ctx)->cmd != DETECT_FLOWBITS_CMD_SET) ) {
254  return 0;
255  }
256  }
257 
259  /* Rule is IP only, but contains negated addresses. */
260  return 2;
261  }
262  if (!(de_ctx->flags & DE_QUIET)) {
263  SCLogDebug("IP-ONLY (%" PRIu32 "): source %s, dest %s", s->id,
264  s->flags & SIG_FLAG_SRC_ANY ? "ANY" : "SET",
265  s->flags & SIG_FLAG_DST_ANY ? "ANY" : "SET");
266  }
267  return 1;
268 }
269 
270 /** \internal
271  * \brief Test is a initialized signature is inspecting protocol detection only
272  * \param de_ctx detection engine ctx
273  * \param s the signature
274  * \retval 1 sig is dp only
275  * \retval 0 sig is not dp only
276  */
277 static int SignatureIsPDOnly(const DetectEngineCtx *de_ctx, const Signature *s)
278 {
279  if (s->alproto != ALPROTO_UNKNOWN)
280  return 0;
281 
282  if (s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL)
283  return 0;
284 
285  /* for now assume that all registered buffer types are incompatible */
286  if (SignatureInspectsBuffers(s)) {
287  SCReturnInt(0);
288  }
289 
290  /* TMATCH list can be ignored, it contains TAGs and
291  * tags are compatible to DP-only. */
292 
293  /* match list matches may be compatible to DP only. We follow the same
294  * logic as IP-only so we can use that flag */
295 
297  if (sm == NULL)
298  return 0;
299 
300  int pd = 0;
301  for ( ; sm != NULL; sm = sm->next) {
302  if (sm->type == DETECT_AL_APP_LAYER_PROTOCOL) {
303  pd = 1;
304  } else {
305  /* flowbits are supported for dp only sigs, as long
306  * as the sig only has a "set" flowbits */
307  if (sm->type == DETECT_FLOWBITS) {
308  if ((((DetectFlowbitsData *)sm->ctx)->cmd != DETECT_FLOWBITS_CMD_SET) ) {
309  SCLogDebug("%u: not PD-only: flowbit settings other than 'set'", s->id);
310  return 0;
311  }
312  } else if (sm->type == DETECT_FLOW) {
314  SCLogDebug("%u: not PD-only: flow settings other than toserver/toclient", s->id);
315  return 0;
316  }
317  } else if ( !(sigmatch_table[sm->type].flags & SIGMATCH_IPONLY_COMPAT)) {
318  SCLogDebug("%u: not PD-only: %s not PD/IP-only compat", s->id, sigmatch_table[sm->type].name);
319  return 0;
320  }
321  }
322  }
323 
324  if (pd) {
325  SCLogDebug("PD-ONLY (%" PRIu32 ")", s->id);
326  }
327  return pd;
328 }
329 
330 /**
331  * \internal
332  * \brief Check if the initialized signature is inspecting the packet payload
333  * \param de_ctx detection engine ctx
334  * \param s the signature
335  * \retval 1 sig is inspecting the payload
336  * \retval 0 sig is not inspecting the payload
337  */
338 static int SignatureIsInspectingPayload(DetectEngineCtx *de_ctx, const Signature *s)
339 {
340 
341  if (s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL) {
342  return 1;
343  }
344  return 0;
345 }
346 
347 /**
348  * \internal
349  * \brief check if a signature is decoder event matching only
350  * \param de_ctx detection engine
351  * \param s the signature to test
352  * \retval 0 not a DEOnly sig
353  * \retval 1 DEOnly sig
354  */
355 static int SignatureIsDEOnly(DetectEngineCtx *de_ctx, const Signature *s)
356 {
357  if (s->alproto != ALPROTO_UNKNOWN) {
358  SCReturnInt(0);
359  }
360 
361  if (s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL)
362  {
363  SCReturnInt(0);
364  }
365 
366  /* for now assume that all registered buffer types are incompatible */
367  if (SignatureInspectsBuffers(s)) {
368  SCReturnInt(0);
369  }
370 
371  /* check for conflicting keywords */
373  for ( ;sm != NULL; sm = sm->next) {
375  SCReturnInt(0);
376  }
377 
378  /* need at least one decode event keyword to be considered decode event. */
380  for ( ;sm != NULL; sm = sm->next) {
381  if (sm->type == DETECT_DECODE_EVENT)
382  goto deonly;
383  if (sm->type == DETECT_ENGINE_EVENT)
384  goto deonly;
385  if (sm->type == DETECT_STREAM_EVENT)
386  goto deonly;
387  }
388 
389  SCReturnInt(0);
390 
391 deonly:
392  if (!(de_ctx->flags & DE_QUIET)) {
393  SCLogDebug("DE-ONLY (%" PRIu32 "): source %s, dest %s", s->id,
394  s->flags & SIG_FLAG_SRC_ANY ? "ANY" : "SET",
395  s->flags & SIG_FLAG_DST_ANY ? "ANY" : "SET");
396  }
397 
398  SCReturnInt(1);
399 }
400 
401 #define MASK_TCP_INITDEINIT_FLAGS (TH_SYN|TH_RST|TH_FIN)
402 #define MASK_TCP_UNUSUAL_FLAGS (TH_URG|TH_ECN|TH_CWR)
403 
404 /* Create mask for this packet + it's flow if it has one
405  */
406 void
408  bool app_decoder_events)
409 {
410  if (!(PKT_IS_PSEUDOPKT(p))) {
411  (*mask) |= SIG_MASK_REQUIRE_REAL_PKT;
412  }
413  if (!(p->flags & PKT_NOPAYLOAD_INSPECTION) && p->payload_len > 0) {
414  SCLogDebug("packet has payload");
415  (*mask) |= SIG_MASK_REQUIRE_PAYLOAD;
416  } else if (p->flags & PKT_DETECT_HAS_STREAMDATA) {
417  SCLogDebug("stream data available");
418  (*mask) |= SIG_MASK_REQUIRE_PAYLOAD;
419  } else {
420  SCLogDebug("packet has no payload");
421  (*mask) |= SIG_MASK_REQUIRE_NO_PAYLOAD;
422  }
423 
424  if (p->events.cnt > 0 || app_decoder_events != 0 ||
425  (p->app_layer_events != NULL && p->app_layer_events->cnt)) {
426  SCLogDebug("packet/flow has events set");
428  }
429 
430  if (!(PKT_IS_PSEUDOPKT(p)) && PacketIsTCP(p)) {
431  const TCPHdr *tcph = PacketGetTCP(p);
432  if ((tcph->th_flags & MASK_TCP_INITDEINIT_FLAGS) != 0) {
434  }
435  if ((tcph->th_flags & MASK_TCP_UNUSUAL_FLAGS) != 0) {
437  }
438  }
439 
440  if (p->flags & PKT_HAS_FLOW) {
441  SCLogDebug("packet has flow");
442  (*mask) |= SIG_MASK_REQUIRE_FLOW;
443  }
444 }
445 
446 static int SignatureCreateMask(Signature *s)
447 {
448  SCEnter();
449 
453  }
454  if (s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL) {
456  SCLogDebug("sig requires payload");
457  }
458 
459  SigMatch *sm;
460  for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) {
461  switch(sm->type) {
462  case DETECT_FLOWBITS:
463  {
464  /* figure out what flowbit action */
466  if (fb->cmd == DETECT_FLOWBITS_CMD_ISSET) {
467  /* not a mask flag, but still set it here */
469 
470  SCLogDebug("SIG_FLAG_REQUIRE_FLOWVAR set as sig has "
471  "flowbit isset option.");
472  }
473 
474  /* flow is required for any flowbit manipulation */
476  SCLogDebug("sig requires flow to be able to manipulate "
477  "flowbit(s)");
478  break;
479  }
480  case DETECT_FLOWINT:
481  /* flow is required for any flowint manipulation */
483  SCLogDebug("sig requires flow to be able to manipulate "
484  "flowint(s)");
485  break;
486  case DETECT_FLAGS:
487  {
488  DetectFlagsData *fl = (DetectFlagsData *)sm->ctx;
489 
490  if (fl->flags & MASK_TCP_INITDEINIT_FLAGS) {
492  SCLogDebug("sig requires SIG_MASK_REQUIRE_FLAGS_INITDEINIT");
493  }
494  if (fl->flags & MASK_TCP_UNUSUAL_FLAGS) {
496  SCLogDebug("sig requires SIG_MASK_REQUIRE_FLAGS_UNUSUAL");
497  }
498  break;
499  }
500  case DETECT_DSIZE:
501  {
502  DetectU16Data *ds = (DetectU16Data *)sm->ctx;
503  /* LT will include 0, so no payload.
504  * if GT is used in the same rule the
505  * flag will be set anyway. */
506  if (ds->mode == DETECT_UINT_RA || ds->mode == DETECT_UINT_GT ||
507  ds->mode == DETECT_UINT_NE || ds->mode == DETECT_UINT_GTE) {
508 
510  SCLogDebug("sig requires payload");
511 
512  } else if (ds->mode == DETECT_UINT_EQ) {
513  if (ds->arg1 > 0) {
515  SCLogDebug("sig requires payload");
516  } else {
518  SCLogDebug("sig requires no payload");
519  }
520  }
521  break;
522  }
523  case DETECT_DECODE_EVENT:
524  // fallthrough
525  case DETECT_STREAM_EVENT:
526  // fallthrough
528  // fallthrough
529  case DETECT_ENGINE_EVENT:
531  break;
532  }
533  }
534 
535  for (sm = s->init_data->smlists[DETECT_SM_LIST_POSTMATCH]; sm != NULL; sm = sm->next) {
536  switch (sm->type) {
537  case DETECT_CONFIG: {
539  if (fd->scope == CONFIG_SCOPE_FLOW) {
541  }
542  break;
543  }
544  }
545  }
546 
549  SCLogDebug("sig requires flow");
550  }
551 
552  if (s->flags & SIG_FLAG_APPLAYER) {
554  SCLogDebug("sig requires flow");
555  }
556 
557  SCLogDebug("mask %02X", s->mask);
558  SCReturnInt(0);
559 }
560 
561 static void SigInitStandardMpmFactoryContexts(DetectEngineCtx *de_ctx)
562 {
564 }
565 
566 /** \brief Pure-PCRE or bytetest rule */
567 static bool RuleInspectsPayloadHasNoMpm(const Signature *s)
568 {
569  if (s->init_data->mpm_sm == NULL && s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL)
570  return true;
571  return false;
572 }
573 
574 static int RuleGetMpmPatternSize(const Signature *s)
575 {
576  if (s->init_data->mpm_sm == NULL)
577  return -1;
578  int mpm_list = s->init_data->mpm_sm_list;
579  if (mpm_list < 0)
580  return -1;
581  const DetectContentData *cd = (const DetectContentData *)s->init_data->mpm_sm->ctx;
582  if (cd == NULL)
583  return -1;
584  return (int)cd->content_len;
585 }
586 
587 static bool RuleMpmIsNegated(const Signature *s)
588 {
589  if (s->flags & SIG_FLAG_MPM_NEG)
590  return true;
591  if (s->init_data->mpm_sm == NULL)
592  return false;
593  int mpm_list = s->init_data->mpm_sm_list;
594  if (mpm_list < 0)
595  return false;
596  const DetectContentData *cd = (const DetectContentData *)s->init_data->mpm_sm->ctx;
597  if (cd == NULL)
598  return false;
599  return (cd->flags & DETECT_CONTENT_NEGATED) ? true : false;
600 }
601 
602 static json_t *RulesGroupPrintSghStats(const DetectEngineCtx *de_ctx, const SigGroupHead *sgh,
603  const int add_rules, const int add_mpm_stats)
604 {
605  uint32_t prefilter_cnt = 0;
606  uint32_t mpm_cnt = 0;
607  uint32_t nonmpm_cnt = 0;
608  uint32_t mpm_depth_cnt = 0;
609  uint32_t mpm_endswith_cnt = 0;
610  uint32_t negmpm_cnt = 0;
611  uint32_t any5_cnt = 0;
612  uint32_t payload_no_mpm_cnt = 0;
613  uint32_t syn_cnt = 0;
614 
615  uint32_t mpms_min = 0;
616  uint32_t mpms_max = 0;
617 
618  int max_buffer_type_id = de_ctx->buffer_type_id;
619 
620  struct {
621  uint32_t total;
622  uint32_t cnt;
623  uint32_t min;
624  uint32_t max;
625  } mpm_stats[max_buffer_type_id];
626  memset(mpm_stats, 0x00, sizeof(mpm_stats));
627 
628  uint32_t alstats[ALPROTO_MAX] = {0};
629  uint32_t mpm_sizes[max_buffer_type_id][256];
630  memset(mpm_sizes, 0, sizeof(mpm_sizes));
631  uint32_t alproto_mpm_bufs[ALPROTO_MAX][max_buffer_type_id];
632  memset(alproto_mpm_bufs, 0, sizeof(alproto_mpm_bufs));
633 
634  DEBUG_VALIDATE_BUG_ON(sgh->init == NULL);
635  if (sgh->init == NULL)
636  return NULL;
637 
638  json_t *js = json_object();
639  if (unlikely(js == NULL))
640  return NULL;
641 
642  json_object_set_new(js, "id", json_integer(sgh->id));
643 
644  json_t *js_array = json_array();
645 
646  for (uint32_t x = 0; x < sgh->init->sig_cnt; x++) {
647  const Signature *s = sgh->init->match_array[x];
648  if (s == NULL)
649  continue;
650 
651  int any = 0;
652  if (s->proto.flags & DETECT_PROTO_ANY) {
653  any++;
654  }
655  if (s->flags & SIG_FLAG_DST_ANY) {
656  any++;
657  }
658  if (s->flags & SIG_FLAG_SRC_ANY) {
659  any++;
660  }
661  if (s->flags & SIG_FLAG_DP_ANY) {
662  any++;
663  }
664  if (s->flags & SIG_FLAG_SP_ANY) {
665  any++;
666  }
667  if (any == 5) {
668  any5_cnt++;
669  }
670 
671  prefilter_cnt += (s->init_data->prefilter_sm != 0);
672  if (s->init_data->mpm_sm == NULL) {
673  nonmpm_cnt++;
674 
675  if (s->sm_arrays[DETECT_SM_LIST_MATCH] != NULL) {
676  SCLogDebug("SGH %p Non-MPM inspecting only packets. Rule %u", sgh, s->id);
677  }
678 
679  DetectPort *sp = s->sp;
680  DetectPort *dp = s->dp;
681 
682  if (s->flags & SIG_FLAG_TOSERVER && (dp->port == 0 && dp->port2 == 65535)) {
683  SCLogDebug("SGH %p Non-MPM toserver and to 'any'. Rule %u", sgh, s->id);
684  }
685  if (s->flags & SIG_FLAG_TOCLIENT && (sp->port == 0 && sp->port2 == 65535)) {
686  SCLogDebug("SGH %p Non-MPM toclient and to 'any'. Rule %u", sgh, s->id);
687  }
688 
690  syn_cnt++;
691  }
692 
693  } else {
694  int mpm_list = s->init_data->mpm_sm_list;
695  BUG_ON(mpm_list < 0);
696  const DetectContentData *cd = (const DetectContentData *)s->init_data->mpm_sm->ctx;
697  uint32_t size = cd->content_len < 256 ? cd->content_len : 255;
698 
699  mpm_sizes[mpm_list][size]++;
700  alproto_mpm_bufs[s->alproto][mpm_list]++;
701 
702  if (mpm_list == DETECT_SM_LIST_PMATCH) {
703  if (size == 1) {
704  DetectPort *sp = s->sp;
705  DetectPort *dp = s->dp;
706  if (s->flags & SIG_FLAG_TOSERVER) {
707  if (dp->port == 0 && dp->port2 == 65535) {
708  SCLogDebug("SGH %p toserver 1byte fast_pattern to ANY. Rule %u", sgh, s->id);
709  } else {
710  SCLogDebug("SGH %p toserver 1byte fast_pattern to port(s) %u-%u. Rule %u", sgh, dp->port, dp->port2, s->id);
711  }
712  }
713  if (s->flags & SIG_FLAG_TOCLIENT) {
714  if (sp->port == 0 && sp->port2 == 65535) {
715  SCLogDebug("SGH %p toclient 1byte fast_pattern to ANY. Rule %u", sgh, s->id);
716  } else {
717  SCLogDebug("SGH %p toclient 1byte fast_pattern to port(s) %u-%u. Rule %u", sgh, sp->port, sp->port2, s->id);
718  }
719  }
720  }
721  }
722 
723  uint32_t w = PatternStrength(cd->content, cd->content_len);
724  if (mpms_min == 0)
725  mpms_min = w;
726  if (w < mpms_min)
727  mpms_min = w;
728  if (w > mpms_max)
729  mpms_max = w;
730 
731  BUG_ON(mpm_list >= max_buffer_type_id);
732  mpm_stats[mpm_list].total += w;
733  mpm_stats[mpm_list].cnt++;
734  if (mpm_stats[mpm_list].min == 0 || w < mpm_stats[mpm_list].min)
735  mpm_stats[mpm_list].min = w;
736  if (w > mpm_stats[mpm_list].max)
737  mpm_stats[mpm_list].max = w;
738 
739  mpm_cnt++;
740 
741  if (w < 10) {
742  SCLogDebug("SGH %p Weak MPM Pattern on %s. Rule %u", sgh, DetectListToString(mpm_list), s->id);
743  }
744  if (w < 10 && any == 5) {
745  SCLogDebug("SGH %p Weak MPM Pattern on %s, rule is 5xAny. Rule %u", sgh, DetectListToString(mpm_list), s->id);
746  }
747 
748  if (cd->flags & DETECT_CONTENT_NEGATED) {
749  SCLogDebug("SGH %p MPM Pattern on %s, is negated. Rule %u", sgh, DetectListToString(mpm_list), s->id);
750  negmpm_cnt++;
751  }
752  if (cd->flags & DETECT_CONTENT_ENDS_WITH) {
753  mpm_endswith_cnt++;
754  }
755  if (cd->flags & DETECT_CONTENT_DEPTH) {
756  mpm_depth_cnt++;
757  }
758  }
759 
760  if (RuleInspectsPayloadHasNoMpm(s)) {
761  SCLogDebug("SGH %p No MPM. Payload inspecting. Rule %u", sgh, s->id);
762  payload_no_mpm_cnt++;
763  }
764 
765  alstats[s->alproto]++;
766 
767  if (add_rules) {
768  json_t *js_sig = json_object();
769  if (unlikely(js == NULL))
770  continue;
771  json_object_set_new(js_sig, "sig_id", json_integer(s->id));
772  json_array_append_new(js_array, js_sig);
773  }
774  }
775 
776  json_object_set_new(js, "rules", js_array);
777 
778  json_t *stats = json_object();
779  json_object_set_new(stats, "total", json_integer(sgh->init->sig_cnt));
780 
781  json_t *types = json_object();
782  json_object_set_new(types, "mpm", json_integer(mpm_cnt));
783  json_object_set_new(types, "non_mpm", json_integer(nonmpm_cnt));
784  json_object_set_new(types, "mpm_depth", json_integer(mpm_depth_cnt));
785  json_object_set_new(types, "mpm_endswith", json_integer(mpm_endswith_cnt));
786  json_object_set_new(types, "negated_mpm", json_integer(negmpm_cnt));
787  json_object_set_new(types, "payload_but_no_mpm", json_integer(payload_no_mpm_cnt));
788  json_object_set_new(types, "prefilter", json_integer(prefilter_cnt));
789  json_object_set_new(types, "syn", json_integer(syn_cnt));
790  json_object_set_new(types, "any5", json_integer(any5_cnt));
791  json_object_set_new(stats, "types", types);
792 
793  for (AppProto i = 0; i < ALPROTO_MAX; i++) {
794  if (alstats[i] > 0) {
795  json_t *app = json_object();
796  json_object_set_new(app, "total", json_integer(alstats[i]));
797 
798  for (int y = 0; y < max_buffer_type_id; y++) {
799  if (alproto_mpm_bufs[i][y] == 0)
800  continue;
801 
802  const char *name;
804  name = DetectListToHumanString(y);
805  else
807 
808  json_object_set_new(app, name, json_integer(alproto_mpm_bufs[i][y]));
809  }
810 
811  const char *proto_name = (i == ALPROTO_UNKNOWN) ? "payload" : AppProtoToString(i);
812  json_object_set_new(stats, proto_name, app);
813  }
814  }
815 
816  if (add_mpm_stats) {
817  json_t *mpm_js = json_object();
818 
819  for (int i = 0; i < max_buffer_type_id; i++) {
820  if (mpm_stats[i].cnt > 0) {
821 
822  json_t *mpm_sizes_array = json_array();
823  for (int y = 0; y < 256; y++) {
824  if (mpm_sizes[i][y] == 0)
825  continue;
826 
827  json_t *e = json_object();
828  json_object_set_new(e, "size", json_integer(y));
829  json_object_set_new(e, "count", json_integer(mpm_sizes[i][y]));
830  json_array_append_new(mpm_sizes_array, e);
831  }
832 
833  json_t *buf = json_object();
834  json_object_set_new(buf, "total", json_integer(mpm_stats[i].cnt));
835  json_object_set_new(buf, "avg_strength", json_integer(mpm_stats[i].total / mpm_stats[i].cnt));
836  json_object_set_new(buf, "min_strength", json_integer(mpm_stats[i].min));
837  json_object_set_new(buf, "max_strength", json_integer(mpm_stats[i].max));
838 
839  json_object_set_new(buf, "sizes", mpm_sizes_array);
840 
841  const char *name;
843  name = DetectListToHumanString(i);
844  else
846 
847  json_object_set_new(mpm_js, name, buf);
848  }
849  }
850 
851  json_object_set_new(stats, "mpm", mpm_js);
852  }
853  json_object_set_new(js, "stats", stats);
854 
855  json_object_set_new(js, "score", json_integer(sgh->init->score));
856 
857  return js;
858 }
859 
860 static void RulesDumpGrouping(const DetectEngineCtx *de_ctx,
861  const int add_rules, const int add_mpm_stats)
862 {
863  json_t *js = json_object();
864  if (unlikely(js == NULL))
865  return;
866 
867  int p;
868  for (p = 0; p < 256; p++) {
869  if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
870  const char *name = (p == IPPROTO_TCP) ? "tcp" : "udp";
871 
872  json_t *tcp = json_object();
873 
874  json_t *ts_array = json_array();
875  DetectPort *list = (p == IPPROTO_TCP) ? de_ctx->flow_gh[1].tcp :
876  de_ctx->flow_gh[1].udp;
877  while (list != NULL) {
878  json_t *port = json_object();
879  json_object_set_new(port, "port", json_integer(list->port));
880  json_object_set_new(port, "port2", json_integer(list->port2));
881 
882  json_t *tcp_ts =
883  RulesGroupPrintSghStats(de_ctx, list->sh, add_rules, add_mpm_stats);
884  json_object_set_new(port, "rulegroup", tcp_ts);
885  json_array_append_new(ts_array, port);
886 
887  list = list->next;
888  }
889  json_object_set_new(tcp, "toserver", ts_array);
890 
891  json_t *tc_array = json_array();
892  list = (p == IPPROTO_TCP) ? de_ctx->flow_gh[0].tcp :
893  de_ctx->flow_gh[0].udp;
894  while (list != NULL) {
895  json_t *port = json_object();
896  json_object_set_new(port, "port", json_integer(list->port));
897  json_object_set_new(port, "port2", json_integer(list->port2));
898 
899  json_t *tcp_tc =
900  RulesGroupPrintSghStats(de_ctx, list->sh, add_rules, add_mpm_stats);
901  json_object_set_new(port, "rulegroup", tcp_tc);
902  json_array_append_new(tc_array, port);
903 
904  list = list->next;
905  }
906  json_object_set_new(tcp, "toclient", tc_array);
907 
908  json_object_set_new(js, name, tcp);
909  } else if (p == IPPROTO_ICMP || p == IPPROTO_ICMPV6) {
910  const char *name = (p == IPPROTO_ICMP) ? "icmpv4" : "icmpv6";
911  json_t *o = json_object();
912  if (de_ctx->flow_gh[1].sgh[p]) {
913  json_t *ts = json_object();
914  json_t *group_ts = RulesGroupPrintSghStats(
915  de_ctx, de_ctx->flow_gh[1].sgh[p], add_rules, add_mpm_stats);
916  json_object_set_new(ts, "rulegroup", group_ts);
917  json_object_set_new(o, "toserver", ts);
918  }
919  if (de_ctx->flow_gh[0].sgh[p]) {
920  json_t *tc = json_object();
921  json_t *group_tc = RulesGroupPrintSghStats(
922  de_ctx, de_ctx->flow_gh[0].sgh[p], add_rules, add_mpm_stats);
923  json_object_set_new(tc, "rulegroup", group_tc);
924  json_object_set_new(o, "toclient", tc);
925  }
926  json_object_set_new(js, name, o);
927  }
928  }
929 
930  const char *filename = "rule_group.json";
931  const char *log_dir = ConfigGetLogDirectory();
932  char log_path[PATH_MAX] = "";
933 
934  snprintf(log_path, sizeof(log_path), "%s/%s", log_dir, filename);
935 
936  FILE *fp = fopen(log_path, "w");
937  if (fp == NULL) {
938  return;
939  }
940 
941  char *js_s = json_dumps(js,
942  JSON_PRESERVE_ORDER|JSON_ESCAPE_SLASH);
943  if (unlikely(js_s == NULL)) {
944  fclose(fp);
945  return;
946  }
947 
948  json_object_clear(js);
949  json_decref(js);
950 
951  fprintf(fp, "%s\n", js_s);
952  free(js_s);
953  fclose(fp);
954 }
955 
956 static int RulesGroupByIPProto(DetectEngineCtx *de_ctx)
957 {
958  Signature *s = de_ctx->sig_list;
959 
960  SigGroupHead *sgh_ts[256] = {NULL};
961  SigGroupHead *sgh_tc[256] = {NULL};
962 
963  for ( ; s != NULL; s = s->next) {
964  if (s->type == SIG_TYPE_IPONLY)
965  continue;
966 
967  /* traverse over IP protocol list from libc */
968  for (int p = 0; p < 256; p++) {
969  if (p == IPPROTO_TCP || p == IPPROTO_UDP) {
970  continue;
971  }
972  if (!(s->proto.proto[p / 8] & (1<<(p % 8)) || (s->proto.flags & DETECT_PROTO_ANY))) {
973  continue;
974  }
975 
976  /* Signatures that are ICMP, SCTP, not IP only are handled here */
977  if (s->flags & SIG_FLAG_TOCLIENT) {
978  SigGroupHeadAppendSig(de_ctx, &sgh_tc[p], s);
979  }
980  if (s->flags & SIG_FLAG_TOSERVER) {
981  SigGroupHeadAppendSig(de_ctx, &sgh_ts[p], s);
982  }
983  }
984  }
985 
986  /* lets look at deduplicating this list */
989 
990  uint32_t cnt = 0;
991  uint32_t own = 0;
992  uint32_t ref = 0;
993  int p;
994  for (p = 0; p < 256; p++) {
995  if (p == IPPROTO_TCP || p == IPPROTO_UDP)
996  continue;
997  if (sgh_ts[p] == NULL)
998  continue;
999 
1000  cnt++;
1001 
1002  SigGroupHead *lookup_sgh = SigGroupHeadHashLookup(de_ctx, sgh_ts[p]);
1003  if (lookup_sgh == NULL) {
1004  SCLogDebug("proto group %d sgh %p is the original", p, sgh_ts[p]);
1005 
1006  SigGroupHeadSetSigCnt(sgh_ts[p], 0);
1007  SigGroupHeadBuildMatchArray(de_ctx, sgh_ts[p], 0);
1008 
1009  SigGroupHeadHashAdd(de_ctx, sgh_ts[p]);
1010  SigGroupHeadStore(de_ctx, sgh_ts[p]);
1011  own++;
1012  } else {
1013  SCLogDebug("proto group %d sgh %p is a copy", p, sgh_ts[p]);
1014 
1015  SigGroupHeadFree(de_ctx, sgh_ts[p]);
1016  sgh_ts[p] = lookup_sgh;
1017  ref++;
1018  }
1019  }
1020  SCLogPerf("OTHER %s: %u proto groups, %u unique SGH's, %u copies",
1021  "toserver", cnt, own, ref);
1022 
1023  cnt = 0;
1024  own = 0;
1025  ref = 0;
1026  for (p = 0; p < 256; p++) {
1027  if (p == IPPROTO_TCP || p == IPPROTO_UDP)
1028  continue;
1029  if (sgh_tc[p] == NULL)
1030  continue;
1031 
1032  cnt++;
1033 
1034  SigGroupHead *lookup_sgh = SigGroupHeadHashLookup(de_ctx, sgh_tc[p]);
1035  if (lookup_sgh == NULL) {
1036  SCLogDebug("proto group %d sgh %p is the original", p, sgh_tc[p]);
1037 
1038  SigGroupHeadSetSigCnt(sgh_tc[p], 0);
1039  SigGroupHeadBuildMatchArray(de_ctx, sgh_tc[p], 0);
1040 
1041  SigGroupHeadHashAdd(de_ctx, sgh_tc[p]);
1042  SigGroupHeadStore(de_ctx, sgh_tc[p]);
1043  own++;
1044 
1045  } else {
1046  SCLogDebug("proto group %d sgh %p is a copy", p, sgh_tc[p]);
1047 
1048  SigGroupHeadFree(de_ctx, sgh_tc[p]);
1049  sgh_tc[p] = lookup_sgh;
1050  ref++;
1051  }
1052  }
1053  SCLogPerf("OTHER %s: %u proto groups, %u unique SGH's, %u copies",
1054  "toclient", cnt, own, ref);
1055 
1056  for (p = 0; p < 256; p++) {
1057  if (p == IPPROTO_TCP || p == IPPROTO_UDP)
1058  continue;
1059 
1060  de_ctx->flow_gh[0].sgh[p] = sgh_tc[p];
1061  de_ctx->flow_gh[1].sgh[p] = sgh_ts[p];
1062  }
1063 
1064  return 0;
1065 }
1066 
1067 static int PortIsPriority(const DetectEngineCtx *de_ctx, const DetectPort *a, int ipproto)
1068 {
1070  if (ipproto == IPPROTO_UDP)
1072 
1073  while (w) {
1074  /* Make sure the priority port falls in the port range of a */
1075  DEBUG_VALIDATE_BUG_ON(a->port > a->port2);
1076  if (a->port == w->port && w->port2 == a->port2) {
1077  return 1;
1078  }
1079  w = w->next;
1080  }
1081 
1082  return 0;
1083 }
1084 
1085 static int RuleSetScore(Signature *s)
1086 {
1087  DetectPort *p = NULL;
1088  if (s->flags & SIG_FLAG_TOSERVER)
1089  p = s->dp;
1090  else if (s->flags & SIG_FLAG_TOCLIENT)
1091  p = s->sp;
1092  else
1093  return 0;
1094 
1095  /* for sigs that don't use 'any' as port, see if we want to
1096  * prioritize poor sigs */
1097  int wl = 0;
1098  if (!(p->port == 0 && p->port2 == 65535)) {
1099  /* pure pcre, bytetest, etc rules */
1100  if (RuleInspectsPayloadHasNoMpm(s)) {
1101  SCLogDebug("Rule %u MPM has 1 byte fast_pattern. Prioritizing SGH's.", s->id);
1103 
1104  } else if (RuleMpmIsNegated(s)) {
1105  SCLogDebug("Rule %u MPM is negated. Prioritizing SGH's.", s->id);
1107 
1108  /* one byte pattern in packet/stream payloads */
1109  } else if (s->init_data->mpm_sm != NULL &&
1111  RuleGetMpmPatternSize(s) == 1) {
1112  SCLogDebug("Rule %u No MPM. Payload inspecting. Prioritizing SGH's.", s->id);
1114 
1116  SCLogDebug("Rule %u Needs SYN, so inspected often. Prioritizing SGH's.", s->id);
1118  }
1119  }
1120 
1121  s->init_data->score = wl;
1122  return wl;
1123 }
1124 
1125 static int SortCompare(const void *a, const void *b)
1126 {
1127  const DetectPort *pa = *(const DetectPort **)a;
1128  const DetectPort *pb = *(const DetectPort **)b;
1129 
1130  if (pa->sh->init->score < pb->sh->init->score) {
1131  return 1;
1132  } else if (pa->sh->init->score > pb->sh->init->score) {
1133  return -1;
1134  }
1135 
1136  if (pa->sh->init->sig_cnt < pb->sh->init->sig_cnt) {
1137  return 1;
1138  } else if (pa->sh->init->sig_cnt > pb->sh->init->sig_cnt) {
1139  return -1;
1140  }
1141 
1142  /* Hack to make the qsort output deterministic across platforms.
1143  * This had to be done because the order of equal elements sorted
1144  * by qsort is undeterministic and showed different output on BSD,
1145  * MacOS and Windows. Sorting based on id makes it deterministic. */
1146  if (pa->sh->id < pb->sh->id)
1147  return -1;
1148 
1149  return 1;
1150 }
1151 
1152 static inline void SortGroupList(
1153  uint32_t *groups, DetectPort **list, int (*CompareFunc)(const void *, const void *))
1154 {
1155  int cnt = 0;
1156  for (DetectPort *x = *list; x != NULL; x = x->next) {
1157  DEBUG_VALIDATE_BUG_ON(x->port > x->port2);
1158  cnt++;
1159  }
1160  if (cnt <= 1)
1161  return;
1162 
1163  /* build temporary array to sort with qsort */
1164  DetectPort **array = (DetectPort **)SCCalloc(cnt, sizeof(DetectPort *));
1165  if (array == NULL)
1166  return;
1167 
1168  int idx = 0;
1169  for (DetectPort *x = *list; x != NULL;) {
1170  /* assign a temporary id to resolve otherwise equal groups */
1171  x->sh->id = idx + 1;
1172  SigGroupHeadSetSigCnt(x->sh, 0);
1173  DetectPort *next = x->next;
1174  x->next = x->prev = x->last = NULL;
1175  DEBUG_VALIDATE_BUG_ON(x->port > x->port2);
1176  array[idx++] = x;
1177  x = next;
1178  }
1179  DEBUG_VALIDATE_BUG_ON(cnt != idx);
1180 
1181  qsort(array, idx, sizeof(DetectPort *), SortCompare);
1182 
1183  /* rebuild the list based on the qsort-ed array */
1184  DetectPort *new_list = NULL, *tail = NULL;
1185  for (int i = 0; i < idx; i++) {
1186  DetectPort *p = array[i];
1187  /* unset temporary group id */
1188  p->sh->id = 0;
1189 
1190  if (new_list == NULL) {
1191  new_list = p;
1192  }
1193  if (tail != NULL) {
1194  tail->next = p;
1195  }
1196  p->prev = tail;
1197  tail = p;
1198  }
1199 
1200  *list = new_list;
1201  *groups = idx;
1202 
1203 #if DEBUG
1204  int dbgcnt = 0;
1205  SCLogDebug("SORTED LIST:");
1206  for (DetectPort *tmp = *list; tmp != NULL; tmp = tmp->next) {
1207  SCLogDebug("item:= [%u:%u]; score: %d; sig_cnt: %d", tmp->port, tmp->port2,
1208  tmp->sh->init->score, tmp->sh->init->sig_cnt);
1209  dbgcnt++;
1210  BUG_ON(dbgcnt > cnt);
1211  }
1212 #endif
1213  SCFree(array);
1214 }
1215 /** \internal
1216  * \brief Create a list of DetectPort objects sorted based on CompareFunc's
1217  * logic.
1218  *
1219  * List can limit the number of groups. In this case an extra "join" group
1220  * is created that contains the sigs belonging to that. It's *appended* to
1221  * the list, meaning that if the list is walked linearly it's found last.
1222  * The joingr is meant to be a catch all.
1223  *
1224  */
1225 static int CreateGroupedPortList(DetectEngineCtx *de_ctx, DetectPort *port_list,
1226  DetectPort **newhead, uint32_t unique_groups,
1227  int (*CompareFunc)(const void *, const void *))
1228 {
1229  DetectPort *tmplist = NULL, *joingr = NULL;
1230  uint32_t groups = 0;
1231 
1232  /* insert the ports into the tmplist, where it will
1233  * be sorted descending on 'cnt' and on whether a group
1234  * is prioritized. */
1235  tmplist = port_list;
1236  SortGroupList(&groups, &tmplist, SortCompare);
1237  uint32_t left = unique_groups;
1238  if (left == 0)
1239  left = groups;
1240 
1241  /* create another list: take the port groups from above
1242  * and add them to the 2nd list until we have met our
1243  * count. The rest is added to the 'join' group. */
1244  DetectPort *tmplist2 = NULL, *tmplist2_tail = NULL;
1245  DetectPort *gr, *next_gr;
1246  for (gr = tmplist; gr != NULL;) {
1247  next_gr = gr->next;
1248 
1249  SCLogDebug("temp list gr %p %u:%u", gr, gr->port, gr->port2);
1250  DetectPortPrint(gr);
1251 
1252  /* if we've set up all the unique groups, add the rest to the
1253  * catch-all joingr */
1254  if (left == 0) {
1255  if (joingr == NULL) {
1256  DetectPortParse(de_ctx, &joingr, "0:65535");
1257  if (joingr == NULL) {
1258  goto error;
1259  }
1260  SCLogDebug("joingr => %u-%u", joingr->port, joingr->port2);
1261  joingr->next = NULL;
1262  }
1263  SigGroupHeadCopySigs(de_ctx, gr->sh, &joingr->sh);
1264 
1265  /* when a group's sigs are added to the joingr, we can free it */
1266  gr->next = NULL;
1267  DetectPortFree(de_ctx, gr);
1268  /* append */
1269  } else {
1270  gr->next = NULL;
1271 
1272  if (tmplist2 == NULL) {
1273  tmplist2 = gr;
1274  tmplist2_tail = gr;
1275  } else {
1276  tmplist2_tail->next = gr;
1277  tmplist2_tail = gr;
1278  }
1279  }
1280 
1281  if (left > 0)
1282  left--;
1283 
1284  gr = next_gr;
1285  }
1286 
1287  /* if present, append the joingr that covers the rest */
1288  if (joingr != NULL) {
1289  SCLogDebug("appending joingr %p %u:%u", joingr, joingr->port, joingr->port2);
1290 
1291  if (tmplist2 == NULL) {
1292  tmplist2 = joingr;
1293  // tmplist2_tail = joingr;
1294  } else {
1295  tmplist2_tail->next = joingr;
1296  // tmplist2_tail = joingr;
1297  }
1298  } else {
1299  SCLogDebug("no joingr");
1300  }
1301 
1302  /* pass back our new list to the caller */
1303  *newhead = tmplist2;
1304  DetectPortPrintList(*newhead);
1305 
1306  return 0;
1307 error:
1308  return -1;
1309 }
1310 
1311 #define UNDEFINED_PORT 0
1312 #define RANGE_PORT 1
1313 #define SINGLE_PORT 2
1315 typedef struct UniquePortPoint_ {
1316  uint16_t port; /* value of the port */
1317  bool single; /* is the port single or part of a range */
1319 
1320 /**
1321  * \brief Function to set unique port points. Consider all the ports
1322  * flattened out on one line, set the points that correspond
1323  * to a valid port. Also store whether the port point stored
1324  * was a single port or part of a range.
1325  *
1326  * \param p Port object to be set
1327  * \param unique_list List of unique port points to be updated
1328  * \param size_list Current size of the list
1329  *
1330  * \return Updated size of the list
1331  */
1332 static inline uint32_t SetUniquePortPoints(
1333  const DetectPort *p, uint8_t *unique_list, uint32_t size_list)
1334 {
1335  if (unique_list[p->port] == UNDEFINED_PORT) {
1336  if (p->port == p->port2) {
1337  unique_list[p->port] = SINGLE_PORT;
1338  } else {
1339  unique_list[p->port] = RANGE_PORT;
1340  }
1341  size_list++;
1342  } else if (((unique_list[p->port] == SINGLE_PORT) && (p->port != p->port2)) ||
1343  ((unique_list[p->port] == RANGE_PORT) && (p->port == p->port2))) {
1344  if ((p->port != UINT16_MAX) && (unique_list[p->port + 1] == UNDEFINED_PORT)) {
1345  unique_list[p->port + 1] = RANGE_PORT;
1346  size_list++;
1347  }
1348  }
1349 
1350  /* Treat right boundary as single point to avoid creating unneeded
1351  * ranges later on */
1352  if (unique_list[p->port2] == UNDEFINED_PORT) {
1353  size_list++;
1354  }
1355  unique_list[p->port2] = SINGLE_PORT;
1356  return size_list;
1357 }
1358 
1359 /**
1360  * \brief Function to set the *final* unique port points and save them
1361  * for later use. The points are already sorted because of the way
1362  * they have been retrieved and saved earlier for use at this point.
1363  *
1364  * \param unique_list List of the unique port points to be used
1365  * \param size_unique_arr Number of unique port points
1366  * \param final_arr List of the final unique port points to be created
1367  */
1368 static inline void SetFinalUniquePortPoints(
1369  const uint8_t *unique_list, const uint32_t size_unique_arr, UniquePortPoint *final_arr)
1370 {
1371  for (uint32_t i = 0, j = 0; i < (UINT16_MAX + 1); i++) {
1372  DEBUG_VALIDATE_BUG_ON(j > size_unique_arr);
1373  if (unique_list[i] == RANGE_PORT) {
1374  final_arr[j].port = (uint16_t)i;
1375  final_arr[j++].single = false;
1376  } else if (unique_list[i] == SINGLE_PORT) {
1377  final_arr[j].port = (uint16_t)i;
1378  final_arr[j++].single = true;
1379  }
1380  }
1381 }
1382 
1383 /**
1384  * \brief Function to create the list of ports with the smallest ranges
1385  * by resolving overlaps and end point conditions. These contain the
1386  * correct SGHs as well after going over the interval tree to find
1387  * any range overlaps.
1388  *
1389  * \param de_ctx Detection Engine Context
1390  * \param unique_list Final list of unique port points
1391  * \param size_list Size of the unique_list
1392  * \param it Pointer to the interval tree
1393  * \param list Pointer to the list where final ports will be stored
1394  *
1395  * \return 0 on success, -1 otherwise
1396  */
1397 static inline int CreatePortList(DetectEngineCtx *de_ctx, const uint8_t *unique_list,
1398  const uint32_t size_list, SCPortIntervalTree *it, DetectPort **list)
1399 {
1400  /* Only do the operations if there is at least one unique port */
1401  if (size_list == 0)
1402  return 0;
1403  UniquePortPoint *final_unique_points =
1404  (UniquePortPoint *)SCCalloc(size_list, sizeof(UniquePortPoint));
1405  if (final_unique_points == NULL)
1406  return -1;
1407  SetFinalUniquePortPoints(unique_list, size_list, final_unique_points);
1408  /* Handle edge case when there is just one unique port */
1409  if (size_list == 1) {
1411  de_ctx, final_unique_points[0].port, final_unique_points[0].port, &it->tree, list);
1412  } else {
1413  UniquePortPoint *p1 = &final_unique_points[0];
1414  UniquePortPoint *p2 = &final_unique_points[1];
1415  uint16_t port = p1 ? p1->port : 0; // just for cppcheck
1416  uint16_t port2 = p2->port;
1417  for (uint32_t i = 1; i < size_list; i++) {
1418  DEBUG_VALIDATE_BUG_ON(port > port2);
1419  if ((p1 && p1->single) && p2->single) {
1420  SCPortIntervalFindOverlappingRanges(de_ctx, port, port, &it->tree, list);
1421  SCPortIntervalFindOverlappingRanges(de_ctx, port2, port2, &it->tree, list);
1422  port = port2 + 1;
1423  } else if (p1 && p1->single) {
1424  SCPortIntervalFindOverlappingRanges(de_ctx, port, port, &it->tree, list);
1425  if ((port2 > port + 1)) {
1427  de_ctx, port + 1, port2 - 1, &it->tree, list);
1428  port = port2;
1429  } else {
1430  port = port + 1;
1431  }
1432  } else if (p2->single) {
1433  /* If port2 is boundary and less or equal to port + 1, create a range
1434  * keeping the boundary away as it is single port */
1435  if ((port2 >= port + 1)) {
1436  SCPortIntervalFindOverlappingRanges(de_ctx, port, port2 - 1, &it->tree, list);
1437  }
1438  /* Deal with port2 as it is a single port */
1439  SCPortIntervalFindOverlappingRanges(de_ctx, port2, port2, &it->tree, list);
1440  port = port2 + 1;
1441  } else {
1442  if ((port2 > port + 1)) {
1443  SCPortIntervalFindOverlappingRanges(de_ctx, port, port2 - 1, &it->tree, list);
1444  port = port2;
1445  } else {
1446  SCPortIntervalFindOverlappingRanges(de_ctx, port, port2, &it->tree, list);
1447  port = port2 + 1;
1448  }
1449  }
1450  /* if the current port matches the p2->port, assign it to p1 so that
1451  * there is a UniquePortPoint object to check other info like whether
1452  * the port with this value is single */
1453  if (port == p2->port) {
1454  p1 = p2;
1455  } else {
1456  p1 = NULL;
1457  }
1458  if (i + 1 < size_list) {
1459  p2 = &final_unique_points[i + 1];
1460  port2 = p2->port;
1461  }
1462  }
1463  }
1464  /* final_unique_points array is no longer needed */
1465  SCFree(final_unique_points);
1466  return 0;
1467 }
1468 
1469 static DetectPort *RulesGroupByPorts(DetectEngineCtx *de_ctx, uint8_t ipproto, uint32_t direction)
1470 {
1471  /* step 1: create a hash of 'DetectPort' objects based on all the
1472  * rules. Each object will have a SGH with the sigs added
1473  * that belong to the SGH. */
1475 
1476  uint32_t size_unique_port_arr = 0;
1477  const Signature *s = de_ctx->sig_list;
1478  DetectPort *list = NULL;
1479 
1480  uint8_t *unique_port_points = (uint8_t *)SCCalloc(UINT16_MAX + 1, sizeof(uint8_t));
1481  if (unique_port_points == NULL)
1482  return NULL;
1483 
1484  while (s) {
1485  /* IP Only rules are handled separately */
1486  if (s->type == SIG_TYPE_IPONLY)
1487  goto next;
1488  /* Protocol does not match the Signature protocol and is neither IP or pkthdr */
1489  if (!(s->proto.proto[ipproto / 8] & (1<<(ipproto % 8)) || (s->proto.flags & DETECT_PROTO_ANY)))
1490  goto next;
1491  /* Direction does not match Signature direction */
1492  if (direction == SIG_FLAG_TOSERVER) {
1493  if (!(s->flags & SIG_FLAG_TOSERVER))
1494  goto next;
1495  } else if (direction == SIG_FLAG_TOCLIENT) {
1496  if (!(s->flags & SIG_FLAG_TOCLIENT))
1497  goto next;
1498  }
1499 
1500  /* see if we want to exclude directionless sigs that really care only for
1501  * to_server syn scans/floods */
1505  (!(s->dp->port == 0 && s->dp->port2 == 65535))) {
1506  SCLogWarning("rule %u: SYN-only to port(s) %u:%u "
1507  "w/o direction specified, disabling for toclient direction",
1508  s->id, s->dp->port, s->dp->port2);
1509  goto next;
1510  }
1511 
1512  DetectPort *p = NULL;
1513  if (direction == SIG_FLAG_TOSERVER)
1514  p = s->dp;
1515  else if (direction == SIG_FLAG_TOCLIENT)
1516  p = s->sp;
1517  else
1518  BUG_ON(1);
1519 
1520  int wl = s->init_data->score;
1521  while (p) {
1522  int pwl = PortIsPriority(de_ctx, p, ipproto) ? DETECT_PGSCORE_RULE_PORT_PRIORITIZED : 0;
1523  pwl = MAX(wl,pwl);
1524 
1525  DetectPort *lookup = DetectPortHashLookup(de_ctx, p);
1526  if (lookup) {
1527  SigGroupHeadAppendSig(de_ctx, &lookup->sh, s);
1528  lookup->sh->init->score = MAX(lookup->sh->init->score, pwl);
1529  } else {
1531  BUG_ON(tmp2 == NULL);
1532  SigGroupHeadAppendSig(de_ctx, &tmp2->sh, s);
1533  tmp2->sh->init->score = pwl;
1534  DetectPortHashAdd(de_ctx, tmp2);
1535  size_unique_port_arr =
1536  SetUniquePortPoints(tmp2, unique_port_points, size_unique_port_arr);
1537  }
1538 
1539  p = p->next;
1540  }
1541  next:
1542  s = s->next;
1543  }
1544 
1545  /* step 2: create a list of the smallest port ranges with
1546  * appropriate SGHs */
1547 
1548  /* Create an interval tree of all the given ports to make the search
1549  * for overlaps later on easier */
1551  if (it == NULL)
1552  goto error;
1553 
1554  HashListTableBucket *htb = NULL;
1555  for (htb = HashListTableGetListHead(de_ctx->dport_hash_table); htb != NULL;
1556  htb = HashListTableGetListNext(htb)) {
1558  if (SCPortIntervalInsert(de_ctx, it, p) != SC_OK) {
1559  SCLogDebug("Port was not inserted in the tree");
1560  goto error;
1561  }
1562  }
1563 
1564  /* Create a sorted list of ports in ascending order after resolving overlaps
1565  * and corresponding SGHs */
1566  if (CreatePortList(de_ctx, unique_port_points, size_unique_port_arr, it, &list) < 0)
1567  goto error;
1568 
1569  /* unique_port_points array is no longer needed */
1570  SCFree(unique_port_points);
1571 
1572  /* Port hashes are no longer needed */
1574 
1575  SCLogDebug("rules analyzed");
1576 
1577  /* step 3: group the list and shrink it if necessary */
1578  DetectPort *newlist = NULL;
1579  uint16_t groupmax = (direction == SIG_FLAG_TOCLIENT) ? de_ctx->max_uniq_toclient_groups :
1581  CreateGroupedPortList(de_ctx, list, &newlist, groupmax, SortCompare);
1582  list = newlist;
1583 
1584  /* step 4: deduplicate the SGH's */
1587 
1588  uint32_t cnt = 0;
1589  uint32_t own = 0;
1590  uint32_t ref = 0;
1591  DetectPort *iter;
1592  for (iter = list ; iter != NULL; iter = iter->next) {
1593  BUG_ON (iter->sh == NULL);
1594  DEBUG_VALIDATE_BUG_ON(own + ref != cnt);
1595  cnt++;
1596 
1597  SigGroupHead *lookup_sgh = SigGroupHeadHashLookup(de_ctx, iter->sh);
1598  if (lookup_sgh == NULL) {
1599  SCLogDebug("port group %p sgh %p is the original", iter, iter->sh);
1600 
1601  SigGroupHeadSetSigCnt(iter->sh, 0);
1603  SigGroupHeadSetProtoAndDirection(iter->sh, ipproto, direction);
1604  SigGroupHeadHashAdd(de_ctx, iter->sh);
1605  SigGroupHeadStore(de_ctx, iter->sh);
1606  iter->flags |= PORT_SIGGROUPHEAD_COPY;
1607  own++;
1608  } else {
1609  SCLogDebug("port group %p sgh %p is a copy", iter, iter->sh);
1610 
1611  SigGroupHeadFree(de_ctx, iter->sh);
1612  iter->sh = lookup_sgh;
1613  iter->flags |= PORT_SIGGROUPHEAD_COPY;
1614  ref++;
1615  }
1616  }
1617 #if 0
1618  for (iter = list ; iter != NULL; iter = iter->next) {
1619  SCLogInfo("PORT %u-%u %p (sgh=%s, prioritized=%s/%d)",
1620  iter->port, iter->port2, iter->sh,
1621  iter->flags & PORT_SIGGROUPHEAD_COPY ? "ref" : "own",
1622  iter->sh->init->score ? "true" : "false",
1623  iter->sh->init->score);
1624  }
1625 #endif
1626  SCLogPerf("%s %s: %u port groups, %u unique SGH's, %u copies",
1627  ipproto == 6 ? "TCP" : "UDP",
1628  direction == SIG_FLAG_TOSERVER ? "toserver" : "toclient",
1629  cnt, own, ref);
1631  return list;
1632 
1633 error:
1634  if (unique_port_points != NULL)
1635  SCFree(unique_port_points);
1636  if (it != NULL)
1638 
1639  return NULL;
1640 }
1641 
1643 {
1644  BUG_ON(s->type != SIG_TYPE_NOT_SET);
1645  int iponly = 0;
1646 
1647  /* see if the sig is dp only */
1648  if (SignatureIsPDOnly(de_ctx, s) == 1) {
1649  s->type = SIG_TYPE_PDONLY;
1650 
1651  /* see if the sig is ip only */
1652  } else if ((iponly = SignatureIsIPOnly(de_ctx, s)) > 0) {
1653  if (iponly == 1) {
1654  s->type = SIG_TYPE_IPONLY;
1655  } else if (iponly == 2) {
1657  }
1658  } else if (SignatureIsDEOnly(de_ctx, s) == 1) {
1659  s->type = SIG_TYPE_DEONLY;
1660 
1661  } else {
1662  const bool has_match = s->init_data->smlists[DETECT_SM_LIST_MATCH] != NULL;
1663  const bool has_pmatch = s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL;
1664  bool has_buffer_frame_engine = false;
1665  bool has_buffer_packet_engine = false;
1666  bool has_buffer_app_engine = false;
1667 
1668  for (uint32_t x = 0; x < s->init_data->buffer_index; x++) {
1669  const uint32_t id = s->init_data->buffers[x].id;
1670 
1672  has_buffer_packet_engine = true;
1674  has_buffer_frame_engine = true;
1675  } else {
1676  has_buffer_app_engine = true;
1677  }
1678  }
1679 
1680  if (has_buffer_packet_engine) {
1681  s->type = SIG_TYPE_PKT;
1682  } else if (has_buffer_frame_engine || has_buffer_app_engine) {
1683  s->type = SIG_TYPE_APP_TX;
1684  } else if (has_pmatch) {
1687  s->type = SIG_TYPE_PKT;
1688  } else if ((s->flags & (SIG_FLAG_REQUIRE_PACKET | SIG_FLAG_REQUIRE_STREAM)) ==
1690  s->type = SIG_TYPE_STREAM;
1691  } else {
1693  }
1694  } else if (has_match) {
1695  s->type = SIG_TYPE_PKT;
1696 
1697  /* app-layer but no inspect engines */
1698  } else if (s->flags & SIG_FLAG_APPLAYER) {
1699  s->type = SIG_TYPE_APPLAYER;
1700  } else {
1701  s->type = SIG_TYPE_PKT;
1702  }
1703  }
1704 }
1705 
1706 extern int g_skip_prefilter;
1707 /**
1708  * \brief Preprocess signature, classify ip-only, etc, build sig array
1709  *
1710  * \param de_ctx Pointer to the Detection Engine Context
1711  *
1712  * \retval 0 on success
1713  * \retval -1 on failure
1714  */
1716 {
1717  uint32_t cnt_iponly = 0;
1718  uint32_t cnt_payload = 0;
1719  uint32_t cnt_applayer = 0;
1720  uint32_t cnt_deonly = 0;
1721 
1722  if (!(de_ctx->flags & DE_QUIET)) {
1723  SCLogDebug("building signature grouping structure, stage 1: "
1724  "preprocessing rules...");
1725  }
1726 
1729  if (de_ctx->sig_array == NULL)
1730  goto error;
1731 
1732  /* now for every rule add the source group */
1733  for (Signature *s = de_ctx->sig_list; s != NULL; s = s->next) {
1734  de_ctx->sig_array[s->num] = s;
1735 
1736  SCLogDebug("Signature %" PRIu32 ", internal id %" PRIu32 ", ptrs %p %p ", s->id, s->num, s, de_ctx->sig_array[s->num]);
1737 
1738  if (s->type == SIG_TYPE_PDONLY) {
1739  SCLogDebug("Signature %"PRIu32" is considered \"PD only\"", s->id);
1740  } else if (s->type == SIG_TYPE_IPONLY) {
1741  SCLogDebug("Signature %"PRIu32" is considered \"IP only\"", s->id);
1742  cnt_iponly++;
1743  } else if (SignatureIsInspectingPayload(de_ctx, s) == 1) {
1744  SCLogDebug("Signature %"PRIu32" is considered \"Payload inspecting\"", s->id);
1745  cnt_payload++;
1746  } else if (s->type == SIG_TYPE_DEONLY) {
1747  SCLogDebug("Signature %"PRIu32" is considered \"Decoder Event only\"", s->id);
1748  cnt_deonly++;
1749  } else if (s->flags & SIG_FLAG_APPLAYER) {
1750  SCLogDebug("Signature %"PRIu32" is considered \"Applayer inspecting\"", s->id);
1751  cnt_applayer++;
1752  }
1753 
1754 #ifdef DEBUG
1755  if (SCLogDebugEnabled()) {
1756  uint16_t colen = 0;
1757  char copresent = 0;
1758  SigMatch *sm;
1759  DetectContentData *co;
1760  for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH]; sm != NULL; sm = sm->next) {
1761  if (sm->type != DETECT_CONTENT)
1762  continue;
1763 
1764  copresent = 1;
1765  co = (DetectContentData *)sm->ctx;
1766  if (co->content_len > colen)
1767  colen = co->content_len;
1768  }
1769 
1770  if (copresent && colen == 1) {
1771  SCLogDebug("signature %8u content maxlen 1", s->id);
1772  for (int proto = 0; proto < 256; proto++) {
1773  if (s->proto.proto[(proto/8)] & (1<<(proto%8)))
1774  SCLogDebug("=> proto %" PRId32 "", proto);
1775  }
1776  }
1777  }
1778 #endif /* DEBUG */
1779 
1780  if (RuleMpmIsNegated(s)) {
1781  s->flags |= SIG_FLAG_MPM_NEG;
1782  }
1783 
1784  SignatureCreateMask(s);
1787 
1788  RuleSetScore(s);
1789 
1790  /* if keyword engines are enabled in the config, handle them here */
1792  !(s->flags & SIG_FLAG_PREFILTER)) {
1793  int prefilter_list = DETECT_TBLSIZE;
1794 
1795  // TODO buffers?
1796 
1797  /* get the keyword supporting prefilter with the lowest type */
1798  for (int i = 0; i < DETECT_SM_LIST_MAX; i++) {
1799  for (SigMatch *sm = s->init_data->smlists[i]; sm != NULL; sm = sm->next) {
1800  if (sigmatch_table[sm->type].SupportsPrefilter != NULL) {
1801  if (sigmatch_table[sm->type].SupportsPrefilter(s)) {
1802  prefilter_list = MIN(prefilter_list, sm->type);
1803  }
1804  }
1805  }
1806  }
1807 
1808  /* apply that keyword as prefilter */
1809  if (prefilter_list != DETECT_TBLSIZE) {
1810  for (int i = 0; i < DETECT_SM_LIST_MAX; i++) {
1811  for (SigMatch *sm = s->init_data->smlists[i]; sm != NULL; sm = sm->next) {
1812  if (sm->type == prefilter_list) {
1813  s->init_data->prefilter_sm = sm;
1814  s->flags |= SIG_FLAG_PREFILTER;
1815  SCLogConfig("sid %u: prefilter is on \"%s\"", s->id, sigmatch_table[sm->type].name);
1816  break;
1817  }
1818  }
1819  }
1820  }
1821  }
1822 
1823  /* run buffer type callbacks if any */
1824  for (int x = 0; x < DETECT_SM_LIST_MAX; x++) {
1825  if (s->init_data->smlists[x])
1827  }
1828  for (uint32_t x = 0; x < s->init_data->buffer_index; x++) {
1830  }
1831 
1832  de_ctx->sig_cnt++;
1833  }
1834 
1835  if (!(de_ctx->flags & DE_QUIET)) {
1836  if (strlen(de_ctx->config_prefix) > 0)
1837  SCLogInfo("tenant id %d: %" PRIu32 " signatures processed. %" PRIu32 " are IP-only "
1838  "rules, %" PRIu32 " are inspecting packet payload, %" PRIu32
1839  " inspect application layer, %" PRIu32 " are decoder event only",
1840  de_ctx->tenant_id, de_ctx->sig_cnt, cnt_iponly, cnt_payload, cnt_applayer,
1841  cnt_deonly);
1842  else
1843  SCLogInfo("%" PRIu32 " signatures processed. %" PRIu32 " are IP-only "
1844  "rules, %" PRIu32 " are inspecting packet payload, %" PRIu32
1845  " inspect application layer, %" PRIu32 " are decoder event only",
1846  de_ctx->sig_cnt, cnt_iponly, cnt_payload, cnt_applayer, cnt_deonly);
1847 
1848  SCLogConfig("building signature grouping structure, stage 1: "
1849  "preprocessing rules... complete");
1850  }
1851 
1852  if (DetectFlowbitsAnalyze(de_ctx) != 0)
1853  goto error;
1854 
1855  return 0;
1856 
1857 error:
1858  return -1;
1859 }
1860 
1861 /**
1862  * \internal
1863  * \brief add a decoder event signature to the detection engine ctx
1864  */
1865 static void DetectEngineAddDecoderEventSig(DetectEngineCtx *de_ctx, Signature *s)
1866 {
1867  SCLogDebug("adding signature %"PRIu32" to the decoder event sgh", s->id);
1869 }
1870 
1871 /**
1872  * \brief Fill the global src group head, with the sigs included
1873  *
1874  * \param de_ctx Pointer to the Detection Engine Context whose Signatures have
1875  * to be processed
1876  *
1877  * \retval 0 On success
1878  * \retval -1 On failure
1879  */
1881 {
1882  SCLogDebug("building signature grouping structure, stage 2: "
1883  "building source address lists...");
1884 
1886 
1887  de_ctx->flow_gh[1].tcp = RulesGroupByPorts(de_ctx, IPPROTO_TCP, SIG_FLAG_TOSERVER);
1888  de_ctx->flow_gh[0].tcp = RulesGroupByPorts(de_ctx, IPPROTO_TCP, SIG_FLAG_TOCLIENT);
1889  de_ctx->flow_gh[1].udp = RulesGroupByPorts(de_ctx, IPPROTO_UDP, SIG_FLAG_TOSERVER);
1890  de_ctx->flow_gh[0].udp = RulesGroupByPorts(de_ctx, IPPROTO_UDP, SIG_FLAG_TOCLIENT);
1891 
1892  /* Setup the other IP Protocols (so not TCP/UDP) */
1893  RulesGroupByIPProto(de_ctx);
1894 
1895  /* now for every rule add the source group to our temp lists */
1896  for (Signature *s = de_ctx->sig_list; s != NULL; s = s->next) {
1897  SCLogDebug("s->id %"PRIu32, s->id);
1898  if (s->type == SIG_TYPE_IPONLY) {
1900  } else if (s->type == SIG_TYPE_DEONLY) {
1901  DetectEngineAddDecoderEventSig(de_ctx, s);
1902  }
1903  }
1904 
1907  return 0;
1908 }
1909 
1910 static void DetectEngineBuildDecoderEventSgh(DetectEngineCtx *de_ctx)
1911 {
1912  if (de_ctx->decoder_event_sgh == NULL)
1913  return;
1914 
1915  uint32_t max_idx = DetectEngineGetMaxSigId(de_ctx);
1918 }
1919 
1921 {
1922  /* prepare the decoder event sgh */
1923  DetectEngineBuildDecoderEventSgh(de_ctx);
1924  return 0;
1925 }
1926 
1928 {
1929  BUG_ON(de_ctx == NULL);
1930 
1931  SCLogDebug("cleaning up signature grouping structure...");
1932 
1935  de_ctx->decoder_event_sgh = NULL;
1936 
1937  for (int f = 0; f < FLOW_STATES; f++) {
1938  for (int p = 0; p < 256; p++) {
1939  de_ctx->flow_gh[f].sgh[p] = NULL;
1940  }
1941 
1942  /* free lookup lists */
1944  de_ctx->flow_gh[f].tcp = NULL;
1946  de_ctx->flow_gh[f].udp = NULL;
1947  }
1948 
1949  for (uint32_t idx = 0; idx < de_ctx->sgh_array_cnt; idx++) {
1950  SigGroupHead *sgh = de_ctx->sgh_array[idx];
1951  if (sgh == NULL)
1952  continue;
1953 
1954  SCLogDebug("sgh %p", sgh);
1955  SigGroupHeadFree(de_ctx, sgh);
1956  }
1958  de_ctx->sgh_array = NULL;
1959  de_ctx->sgh_array_cnt = 0;
1960  de_ctx->sgh_array_size = 0;
1961 
1963 
1964  SCLogDebug("cleaning up signature grouping structure... complete");
1965  return 0;
1966 }
1967 
1968 #if 0
1969 static void DbgPrintSigs(DetectEngineCtx *de_ctx, SigGroupHead *sgh)
1970 {
1971  if (sgh == NULL) {
1972  printf("\n");
1973  return;
1974  }
1975 
1976  uint32_t sig;
1977  for (sig = 0; sig < sgh->sig_cnt; sig++) {
1978  printf("%" PRIu32 " ", sgh->match_array[sig]->id);
1979  }
1980  printf("\n");
1981 }
1982 
1983 static void DbgPrintSigs2(DetectEngineCtx *de_ctx, SigGroupHead *sgh)
1984 {
1985  if (sgh == NULL || sgh->init == NULL) {
1986  printf("\n");
1987  return;
1988  }
1989 
1990  uint32_t sig;
1991  for (sig = 0; sig < DetectEngineGetMaxSigId(de_ctx); sig++) {
1992  if (sgh->init->sig_array[(sig/8)] & (1<<(sig%8))) {
1993  printf("%" PRIu32 " ", de_ctx->sig_array[sig]->id);
1994  }
1995  }
1996  printf("\n");
1997 }
1998 #endif
1999 
2000 /** \brief finalize preparing sgh's */
2002 {
2003  SCEnter();
2004 
2005  //SCLogInfo("sgh's %"PRIu32, de_ctx->sgh_array_cnt);
2006 
2007  uint32_t cnt = 0;
2008  for (uint32_t idx = 0; idx < de_ctx->sgh_array_cnt; idx++) {
2009  SigGroupHead *sgh = de_ctx->sgh_array[idx];
2010  if (sgh == NULL)
2011  continue;
2012 
2013  SCLogDebug("sgh %p", sgh);
2014 
2016  SCLogDebug("filestore count %u", sgh->filestore_cnt);
2017 
2019 
2021 
2022  sgh->id = idx;
2023  cnt++;
2024  }
2025  SCLogPerf("Unique rule groups: %u", cnt);
2026 
2028 
2029  if (de_ctx->decoder_event_sgh != NULL) {
2030  /* no need to set filestore count here as that would make a
2031  * signature not decode event only. */
2033  }
2034 
2035  int dump_grouping = 0;
2036  (void)ConfGetBool("detect.profiling.grouping.dump-to-disk", &dump_grouping);
2037 
2038  if (dump_grouping) {
2039  int add_rules = 0;
2040  (void)ConfGetBool("detect.profiling.grouping.include-rules", &add_rules);
2041  int add_mpm_stats = 0;
2042  (void)ConfGetBool("detect.profiling.grouping.include-mpm-stats", &add_mpm_stats);
2043 
2044  RulesDumpGrouping(de_ctx, add_rules, add_mpm_stats);
2045  }
2046 
2047  for (uint32_t idx = 0; idx < de_ctx->sgh_array_cnt; idx++) {
2048  SigGroupHead *sgh = de_ctx->sgh_array[idx];
2049  if (sgh == NULL)
2050  continue;
2052  sgh->init = NULL;
2053  }
2054  /* cleanup the hashes now since we won't need them
2055  * after the initialization phase. */
2057 
2058 #ifdef PROFILING
2060 #endif
2061  SCReturnInt(0);
2062 }
2063 
2064 extern bool rule_engine_analysis_set;
2065 /** \internal
2066  * \brief perform final per signature setup tasks
2067  *
2068  * - Create SigMatchData arrays from the init only SigMatch lists
2069  * - Setup per signature inspect engines
2070  * - remove signature init data.
2071  */
2072 static int SigMatchPrepare(DetectEngineCtx *de_ctx)
2073 {
2074  SCEnter();
2075 
2076  Signature *s = de_ctx->sig_list;
2077  for (; s != NULL; s = s->next) {
2078  /* set up inspect engines */
2080 
2081  /* built-ins */
2082  for (int type = 0; type < DETECT_SM_LIST_MAX; type++) {
2083  /* skip PMATCH if it is used in a stream 'app engine' instead */
2085  continue;
2086  SigMatch *sm = s->init_data->smlists[type];
2088  }
2089  /* set up the pkt inspection engines */
2091 
2095  }
2096  /* free lists. Ctx' are xferred to sm_arrays so won't get freed */
2097  for (uint32_t i = 0; i < DETECT_SM_LIST_MAX; i++) {
2098  SigMatch *sm = s->init_data->smlists[i];
2099  while (sm != NULL) {
2100  SigMatch *nsm = sm->next;
2101  SigMatchFree(de_ctx, sm);
2102  sm = nsm;
2103  }
2104  }
2105  for (uint32_t i = 0; i < (uint32_t)s->init_data->transforms.cnt; i++) {
2106  if (s->init_data->transforms.transforms[i].options) {
2107  int transform = s->init_data->transforms.transforms[i].transform;
2108  sigmatch_table[transform].Free(
2110  s->init_data->transforms.transforms[i].options = NULL;
2111  }
2112  }
2113  for (uint32_t x = 0; x < s->init_data->buffer_index; x++) {
2114  SigMatch *sm = s->init_data->buffers[x].head;
2115  while (sm != NULL) {
2116  SigMatch *nsm = sm->next;
2117  SigMatchFree(de_ctx, sm);
2118  sm = nsm;
2119  }
2120  }
2121  if (s->init_data->cidr_dst != NULL)
2123 
2124  if (s->init_data->cidr_src != NULL)
2126 
2127  SCFree(s->init_data->buffers);
2128  SCFree(s->init_data);
2129  s->init_data = NULL;
2130  }
2131 
2133  SCReturnInt(0);
2134 }
2135 
2136 /**
2137  * \brief Convert the signature list into the runtime match structure.
2138  *
2139  * \param de_ctx Pointer to the Detection Engine Context whose Signatures have
2140  * to be processed
2141  *
2142  * \retval 0 On Success.
2143  * \retval -1 On failure.
2144  */
2146 {
2147  Signature *s = de_ctx->sig_list;
2148 
2149  /* Assign the unique order id of signatures after sorting,
2150  * so the IP Only engine process them in order too. Also
2151  * reset the old signums and assign new signums. We would
2152  * have experienced Sig reordering by now, hence the new
2153  * signums. */
2154  de_ctx->signum = 0;
2155  while (s != NULL) {
2156  s->num = de_ctx->signum++;
2157 
2158  s = s->next;
2159  }
2160 
2162  return -1;
2163 
2164  SigInitStandardMpmFactoryContexts(de_ctx);
2165 
2166  if (SigPrepareStage1(de_ctx) != 0) {
2167  FatalError("initializing the detection engine failed");
2168  }
2169 
2170  if (SigPrepareStage2(de_ctx) != 0) {
2171  FatalError("initializing the detection engine failed");
2172  }
2173 
2174  if (SigPrepareStage3(de_ctx) != 0) {
2175  FatalError("initializing the detection engine failed");
2176  }
2177  if (SigPrepareStage4(de_ctx) != 0) {
2178  FatalError("initializing the detection engine failed");
2179  }
2180 
2185  if (r != 0) {
2186  FatalError("initializing the detection engine failed");
2187  }
2188 
2189  if (SigMatchPrepare(de_ctx) != 0) {
2190  FatalError("initializing the detection engine failed");
2191  }
2192 
2193 #ifdef PROFILING
2196  de_ctx->profile_match_logging_threshold = UINT_MAX; // disabled
2197 
2198  intmax_t v = 0;
2199  if (ConfGetInt("detect.profiling.inspect-logging-threshold", &v) == 1)
2200  de_ctx->profile_match_logging_threshold = (uint32_t)v;
2201 #endif
2202 #ifdef PROFILE_RULES
2203  SCProfilingRuleInitCounters(de_ctx);
2204 #endif
2205 
2208  }
2209  return 0;
2210 }
2211 
2213 {
2215 
2216  return 0;
2217 }
detect-tcp-flags.h
HashListTableGetListData
#define HashListTableGetListData(hb)
Definition: util-hashlist.h:56
SIG_TYPE_STREAM
@ SIG_TYPE_STREAM
Definition: detect.h:72
DETECT_FLOW_FLAG_TOCLIENT
#define DETECT_FLOW_FLAG_TOCLIENT
Definition: detect-flow.h:28
ConfGetInt
int ConfGetInt(const char *name, intmax_t *val)
Retrieve a configuration value as an integer.
Definition: conf.c:399
SignatureInitDataBuffer_::head
SigMatch * head
Definition: detect.h:537
detect-content.h
ts
uint64_t ts
Definition: source-erf-file.c:55
util-port-interval-tree.h
detect-engine.h
DetectEngineResetMaxSigId
void DetectEngineResetMaxSigId(DetectEngineCtx *de_ctx)
Definition: detect-engine.c:3043
DetectEngineBufferTypeSupportsPacketGetById
bool DetectEngineBufferTypeSupportsPacketGetById(const DetectEngineCtx *de_ctx, const int id)
Definition: detect-engine.c:1261
DETECT_SM_LIST_PMATCH
@ DETECT_SM_LIST_PMATCH
Definition: detect.h:116
SIG_MASK_REQUIRE_REAL_PKT
#define SIG_MASK_REQUIRE_REAL_PKT
Definition: detect.h:306
MASK_TCP_UNUSUAL_FLAGS
#define MASK_TCP_UNUSUAL_FLAGS
Definition: detect-engine-build.c:402
DetectFlagsSignatureNeedsSynOnlyPackets
int DetectFlagsSignatureNeedsSynOnlyPackets(const Signature *s)
Definition: detect-tcp-flags.c:535
SignatureInitData_::smlists
struct SigMatch_ * smlists[DETECT_SM_LIST_MAX]
Definition: detect.h:588
detect-engine-proto.h
detect-dsize.h
sigmatch_table
SigTableElmt * sigmatch_table
Definition: detect-parse.c:128
PKT_HAS_FLOW
#define PKT_HAS_FLOW
Definition: decode.h:1268
UniquePortPoint_
Definition: detect-engine-build.c:1315
SIG_TYPE_APP_TX
@ SIG_TYPE_APP_TX
Definition: detect.h:75
SigMatchFree
void SigMatchFree(DetectEngineCtx *de_ctx, SigMatch *sm)
free a SigMatch
Definition: detect-parse.c:337
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1299
DetectEngineCtx_::decoder_event_sgh
struct SigGroupHead_ * decoder_event_sgh
Definition: detect.h:931
DetectPortHashInit
int DetectPortHashInit(DetectEngineCtx *de_ctx)
Initializes the hash table in the detection engine context to hold the DetectPort hash.
Definition: detect-engine-port.c:1370
DetectEngineCtx_::flow_gh
DetectEngineLookupFlow flow_gh[FLOW_STATES]
Definition: detect.h:873
FILE_SIG_NEED_SHA1
#define FILE_SIG_NEED_SHA1
Definition: detect.h:318
SigPrepareStage4
int SigPrepareStage4(DetectEngineCtx *de_ctx)
finalize preparing sgh's
Definition: detect-engine-build.c:2001
detect-engine-siggroup.h
DetectFlowData_
Definition: detect-flow.h:37
SigTableElmt_::name
const char * name
Definition: detect.h:1309
PKT_IS_PSEUDOPKT
#define PKT_IS_PSEUDOPKT(p)
return 1 if the packet is a pseudo packet
Definition: decode.h:1321
Signature_::num
SigIntId num
Definition: detect.h:615
DetectEngineBufferRunSetupCallback
void DetectEngineBufferRunSetupCallback(const DetectEngineCtx *de_ctx, const int id, Signature *s)
Definition: detect-engine.c:1298
ConfGetBool
int ConfGetBool(const char *name, int *val)
Retrieve a configuration value as a boolean.
Definition: conf.c:482
SigGroupHead_
Container for matching data for a signature group.
Definition: detect.h:1465
DetectListToHumanString
const char * DetectListToHumanString(int list)
Definition: detect-parse.c:161
SIG_FLAG_INIT_FLOW
#define SIG_FLAG_INIT_FLOW
Definition: detect.h:288
SigFree
void SigFree(DetectEngineCtx *, Signature *)
Definition: detect-parse.c:1629
DumpPatterns
void DumpPatterns(DetectEngineCtx *de_ctx)
Definition: detect-engine-analyzer.c:1322
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
SigGroupHeadBuildNonPrefilterArray
int SigGroupHeadBuildNonPrefilterArray(DetectEngineCtx *de_ctx, SigGroupHead *sgh)
build an array of rule id's for sigs with no prefilter Also updated de_ctx::non_pf_store_cnt_max to t...
Definition: detect-engine-siggroup.c:625
DetectFlagsData_::flags
uint8_t flags
Definition: detect-tcp-flags.h:38
SigGroupHeadInitData_::sig_array
uint8_t * sig_array
Definition: detect.h:1440
DetectPortFree
void DetectPortFree(const DetectEngineCtx *de_ctx, DetectPort *dp)
Free a DetectPort and its members.
Definition: detect-engine-port.c:80
DETECT_CONTENT
@ DETECT_CONTENT
Definition: detect-engine-register.h:72
DetectEngineCtx_::max_uniq_toclient_groups
uint16_t max_uniq_toclient_groups
Definition: detect.h:904
MpmStoreReportStats
void MpmStoreReportStats(const DetectEngineCtx *de_ctx)
Definition: detect-engine-mpm.c:1432
SignatureInitData_::prefilter_sm
SigMatch * prefilter_sm
Definition: detect.h:569
SignatureInitData_::src_contains_negation
bool src_contains_negation
Definition: detect.h:551
DETECT_FLOW
@ DETECT_FLOW
Definition: detect-engine-register.h:56
Signature_::alproto
AppProto alproto
Definition: detect.h:608
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:269
DETECT_UINT_NE
#define DETECT_UINT_NE
Definition: detect-engine-uint.h:36
IPOnlyDeinit
void IPOnlyDeinit(DetectEngineCtx *de_ctx, DetectEngineIPOnlyCtx *io_ctx)
Deinitialize the IP Only detection engine context.
Definition: detect-engine-iponly.c:952
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
DetectPort_::port
uint16_t port
Definition: detect.h:218
SCPortIntervalFindOverlappingRanges
void SCPortIntervalFindOverlappingRanges(DetectEngineCtx *de_ctx, const uint16_t port, const uint16_t port2, const struct PI *head, DetectPort **list)
Callee function to find all overlapping port ranges as asked by the detection engine during Stage 2 o...
Definition: util-port-interval-tree.c:315
PORT_SIGGROUPHEAD_COPY
#define PORT_SIGGROUPHEAD_COPY
Definition: detect.h:214
AppProto
uint16_t AppProto
Definition: app-layer-protos.h:81
DETECT_DECODE_EVENT
@ DETECT_DECODE_EVENT
Definition: detect-engine-register.h:123
DETECT_SM_LIST_DYNAMIC_START
@ DETECT_SM_LIST_DYNAMIC_START
Definition: detect.h:135
Packet_::flags
uint32_t flags
Definition: decode.h:513
UNDEFINED_PORT
#define UNDEFINED_PORT
Definition: detect-engine-build.c:1311
PatternStrength
uint32_t PatternStrength(uint8_t *pat, uint16_t patlen)
Predict a strength value for patterns.
Definition: detect-engine-mpm.c:930
DetectFlowbitsAnalyze
int DetectFlowbitsAnalyze(DetectEngineCtx *de_ctx)
Definition: detect-flowbits.c:420
DetectSetFastPatternAndItsId
int DetectSetFastPatternAndItsId(DetectEngineCtx *de_ctx)
Figure out the FP and their respective content ids for all the sigs in the engine.
Definition: detect-engine-mpm.c:2417
DETECT_AL_APP_LAYER_EVENT
@ DETECT_AL_APP_LAYER_EVENT
Definition: detect-engine-register.h:203
AppProtoToString
const char * AppProtoToString(AppProto alproto)
Maps the ALPROTO_*, to its string equivalent.
Definition: app-layer-protos.c:75
SigTableElmt_::flags
uint16_t flags
Definition: detect.h:1303
SCProfilingSghInitCounters
void SCProfilingSghInitCounters(DetectEngineCtx *de_ctx)
Register the keyword profiling counters.
Definition: util-profiling-rulegroups.c:369
DetectEngineCtx_
main detection engine ctx
Definition: detect.h:843
DETECT_PROTO_ANY
#define DETECT_PROTO_ANY
Definition: detect-engine-proto.h:28
SIG_TYPE_PKT_STREAM
@ SIG_TYPE_PKT_STREAM
Definition: detect.h:71
DetectFlagsSignatureNeedsSynPackets
int DetectFlagsSignatureNeedsSynPackets(const Signature *s)
Definition: detect-tcp-flags.c:516
TransformData_::options
void * options
Definition: detect.h:405
DetectFlowbitsData_::cmd
uint8_t cmd
Definition: detect-flowbits.h:37
HashListTableGetListHead
HashListTableBucket * HashListTableGetListHead(HashListTable *ht)
Definition: util-hashlist.c:287
SigGroupHeadSetProtoAndDirection
void SigGroupHeadSetProtoAndDirection(SigGroupHead *sgh, uint8_t ipproto, int dir)
Definition: detect-engine-siggroup.c:497
SIGMATCH_DEONLY_COMPAT
#define SIGMATCH_DEONLY_COMPAT
Definition: detect.h:1497
DETECT_UINT_EQ
#define DETECT_UINT_EQ
Definition: detect-engine-uint.h:35
DetectEngineBufferTypeGetNameById
const char * DetectEngineBufferTypeGetNameById(const DetectEngineCtx *de_ctx, const int id)
Definition: detect-engine.c:1124
DetectMpmInitializeBuiltinMpms
void DetectMpmInitializeBuiltinMpms(DetectEngineCtx *de_ctx)
Definition: detect-engine-mpm.c:726
SIG_FLAG_DST_ANY
#define SIG_FLAG_DST_ANY
Definition: detect.h:239
util-var-name.h
SIG_FLAG_REQUIRE_STREAM
#define SIG_FLAG_REQUIRE_STREAM
Definition: detect.h:251
MIN
#define MIN(x, y)
Definition: suricata-common.h:391
rule_engine_analysis_set
bool rule_engine_analysis_set
Definition: detect-engine-loader.c:55
DE_QUIET
#define DE_QUIET
Definition: detect.h:323
DetectPort_::next
struct DetectPort_ * next
Definition: detect.h:231
DetectEngineCtx_::tcp_priorityports
DetectPort * tcp_priorityports
Definition: detect.h:982
DetectEngineCtx_::dport_hash_table
HashListTable * dport_hash_table
Definition: detect.h:980
Signature_::sm_arrays
SigMatchData * sm_arrays[DETECT_SM_LIST_MAX]
Definition: detect.h:656
DetectEngineCtx_::prefilter_setting
enum DetectEnginePrefilterSetting prefilter_setting
Definition: detect.h:978
SignatureInitData_::init_flags
uint32_t init_flags
Definition: detect.h:555
JSON_ESCAPE_SLASH
#define JSON_ESCAPE_SLASH
Definition: suricata-common.h:277
proto
uint8_t proto
Definition: decode-template.h:0
DetectPort_::sh
struct SigGroupHead_ * sh
Definition: detect.h:228
DetectEngineCtx_::udp_priorityports
DetectPort * udp_priorityports
Definition: detect.h:983
DetectContentData_
Definition: detect-content.h:93
DETECT_FLOWBITS_CMD_ISSET
#define DETECT_FLOWBITS_CMD_ISSET
Definition: detect-flowbits.h:32
PKT_NOPAYLOAD_INSPECTION
#define PKT_NOPAYLOAD_INSPECTION
Definition: decode.h:1257
SigCleanSignatures
void SigCleanSignatures(DetectEngineCtx *de_ctx)
Definition: detect-engine-build.c:55
DetectPortPrintList
void DetectPortPrintList(DetectPort *head)
Helper function used to print the list of ports present in this DetectPort list.
Definition: detect-engine-port.c:100
DETECT_UINT_GT
#define DETECT_UINT_GT
Definition: detect-engine-uint.h:32
SigPrepareStage1
int SigPrepareStage1(DetectEngineCtx *de_ctx)
Preprocess signature, classify ip-only, etc, build sig array.
Definition: detect-engine-build.c:1715
DETECT_PGSCORE_RULE_SYN_ONLY
#define DETECT_PGSCORE_RULE_SYN_ONLY
Definition: detect-engine-build.c:53
SIG_FLAG_TOCLIENT
#define SIG_FLAG_TOCLIENT
Definition: detect.h:268
MAX
#define MAX(x, y)
Definition: suricata-common.h:395
SIG_FLAG_SRC_ANY
#define SIG_FLAG_SRC_ANY
Definition: detect.h:238
SigGroupHeadSetupFiles
void SigGroupHeadSetupFiles(const DetectEngineCtx *de_ctx, SigGroupHead *sgh)
Set the need hash flag in the sgh.
Definition: detect-engine-siggroup.c:584
ALPROTO_MAX
@ ALPROTO_MAX
Definition: app-layer-protos.h:76
SIG_TYPE_APPLAYER
@ SIG_TYPE_APPLAYER
Definition: detect.h:74
SignatureIsFilesizeInspecting
int SignatureIsFilesizeInspecting(const Signature *s)
Check if a signature contains the filesize keyword.
Definition: detect-engine-build.c:186
Packet_::payload_len
uint16_t payload_len
Definition: decode.h:575
DetectPort_::port2
uint16_t port2
Definition: detect.h:219
detect-engine-prefilter.h
Packet_::app_layer_events
AppLayerDecoderEvents * app_layer_events
Definition: decode.h:601
Packet_::events
PacketEngineEvents events
Definition: decode.h:599
FLOW_STATES
#define FLOW_STATES
Definition: detect.h:835
EngineAnalysisAddAllRulePatterns
void EngineAnalysisAddAllRulePatterns(DetectEngineCtx *de_ctx, const Signature *s)
add all patterns on our stats hash Used to fill the hash later used by DumpPatterns()
Definition: detect-engine-mpm.c:2479
DetectPort_::flags
uint8_t flags
Definition: detect.h:221
DetectPortPrint
void DetectPortPrint(DetectPort *dp)
Helper function that print the DetectPort info.
Definition: detect-engine-port.c:590
PacketCreateMask
void PacketCreateMask(Packet *p, SignatureMask *mask, AppProto alproto, bool app_decoder_events)
Definition: detect-engine-build.c:407
SIG_FLAG_APPLAYER
#define SIG_FLAG_APPLAYER
Definition: detect.h:246
SigGroupHeadHashInit
int SigGroupHeadHashInit(DetectEngineCtx *de_ctx)
Initializes the hash table in the detection engine context to hold the SigGroupHeads.
Definition: detect-engine-siggroup.c:255
FILE_SIG_NEED_MD5
#define FILE_SIG_NEED_MD5
Definition: detect.h:317
DETECT_PREFILTER_AUTO
@ DETECT_PREFILTER_AUTO
Definition: detect.h:820
DetectEngineCtx_::sgh_array_size
uint32_t sgh_array_size
Definition: detect.h:916
SignatureIsFileSha256Inspecting
int SignatureIsFileSha256Inspecting(const Signature *s)
Check if a signature contains the filesha256 keyword.
Definition: detect-engine-build.c:170
Signature_::next
struct Signature_ * next
Definition: detect.h:675
DetectFlowbitsData_
Definition: detect-flowbits.h:35
DetectEngineMultiTenantEnabled
int DetectEngineMultiTenantEnabled(void)
Definition: detect-engine.c:3860
HashListTableGetListNext
#define HashListTableGetListNext(hb)
Definition: util-hashlist.h:55
DETECT_SM_LIST_POSTMATCH
@ DETECT_SM_LIST_POSTMATCH
Definition: detect.h:124
SigGroupHeadInitData_::score
int score
Definition: detect.h:1445
DetectPortCopySingle
DetectPort * DetectPortCopySingle(DetectEngineCtx *de_ctx, DetectPort *src)
Function that return a copy of DetectPort src sigs.
Definition: detect-engine-port.c:550
SIG_FLAG_TOSERVER
#define SIG_FLAG_TOSERVER
Definition: detect.h:267
DetectPortParse
int DetectPortParse(const DetectEngineCtx *de_ctx, DetectPort **head, const char *str)
Function for parsing port strings.
Definition: detect-engine-port.c:1182
SigAddressCleanupStage1
int SigAddressCleanupStage1(DetectEngineCtx *de_ctx)
Definition: detect-engine-build.c:1927
SCPortIntervalInsert
int SCPortIntervalInsert(DetectEngineCtx *de_ctx, SCPortIntervalTree *it, const DetectPort *p)
Function to insert a node in the interval tree.
Definition: util-port-interval-tree.c:109
SIG_TYPE_PKT
@ SIG_TYPE_PKT
Definition: detect.h:70
TCPHdr_::th_flags
uint8_t th_flags
Definition: decode-tcp.h:155
SigGroupHeadBuildMatchArray
int SigGroupHeadBuildMatchArray(DetectEngineCtx *de_ctx, SigGroupHead *sgh, uint32_t max_idx)
Create an array with all the internal ids of the sigs that this sig group head will check for.
Definition: detect-engine-siggroup.c:546
SigGroupHeadInitData_::sig_cnt
SigIntId sig_cnt
Definition: detect.h:1458
DETECT_CONTENT_ENDS_WITH
#define DETECT_CONTENT_ENDS_WITH
Definition: detect-content.h:42
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:17
DETECT_FLOWINT
@ DETECT_FLOWINT
Definition: detect-engine-register.h:65
IPOnlyInit
void IPOnlyInit(DetectEngineCtx *de_ctx, DetectEngineIPOnlyCtx *io_ctx)
Setup the IP Only detection engine context.
Definition: detect-engine-iponly.c:913
SIG_MASK_REQUIRE_ENGINE_EVENT
#define SIG_MASK_REQUIRE_ENGINE_EVENT
Definition: detect.h:308
SIG_TYPE_IPONLY
@ SIG_TYPE_IPONLY
Definition: detect.h:64
SignatureInitData_::mpm_sm
SigMatch * mpm_sm
Definition: detect.h:567
SigFindSignatureBySidGid
Signature * SigFindSignatureBySidGid(DetectEngineCtx *de_ctx, uint32_t sid, uint32_t gid)
Find a specific signature by sid and gid.
Definition: detect-engine-build.c:79
DetectConfigData_::scope
enum ConfigScope scope
Definition: detect-config.h:32
DetectEngineGetMaxSigId
#define DetectEngineGetMaxSigId(de_ctx)
Definition: detect-engine.h:105
DETECT_FLOW_FLAG_TOSERVER
#define DETECT_FLOW_FLAG_TOSERVER
Definition: detect-flow.h:27
FILE_SIG_NEED_MAGIC
#define FILE_SIG_NEED_MAGIC
Definition: detect.h:315
SignatureInitData_::mpm_sm_list
int mpm_sm_list
Definition: detect.h:565
SIG_MASK_REQUIRE_FLOW
#define SIG_MASK_REQUIRE_FLOW
Definition: detect.h:302
SignatureInitData_::cidr_dst
IPOnlyCIDRItem * cidr_dst
Definition: detect.h:562
DETECT_CONTENT_DEPTH
#define DETECT_CONTENT_DEPTH
Definition: detect-content.h:33
SCEnter
#define SCEnter(...)
Definition: util-debug.h:271
detect-engine-mpm.h
DetectEngineLookupFlow_::sgh
struct SigGroupHead_ * sgh[256]
Definition: detect.h:787
detect.h
SIG_MASK_REQUIRE_FLAGS_INITDEINIT
#define SIG_MASK_REQUIRE_FLAGS_INITDEINIT
Definition: detect.h:303
SCProfilingPrefilterInitCounters
void SCProfilingPrefilterInitCounters(DetectEngineCtx *de_ctx)
Register the prefilter profiling counters.
Definition: util-profiling-prefilter.c:300
SigMatchList2DataArray
SigMatchData * SigMatchList2DataArray(SigMatch *head)
convert SigMatch list to SigMatchData array
Definition: detect-parse.c:1857
PKT_DETECT_HAS_STREAMDATA
#define PKT_DETECT_HAS_STREAMDATA
Definition: decode.h:1307
SigMatch_::next
struct SigMatch_ * next
Definition: detect.h:353
DETECT_CONTENT_NEGATED
#define DETECT_CONTENT_NEGATED
Definition: detect-content.h:40
detect-engine-port.h
DETECT_ENGINE_EVENT
@ DETECT_ENGINE_EVENT
Definition: detect-engine-register.h:224
DETECT_SM_LIST_MATCH
@ DETECT_SM_LIST_MATCH
Definition: detect.h:114
SCLogWarning
#define SCLogWarning(...)
Macro used to log WARNING messages.
Definition: util-debug.h:249
DetectContentPropagateLimits
void DetectContentPropagateLimits(Signature *s)
Definition: detect-content.c:735
DetectPort_
Port structure for detection engine.
Definition: detect.h:217
SigGroupHead_::init
SigGroupHeadInitData * init
Definition: detect.h:1488
DetectEngineCtx_::sig_cnt
uint32_t sig_cnt
Definition: detect.h:852
DETECT_PGSCORE_RULE_NO_MPM
#define DETECT_PGSCORE_RULE_NO_MPM
Definition: detect-engine-build.c:52
UniquePortPoint_::single
bool single
Definition: detect-engine-build.c:1317
SignatureInitData_::cidr_src
IPOnlyCIDRItem * cidr_src
Definition: detect.h:562
SigMatch_::ctx
SigMatchCtx * ctx
Definition: detect.h:352
DetectProto_::proto
uint8_t proto[256/8]
Definition: detect-engine-proto.h:36
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:300
AppLayerDecoderEvents_::cnt
uint8_t cnt
Definition: app-layer-events.h:40
IPOnlyPrepare
void IPOnlyPrepare(DetectEngineCtx *de_ctx)
Build the radix trees from the lists of parsed addresses in CIDR format the result should be 4 radix ...
Definition: detect-engine-iponly.c:1138
SigGroupCleanup
int SigGroupCleanup(DetectEngineCtx *de_ctx)
Definition: detect-engine-build.c:2212
DETECT_PGSCORE_RULE_MPM_FAST_PATTERN
#define DETECT_PGSCORE_RULE_MPM_FAST_PATTERN
Definition: detect-engine-build.c:50
SIG_FLAG_REQUIRE_FLOWVAR
#define SIG_FLAG_REQUIRE_FLOWVAR
Definition: detect.h:263
util-profiling.h
FILE_SIG_NEED_SHA256
#define FILE_SIG_NEED_SHA256
Definition: detect.h:319
DetectEngineLookupFlow_::udp
DetectPort * udp
Definition: detect.h:786
Signature_::flags
uint32_t flags
Definition: detect.h:604
Packet_
Definition: decode.h:476
detect-engine-build.h
type
uint16_t type
Definition: decode-vlan.c:107
DETECT_UINT_GTE
#define DETECT_UINT_GTE
Definition: detect-engine-uint.h:33
IPOnlyPrint
void IPOnlyPrint(DetectEngineCtx *de_ctx, DetectEngineIPOnlyCtx *io_ctx)
Print stats of the IP Only engine.
Definition: detect-engine-iponly.c:941
DetectConfigData_
Definition: detect-config.h:29
DetectContentData_::flags
uint32_t flags
Definition: detect-content.h:104
DETECT_AL_APP_LAYER_PROTOCOL
@ DETECT_AL_APP_LAYER_PROTOCOL
Definition: detect-engine-register.h:37
DetectEngineCtx_::max_uniq_toserver_groups
uint16_t max_uniq_toserver_groups
Definition: detect.h:905
IPOnlyAddSignature
void IPOnlyAddSignature(DetectEngineCtx *de_ctx, DetectEngineIPOnlyCtx *io_ctx, Signature *s)
Add a signature to the lists of Addresses in CIDR format (sorted) this step is necessary to build the...
Definition: detect-engine-iponly.c:1410
SC_OK
@ SC_OK
Definition: util-error.h:27
DETECT_CONFIG
@ DETECT_CONFIG
Definition: detect-engine-register.h:227
Signature_::init_data
SignatureInitData * init_data
Definition: detect.h:672
DetectEngineCtx_::sgh_array_cnt
uint32_t sgh_array_cnt
Definition: detect.h:915
SigGroupHeadAppendSig
int SigGroupHeadAppendSig(const DetectEngineCtx *de_ctx, SigGroupHead **sgh, const Signature *s)
Add a Signature to a SigGroupHead.
Definition: detect-engine-siggroup.c:330
DetectEngineCtx_::sgh_array
struct SigGroupHead_ ** sgh_array
Definition: detect.h:914
UniquePortPoint_::port
uint16_t port
Definition: detect-engine-build.c:1316
SignatureInitData_::dst_contains_negation
bool dst_contains_negation
Definition: detect.h:552
SigGroupHeadFree
void SigGroupHeadFree(const DetectEngineCtx *de_ctx, SigGroupHead *sgh)
Free a SigGroupHead and its members.
Definition: detect-engine-siggroup.c:162
DetectEngineTransforms::transforms
TransformData transforms[DETECT_TRANSFORMS_MAX]
Definition: detect.h:409
SIG_TYPE_DEONLY
@ SIG_TYPE_DEONLY
Definition: detect.h:69
detect-flowbits.h
SIG_MASK_REQUIRE_PAYLOAD
#define SIG_MASK_REQUIRE_PAYLOAD
Definition: detect.h:301
SCLogInfo
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:224
DETECT_DSIZE
@ DETECT_DSIZE
Definition: detect-engine-register.h:54
Signature_::sp
DetectPort * sp
Definition: detect.h:644
SIG_TYPE_NOT_SET
@ SIG_TYPE_NOT_SET
Definition: detect.h:63
SignatureIsFileSha1Inspecting
int SignatureIsFileSha1Inspecting(const Signature *s)
Check if a signature contains the filesha1 keyword.
Definition: detect-engine-build.c:154
SCPortIntervalTreeInit
SCPortIntervalTree * SCPortIntervalTreeInit(void)
Function to initialize the interval tree.
Definition: util-port-interval-tree.c:58
IPOnlyCIDRListFree
void IPOnlyCIDRListFree(IPOnlyCIDRItem *tmphead)
This function free a IPOnlyCIDRItem list.
Definition: detect-engine-iponly.c:482
SigGroupBuild
int SigGroupBuild(DetectEngineCtx *de_ctx)
Convert the signature list into the runtime match structure.
Definition: detect-engine-build.c:2145
DetectEngineCtx_::config_prefix
char config_prefix[64]
Definition: detect.h:965
SIG_FLAG_MPM_NEG
#define SIG_FLAG_MPM_NEG
Definition: detect.h:253
SCPortIntervalTree_::tree
struct PI tree
Definition: util-port-interval-tree.h:30
detect-engine-analyzer.h
SIG_FLAG_INIT_STATE_MATCH
#define SIG_FLAG_INIT_STATE_MATCH
Definition: detect.h:292
DetectEngineBufferTypeSupportsFramesGetById
bool DetectEngineBufferTypeSupportsFramesGetById(const DetectEngineCtx *de_ctx, const int id)
Definition: detect-engine.c:1279
EngineAnalysisRules2
void EngineAnalysisRules2(const DetectEngineCtx *de_ctx, const Signature *s)
Definition: detect-engine-analyzer.c:971
SigGroupHeadSetSigCnt
void SigGroupHeadSetSigCnt(SigGroupHead *sgh, uint32_t max_idx)
Updates the SigGroupHead->sig_cnt with the total count of all the Signatures present in this SigGroup...
Definition: detect-engine-siggroup.c:457
DetectProto_::flags
uint8_t flags
Definition: detect-engine-proto.h:37
cnt
uint32_t cnt
Definition: tmqh-packetpool.h:7
util-conf.h
DetectMpmPrepareFrameMpms
int DetectMpmPrepareFrameMpms(DetectEngineCtx *de_ctx)
initialize mpm contexts for applayer buffers that are in "single or "shared" mode.
Definition: detect-engine-mpm.c:513
SINGLE_PORT
#define SINGLE_PORT
Definition: detect-engine-build.c:1313
DetectEnginePktInspectionSetup
int DetectEnginePktInspectionSetup(Signature *s)
Definition: detect-engine.c:2018
tail
Host * tail
Definition: host.h:2
Signature_::proto
DetectProto proto
Definition: detect.h:622
suricata-common.h
SIG_MASK_REQUIRE_NO_PAYLOAD
#define SIG_MASK_REQUIRE_NO_PAYLOAD
Definition: detect.h:305
SIG_FLAG_SP_ANY
#define SIG_FLAG_SP_ANY
Definition: detect.h:240
SigGroupHeadStore
void SigGroupHeadStore(DetectEngineCtx *de_ctx, SigGroupHead *sgh)
Definition: detect-engine-siggroup.c:108
SigMatch_::type
uint16_t type
Definition: detect.h:350
SigGroupHeadInitData_::match_array
Signature ** match_array
Definition: detect.h:1461
Signature_::file_flags
uint8_t file_flags
Definition: detect.h:619
SigPrepareStage3
int SigPrepareStage3(DetectEngineCtx *de_ctx)
Definition: detect-engine-build.c:1920
DetectPort_::prev
struct DetectPort_ * prev
Definition: detect.h:230
SCLogPerf
#define SCLogPerf(...)
Definition: util-debug.h:230
DetectContentData_::content
uint8_t * content
Definition: detect-content.h:94
MASK_TCP_INITDEINIT_FLAGS
#define MASK_TCP_INITDEINIT_FLAGS
Definition: detect-engine-build.c:401
DetectListToString
const char * DetectListToString(int list)
Definition: detect-parse.c:179
DetectEngineCtx_::profile_match_logging_threshold
uint32_t profile_match_logging_threshold
Definition: detect.h:963
FatalError
#define FatalError(...)
Definition: util-debug.h:502
DetectEngineCtx_::sig_list
Signature * sig_list
Definition: detect.h:851
DetectMpmPreparePktMpms
int DetectMpmPreparePktMpms(DetectEngineCtx *de_ctx)
initialize mpm contexts for applayer buffers that are in "single or "shared" mode.
Definition: detect-engine-mpm.c:680
SigGroupHeadHashFree
void SigGroupHeadHashFree(DetectEngineCtx *de_ctx)
Frees the hash table - DetectEngineCtx->sgh_hash_table, allocated by SigGroupHeadHashInit() function.
Definition: detect-engine-siggroup.c:310
SIG_MASK_REQUIRE_FLAGS_UNUSUAL
#define SIG_MASK_REQUIRE_FLAGS_UNUSUAL
Definition: detect.h:304
TransformData_::transform
int transform
Definition: detect.h:404
DETECT_FLOWBITS
@ DETECT_FLOWBITS
Definition: detect-engine-register.h:62
app-layer-events.h
SigGroupHeadHashAdd
int SigGroupHeadHashAdd(DetectEngineCtx *de_ctx, SigGroupHead *sgh)
Adds a SigGroupHead to the detection engine context SigGroupHead hash table.
Definition: detect-engine-siggroup.c:277
util-validate.h
detect-flow.h
SCPortIntervalTree_
Definition: util-port-interval-tree.h:29
SigPrepareStage2
int SigPrepareStage2(DetectEngineCtx *de_ctx)
Fill the global src group head, with the sigs included.
Definition: detect-engine-build.c:1880
SCLogConfig
struct SCLogConfig_ SCLogConfig
Holds the config state used by the logging api.
SignatureInitData_::buffers
SignatureInitDataBuffer * buffers
Definition: detect.h:593
ConfigGetLogDirectory
const char * ConfigGetLogDirectory(void)
Definition: util-conf.c:38
HtpBodyChunk_::next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:178
SigGroupHeadHashLookup
SigGroupHead * SigGroupHeadHashLookup(DetectEngineCtx *de_ctx, SigGroupHead *sgh)
Used to lookup a SigGroupHead hash from the detection engine context SigGroupHead hash table.
Definition: detect-engine-siggroup.c:294
Signature_::dp
DetectPort * dp
Definition: detect.h:644
DETECT_STREAM_EVENT
@ DETECT_STREAM_EVENT
Definition: detect-engine-register.h:225
DETECT_TBLSIZE
int DETECT_TBLSIZE
Definition: detect-engine-register.c:281
DETECT_PGSCORE_RULE_PORT_PRIORITIZED
#define DETECT_PGSCORE_RULE_PORT_PRIORITIZED
Definition: detect-engine-build.c:49
g_skip_prefilter
int g_skip_prefilter
Definition: detect-engine-mpm.c:1072
SignatureIsFilestoring
int SignatureIsFilestoring(const Signature *s)
Check if a signature contains the filestore keyword.
Definition: detect-engine-build.c:100
SCFree
#define SCFree(p)
Definition: util-mem.h:61
SignatureIsIPOnly
int SignatureIsIPOnly(DetectEngineCtx *de_ctx, const Signature *s)
Test is a initialized signature is IP only.
Definition: detect-engine-build.c:209
SigTableElmt_::SupportsPrefilter
bool(* SupportsPrefilter)(const Signature *s)
Definition: detect.h:1296
DetectMpmPrepareBuiltinMpms
int DetectMpmPrepareBuiltinMpms(DetectEngineCtx *de_ctx)
initialize mpm contexts for builtin buffers that are in "single or "shared" mode.
Definition: detect-engine-mpm.c:739
Signature_::id
uint32_t id
Definition: detect.h:638
HashListTableBucket_
Definition: util-hashlist.h:28
detect-engine-iponly.h
SignatureInitData_::score
int score
Definition: detect.h:580
detect-parse.h
SignatureInitDataBuffer_::id
uint32_t id
Definition: detect.h:530
Signature_
Signature container.
Definition: detect.h:603
SigMatch_
a single match condition for a signature
Definition: detect.h:349
DETECT_SM_LIST_MAX
@ DETECT_SM_LIST_MAX
Definition: detect.h:132
SigGroupHeadInitDataFree
void SigGroupHeadInitDataFree(SigGroupHeadInitData *sghid)
Definition: detect-engine-siggroup.c:60
SignatureMask
#define SignatureMask
Definition: detect.h:311
SignatureIsFileMd5Inspecting
int SignatureIsFileMd5Inspecting(const Signature *s)
Check if a signature contains the filemd5 keyword.
Definition: detect-engine-build.c:138
DETECT_PGSCORE_RULE_MPM_NEGATED
#define DETECT_PGSCORE_RULE_MPM_NEGATED
Definition: detect-engine-build.c:51
DetectFlagsData_
Definition: detect-tcp-flags.h:37
ALPROTO_UNKNOWN
@ ALPROTO_UNKNOWN
Definition: app-layer-protos.h:29
SignatureSetType
void SignatureSetType(DetectEngineCtx *de_ctx, Signature *s)
Definition: detect-engine-build.c:1642
RANGE_PORT
#define RANGE_PORT
Definition: detect-engine-build.c:1312
SCProfilingKeywordInitCounters
void SCProfilingKeywordInitCounters(DetectEngineCtx *de_ctx)
Register the keyword profiling counters.
Definition: util-profiling-keywords.c:365
DetectEngineTransforms::cnt
int cnt
Definition: detect.h:410
DetectPortHashAdd
int DetectPortHashAdd(DetectEngineCtx *de_ctx, DetectPort *dp)
Adds a DetectPort to the detection engine context DetectPort hash table.
Definition: detect-engine-port.c:1390
DetectEngineCtx_::sig_array
Signature ** sig_array
Definition: detect.h:860
CONFIG_SCOPE_FLOW
@ CONFIG_SCOPE_FLOW
Definition: util-config.h:48
DetectContentData_::content_len
uint16_t content_len
Definition: detect-content.h:95
DetectEngineCtx_::buffer_type_id
uint32_t buffer_type_id
Definition: detect.h:995
PrefilterSetupRuleGroup
void PrefilterSetupRuleGroup(DetectEngineCtx *de_ctx, SigGroupHead *sgh)
Definition: detect-engine-prefilter.c:416
SigParseApplyDsizeToContent
void SigParseApplyDsizeToContent(Signature *s)
Apply dsize as depth to content matches in the rule.
Definition: detect-dsize.c:324
DetectEngineCtx_::flags
uint8_t flags
Definition: detect.h:845
UniquePortPoint
struct UniquePortPoint_ UniquePortPoint
SignatureInitData_::transforms
DetectEngineTransforms transforms
Definition: detect.h:575
DetectEngineCtx_::io_ctx
DetectEngineIPOnlyCtx io_ctx
Definition: detect.h:884
DetectU16Data
DetectUintData_u16 DetectU16Data
Definition: detect-engine-uint.h:42
DetectPortHashFree
void DetectPortHashFree(DetectEngineCtx *de_ctx)
Frees the hash table - DetectEngineCtx->sgh_hash_table, allocated by DetectPortInit() function.
Definition: detect-engine-port.c:1421
DetectPortHashLookup
DetectPort * DetectPortHashLookup(DetectEngineCtx *de_ctx, DetectPort *dp)
Used to lookup a DetectPort hash from the detection engine context DetectPort hash table.
Definition: detect-engine-port.c:1406
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
DetectEngineCtx_::sig_array_len
uint32_t sig_array_len
Definition: detect.h:861
detect-config.h
DETECT_FLAGS
@ DETECT_FLAGS
Definition: detect-engine-register.h:44
SCReturnInt
#define SCReturnInt(x)
Definition: util-debug.h:275
Signature_::type
enum SignatureType type
Definition: detect.h:606
SignatureIsFilemagicInspecting
int SignatureIsFilemagicInspecting(const Signature *s)
Check if a signature contains the filemagic keyword.
Definition: detect-engine-build.c:119
DetectEngineCtx_::signum
uint32_t signum
Definition: detect.h:863
DetectEngineCtx_::tenant_id
uint32_t tenant_id
Definition: detect.h:849
SigGroupHead_::filestore_cnt
uint16_t filestore_cnt
Definition: detect.h:1471
SignatureInitData_::buffer_index
uint32_t buffer_index
Definition: detect.h:594
DetectMpmPrepareAppMpms
int DetectMpmPrepareAppMpms(DetectEngineCtx *de_ctx)
initialize mpm contexts for applayer buffers that are in "single or "shared" mode.
Definition: detect-engine-mpm.c:286
SIGMATCH_IPONLY_COMPAT
#define SIGMATCH_IPONLY_COMPAT
Definition: detect.h:1495
DetectEngineLookupFlow_::tcp
DetectPort * tcp
Definition: detect.h:785
DetectPortCleanupList
void DetectPortCleanupList(const DetectEngineCtx *de_ctx, DetectPort *head)
Free a DetectPort list and each of its members.
Definition: detect-engine-port.c:124
SIG_TYPE_PDONLY
@ SIG_TYPE_PDONLY
Definition: detect.h:68
SCLogDebugEnabled
int SCLogDebugEnabled(void)
Returns whether debug messages are enabled to be logged or not.
Definition: util-debug.c:767
DEBUG_VALIDATE_BUG_ON
#define DEBUG_VALIDATE_BUG_ON(exp)
Definition: util-validate.h:102
DetectEngineAppInspectionEngine2Signature
int DetectEngineAppInspectionEngine2Signature(DetectEngineCtx *de_ctx, Signature *s)
Definition: detect-engine.c:729
SIG_FLAG_PREFILTER
#define SIG_FLAG_PREFILTER
Definition: detect.h:274
SCPortIntervalTreeFree
void SCPortIntervalTreeFree(DetectEngineCtx *de_ctx, SCPortIntervalTree *it)
Function to free an entire interval tree.
Definition: util-port-interval-tree.c:92
TCPHdr_
Definition: decode-tcp.h:149
detect-engine-address.h
SigGroupHead_::id
uint32_t id
Definition: detect.h:1473
VarNameStoreActivate
int VarNameStoreActivate(void)
Definition: util-var-name.c:214
SIG_FLAG_FILESTORE
#define SIG_FLAG_FILESTORE
Definition: detect.h:265
DETECT_UINT_RA
#define DETECT_UINT_RA
Definition: detect-engine-uint.h:34
FILE_SIG_NEED_SIZE
#define FILE_SIG_NEED_SIZE
Definition: detect.h:320
SIG_FLAG_DP_ANY
#define SIG_FLAG_DP_ANY
Definition: detect.h:241
DETECT_FLOWBITS_CMD_SET
#define DETECT_FLOWBITS_CMD_SET
Definition: detect-flowbits.h:28
detect-engine-threshold.h
SigGroupHeadCopySigs
int SigGroupHeadCopySigs(DetectEngineCtx *de_ctx, SigGroupHead *src, SigGroupHead **dst)
Copies the bitarray holding the sids from the source SigGroupHead to the destination SigGroupHead.
Definition: detect-engine-siggroup.c:401
Signature_::mask
SignatureMask mask
Definition: detect.h:614
SIG_TYPE_LIKE_IPONLY
@ SIG_TYPE_LIKE_IPONLY
Definition: detect.h:65
PacketEngineEvents_::cnt
uint8_t cnt
Definition: decode.h:286
SIG_FLAG_REQUIRE_PACKET
#define SIG_FLAG_REQUIRE_PACKET
Definition: detect.h:250