suricata
detect-engine-analyzer.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2018 Open Information Security Foundation
2  *
3  * You can copy, redistribute or modify this Program under the terms of
4  * the GNU General Public License version 2 as published by the Free
5  * Software Foundation.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * version 2 along with this program; if not, write to the Free Software
14  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
15  * 02110-1301, USA.
16  */
17 
18 /**
19  * \file
20  *
21  * \author Eileen Donlon <emdonlo@gmail.com>
22  * \author Victor Julien <victor@inliniac.net>
23  *
24  * Rule analyzers for the detection engine
25  */
26 
27 #include "suricata-common.h"
28 #include "suricata.h"
29 #include "detect.h"
30 #include "detect-parse.h"
31 #include "detect-engine.h"
32 #include "detect-engine-analyzer.h"
33 #include "detect-engine-mpm.h"
34 #include "conf.h"
35 #include "detect-content.h"
36 #include "detect-flow.h"
37 #include "detect-flags.h"
38 #include "util-print.h"
39 
40 static int rule_warnings_only = 0;
41 static FILE *rule_engine_analysis_FD = NULL;
42 static FILE *fp_engine_analysis_FD = NULL;
43 static pcre *percent_re = NULL;
44 static pcre_extra *percent_re_study = NULL;
45 static char log_path[PATH_MAX];
46 
47 typedef struct FpPatternStats_ {
48  uint16_t min;
49  uint16_t max;
50  uint32_t cnt;
51  uint64_t tot;
53 
54 static FpPatternStats fp_pattern_stats[DETECT_SM_LIST_MAX];
55 
56 static void FpPatternStatsAdd(int list, uint16_t patlen)
57 {
58  if (list < 0 || list >= DETECT_SM_LIST_MAX)
59  return;
60 
61  FpPatternStats *f = &fp_pattern_stats[list];
62 
63  if (f->min == 0)
64  f->min = patlen;
65  else if (patlen < f->min)
66  f->min = patlen;
67 
68  if (patlen > f->max)
69  f->max = patlen;
70 
71  f->cnt++;
72  f->tot += patlen;
73 }
74 
75 void EngineAnalysisFP(const DetectEngineCtx *de_ctx, const Signature *s, char *line)
76 {
77  int fast_pattern_set = 0;
78  int fast_pattern_only_set = 0;
79  int fast_pattern_chop_set = 0;
80  DetectContentData *fp_cd = NULL;
81  SigMatch *mpm_sm = s->init_data->mpm_sm;
82 
83  if (mpm_sm != NULL) {
84  fp_cd = (DetectContentData *)mpm_sm->ctx;
85  if (fp_cd->flags & DETECT_CONTENT_FAST_PATTERN) {
86  fast_pattern_set = 1;
88  fast_pattern_only_set = 1;
89  } else if (fp_cd->flags & DETECT_CONTENT_FAST_PATTERN_CHOP) {
90  fast_pattern_chop_set = 1;
91  }
92  }
93  }
94 
95  fprintf(fp_engine_analysis_FD, "== Sid: %u ==\n", s->id);
96  fprintf(fp_engine_analysis_FD, "%s\n", line);
97 
98  fprintf(fp_engine_analysis_FD, " Fast Pattern analysis:\n");
99  if (s->init_data->prefilter_sm != NULL) {
100  fprintf(fp_engine_analysis_FD, " Prefilter on: %s\n",
102  fprintf(fp_engine_analysis_FD, "\n");
103  return;
104  }
105 
106  if (fp_cd == NULL) {
107  fprintf(fp_engine_analysis_FD, " No content present\n");
108  fprintf(fp_engine_analysis_FD, "\n");
109  return;
110  }
111 
112  fprintf(fp_engine_analysis_FD, " Fast pattern matcher: ");
113  int list_type = SigMatchListSMBelongsTo(s, mpm_sm);
114  if (list_type == DETECT_SM_LIST_PMATCH)
115  fprintf(fp_engine_analysis_FD, "content\n");
116  else {
117  const char *desc = DetectBufferTypeGetDescriptionById(de_ctx, list_type);
118  const char *name = DetectBufferTypeGetNameById(de_ctx, list_type);
119  if (desc && name) {
120  fprintf(fp_engine_analysis_FD, "%s (%s)\n", desc, name);
121  }
122  }
123 
124  int flags_set = 0;
125  fprintf(fp_engine_analysis_FD, " Flags:");
126  if (fp_cd->flags & DETECT_CONTENT_OFFSET) {
127  fprintf(fp_engine_analysis_FD, " Offset");
128  flags_set = 1;
129  } if (fp_cd->flags & DETECT_CONTENT_DEPTH) {
130  fprintf(fp_engine_analysis_FD, " Depth");
131  flags_set = 1;
132  }
133  if (fp_cd->flags & DETECT_CONTENT_WITHIN) {
134  fprintf(fp_engine_analysis_FD, " Within");
135  flags_set = 1;
136  }
137  if (fp_cd->flags & DETECT_CONTENT_DISTANCE) {
138  fprintf(fp_engine_analysis_FD, " Distance");
139  flags_set = 1;
140  }
141  if (fp_cd->flags & DETECT_CONTENT_NOCASE) {
142  fprintf(fp_engine_analysis_FD, " Nocase");
143  flags_set = 1;
144  }
145  if (fp_cd->flags & DETECT_CONTENT_NEGATED) {
146  fprintf(fp_engine_analysis_FD, " Negated");
147  flags_set = 1;
148  }
149  if (flags_set == 0)
150  fprintf(fp_engine_analysis_FD, " None");
151  fprintf(fp_engine_analysis_FD, "\n");
152 
153  fprintf(fp_engine_analysis_FD, " Fast pattern set: %s\n", fast_pattern_set ? "yes" : "no");
154  fprintf(fp_engine_analysis_FD, " Fast pattern only set: %s\n",
155  fast_pattern_only_set ? "yes" : "no");
156  fprintf(fp_engine_analysis_FD, " Fast pattern chop set: %s\n",
157  fast_pattern_chop_set ? "yes" : "no");
158  if (fast_pattern_chop_set) {
159  fprintf(fp_engine_analysis_FD, " Fast pattern offset, length: %u, %u\n",
160  fp_cd->fp_chop_offset, fp_cd->fp_chop_len);
161  }
162 
163  uint16_t patlen = fp_cd->content_len;
164  uint8_t *pat = SCMalloc(fp_cd->content_len + 1);
165  if (unlikely(pat == NULL)) {
166  SCLogError(SC_ERR_MEM_ALLOC, "Error allocating memory");
167  exit(EXIT_FAILURE);
168  }
169  memcpy(pat, fp_cd->content, fp_cd->content_len);
170  pat[fp_cd->content_len] = '\0';
171  fprintf(fp_engine_analysis_FD, " Original content: ");
172  PrintRawUriFp(fp_engine_analysis_FD, pat, patlen);
173  fprintf(fp_engine_analysis_FD, "\n");
174 
175  if (fast_pattern_chop_set) {
176  SCFree(pat);
177  patlen = fp_cd->fp_chop_len;
178  pat = SCMalloc(fp_cd->fp_chop_len + 1);
179  if (unlikely(pat == NULL)) {
180  exit(EXIT_FAILURE);
181  }
182  memcpy(pat, fp_cd->content + fp_cd->fp_chop_offset, fp_cd->fp_chop_len);
183  pat[fp_cd->fp_chop_len] = '\0';
184  fprintf(fp_engine_analysis_FD, " Final content: ");
185  PrintRawUriFp(fp_engine_analysis_FD, pat, patlen);
186  fprintf(fp_engine_analysis_FD, "\n");
187 
188  FpPatternStatsAdd(list_type, patlen);
189  } else {
190  fprintf(fp_engine_analysis_FD, " Final content: ");
191  PrintRawUriFp(fp_engine_analysis_FD, pat, patlen);
192  fprintf(fp_engine_analysis_FD, "\n");
193 
194  FpPatternStatsAdd(list_type, patlen);
195  }
196  SCFree(pat);
197 
198  fprintf(fp_engine_analysis_FD, "\n");
199  return;
200 }
201 
202 /**
203  * \brief Sets up the fast pattern analyzer according to the config.
204  *
205  * \retval 1 If rule analyzer successfully enabled.
206  * \retval 0 If not enabled.
207  */
209 {
210  int fp_engine_analysis_set = 0;
211 
212  if ((ConfGetBool("engine-analysis.rules-fast-pattern",
213  &fp_engine_analysis_set)) == 0) {
214  return 0;
215  }
216 
217  if (fp_engine_analysis_set == 0)
218  return 0;
219 
220  const char *log_dir;
221  log_dir = ConfigGetLogDirectory();
222  snprintf(log_path, sizeof(log_path), "%s/%s", log_dir,
223  "rules_fast_pattern.txt");
224 
225  fp_engine_analysis_FD = fopen(log_path, "w");
226  if (fp_engine_analysis_FD == NULL) {
227  SCLogError(SC_ERR_FOPEN, "failed to open %s: %s", log_path,
228  strerror(errno));
229  return 0;
230  }
231 
232  SCLogInfo("Engine-Analysis for fast_pattern printed to file - %s",
233  log_path);
234 
235  struct timeval tval;
236  struct tm *tms;
237  gettimeofday(&tval, NULL);
238  struct tm local_tm;
239  tms = SCLocalTime(tval.tv_sec, &local_tm);
240  fprintf(fp_engine_analysis_FD, "----------------------------------------------"
241  "---------------------\n");
242  fprintf(fp_engine_analysis_FD, "Date: %" PRId32 "/%" PRId32 "/%04d -- "
243  "%02d:%02d:%02d\n",
244  tms->tm_mday, tms->tm_mon + 1, tms->tm_year + 1900, tms->tm_hour,
245  tms->tm_min, tms->tm_sec);
246  fprintf(fp_engine_analysis_FD, "----------------------------------------------"
247  "---------------------\n");
248 
249  memset(&fp_pattern_stats, 0, sizeof(fp_pattern_stats));
250  return 1;
251 }
252 
253 /**
254  * \brief Sets up the rule analyzer according to the config
255  * \retval 1 if rule analyzer successfully enabled
256  * \retval 0 if not enabled
257  */
259 {
260  ConfNode *conf = ConfGetNode("engine-analysis");
261  int enabled = 0;
262  if (conf != NULL) {
263  const char *value = ConfNodeLookupChildValue(conf, "rules");
264  if (value && ConfValIsTrue(value)) {
265  enabled = 1;
266  } else if (value && strcasecmp(value, "warnings-only") == 0) {
267  enabled = 1;
268  rule_warnings_only = 1;
269  }
270  if (enabled) {
271  const char *log_dir;
272  log_dir = ConfigGetLogDirectory();
273  snprintf(log_path, sizeof(log_path), "%s/%s", log_dir, "rules_analysis.txt");
274  rule_engine_analysis_FD = fopen(log_path, "w");
275  if (rule_engine_analysis_FD == NULL) {
276  SCLogError(SC_ERR_FOPEN, "failed to open %s: %s", log_path, strerror(errno));
277  return 0;
278  }
279 
280  SCLogInfo("Engine-Analysis for rules printed to file - %s",
281  log_path);
282 
283  struct timeval tval;
284  struct tm *tms;
285  gettimeofday(&tval, NULL);
286  struct tm local_tm;
287  tms = SCLocalTime(tval.tv_sec, &local_tm);
288  fprintf(rule_engine_analysis_FD, "----------------------------------------------"
289  "---------------------\n");
290  fprintf(rule_engine_analysis_FD, "Date: %" PRId32 "/%" PRId32 "/%04d -- "
291  "%02d:%02d:%02d\n",
292  tms->tm_mday, tms->tm_mon + 1, tms->tm_year + 1900, tms->tm_hour,
293  tms->tm_min, tms->tm_sec);
294  fprintf(rule_engine_analysis_FD, "----------------------------------------------"
295  "---------------------\n");
296 
297  /*compile regex's for rule analysis*/
298  if (PerCentEncodingSetup()== 0) {
299  fprintf(rule_engine_analysis_FD, "Error compiling regex; can't check for percent encoding in normalized http content.\n");
300  }
301  }
302  }
303  else {
304  SCLogInfo("Conf parameter \"engine-analysis.rules\" not found. "
305  "Defaulting to not printing the rules analysis report.");
306  }
307  if (!enabled) {
308  SCLogInfo("Engine-Analysis for rules disabled in conf file.");
309  return 0;
310  }
311  return 1;
312 }
313 
315 {
316  fprintf(fp_engine_analysis_FD, "============\n"
317  "Summary:\n============\n");
318  int i;
319  for (i = 0; i < DETECT_SM_LIST_MAX; i++) {
320  FpPatternStats *f = &fp_pattern_stats[i];
321  if (f->cnt == 0)
322  continue;
323 
324  fprintf(fp_engine_analysis_FD,
325  "%s, smallest pattern %u byte(s), longest pattern %u byte(s), number of patterns %u, avg pattern len %.2f byte(s)\n",
326  DetectSigmatchListEnumToString(i), f->min, f->max, f->cnt, (float)((double)f->tot/(float)f->cnt));
327  }
328 
329  if (fp_engine_analysis_FD != NULL) {
330  fclose(fp_engine_analysis_FD);
331  fp_engine_analysis_FD = NULL;
332  }
333 
334  return;
335 }
336 
337 
339 {
340  if (rule_engine_analysis_FD != NULL) {
341  SCLogInfo("Engine-Analyis for rules printed to file - %s", log_path);
342  fclose(rule_engine_analysis_FD);
343  rule_engine_analysis_FD = NULL;
344  }
345 }
346 
347 /**
348  * \brief Compiles regex for rule analysis
349  * \retval 1 if successful
350  * \retval 0 if on error
351  */
353 {
354 #define DETECT_PERCENT_ENCODING_REGEX "%[0-9|a-f|A-F]{2}"
355  const char *eb = NULL;
356  int eo = 0;
357  int opts = 0; //PCRE_NEWLINE_ANY??
358 
359  percent_re = pcre_compile(DETECT_PERCENT_ENCODING_REGEX, opts, &eb, &eo, NULL);
360  if (percent_re == NULL) {
361  SCLogError(SC_ERR_PCRE_COMPILE, "Compile of \"%s\" failed at offset %" PRId32 ": %s",
363  return 0;
364  }
365 
366  percent_re_study = pcre_study(percent_re, 0, &eb);
367  if (eb != NULL) {
368  SCLogError(SC_ERR_PCRE_STUDY, "pcre study failed: %s", eb);
369  return 0;
370  }
371  return 1;
372 }
373 
374 /**
375  * \brief Checks for % encoding in content.
376  * \param Pointer to content
377  * \retval number of matches if content has % encoding
378  * \retval 0 if it doesn't have % encoding
379  * \retval -1 on error
380  */
381 int PerCentEncodingMatch (uint8_t *content, uint8_t content_len)
382 {
383 #define MAX_ENCODED_CHARS 240
384  int ret = 0;
385  int ov[MAX_ENCODED_CHARS];
386 
387  ret = pcre_exec(percent_re, percent_re_study, (char *)content, content_len, 0, 0, ov, MAX_ENCODED_CHARS);
388  if (ret == -1) {
389  return 0;
390  }
391  else if (ret < -1) {
392  SCLogError(SC_ERR_PCRE_MATCH, "Error parsing content - %s; error code is %d", content, ret);
393  return -1;
394  }
395  return ret;
396 }
397 
398 static void EngineAnalysisRulesPrintFP(const DetectEngineCtx *de_ctx, const Signature *s)
399 {
400  DetectContentData *fp_cd = NULL;
401  SigMatch *mpm_sm = s->init_data->mpm_sm;
402 
403  if (mpm_sm != NULL) {
404  fp_cd = (DetectContentData *)mpm_sm->ctx;
405  }
406 
407  if (fp_cd == NULL) {
408  return;
409  }
410 
411  uint16_t patlen = fp_cd->content_len;
412  uint8_t *pat = SCMalloc(fp_cd->content_len + 1);
413  if (unlikely(pat == NULL)) {
414  SCLogError(SC_ERR_MEM_ALLOC, "Error allocating memory");
415  exit(EXIT_FAILURE);
416  }
417  memcpy(pat, fp_cd->content, fp_cd->content_len);
418  pat[fp_cd->content_len] = '\0';
419 
421  SCFree(pat);
422  patlen = fp_cd->fp_chop_len;
423  pat = SCMalloc(fp_cd->fp_chop_len + 1);
424  if (unlikely(pat == NULL)) {
425  exit(EXIT_FAILURE);
426  }
427  memcpy(pat, fp_cd->content + fp_cd->fp_chop_offset, fp_cd->fp_chop_len);
428  pat[fp_cd->fp_chop_len] = '\0';
429  fprintf(rule_engine_analysis_FD, " Fast Pattern \"");
430  PrintRawUriFp(rule_engine_analysis_FD, pat, patlen);
431  } else {
432  fprintf(rule_engine_analysis_FD, " Fast Pattern \"");
433  PrintRawUriFp(rule_engine_analysis_FD, pat, patlen);
434  }
435  SCFree(pat);
436 
437  fprintf(rule_engine_analysis_FD, "\" on \"");
438 
439  int list_type = SigMatchListSMBelongsTo(s, mpm_sm);
440  if (list_type == DETECT_SM_LIST_PMATCH) {
441  int payload = 0;
442  int stream = 0;
444  payload = 1;
446  stream = 1;
447  fprintf(rule_engine_analysis_FD, "%s",
448  payload ? (stream ? "payload and reassembled stream" : "payload") : "reassembled stream");
449  }
450  else {
451  const char *desc = DetectBufferTypeGetDescriptionById(de_ctx, list_type);
452  const char *name = DetectBufferTypeGetNameById(de_ctx, list_type);
453  if (desc && name) {
454  fprintf(rule_engine_analysis_FD, "%s (%s)", desc, name);
455  }
456  }
457 
458  fprintf(rule_engine_analysis_FD, "\" buffer.\n");
459 
460  return;
461 }
462 
463 
464 void EngineAnalysisRulesFailure(char *line, char *file, int lineno)
465 {
466  fprintf(rule_engine_analysis_FD, "== Sid: UNKNOWN ==\n");
467  fprintf(rule_engine_analysis_FD, "%s\n", line);
468  fprintf(rule_engine_analysis_FD, " FAILURE: invalid rule.\n");
469  fprintf(rule_engine_analysis_FD, " File: %s.\n", file);
470  fprintf(rule_engine_analysis_FD, " Line: %d.\n", lineno);
471  fprintf(rule_engine_analysis_FD, "\n");
472 }
473 
474 #ifdef HAVE_LIBJANSSON
475 #include "util-buffer.h"
476 #include "output-json.h"
477 
478 typedef struct RuleAnalyzer {
479  json_t *js; /* document root */
480 
481  json_t *js_warnings;
482  json_t *js_notes;
483 } RuleAnalyzer;
484 
485 static void __attribute__ ((format (printf, 2, 3)))
486 AnalyzerNote(RuleAnalyzer *ctx, char *fmt, ...)
487 {
488  va_list ap;
489  char str[1024];
490 
491  va_start(ap, fmt);
492  vsnprintf(str, sizeof(str), fmt, ap);
493  va_end(ap);
494 
495  if (!ctx->js_notes)
496  ctx->js_notes = json_array();
497  if (ctx->js_notes)
498  json_array_append_new(ctx->js_notes, json_string(str));
499 }
500 
501 static void __attribute__ ((format (printf, 2, 3)))
502 AnalyzerWarning(RuleAnalyzer *ctx, char *fmt, ...)
503 {
504  va_list ap;
505  char str[1024];
506 
507  va_start(ap, fmt);
508  vsnprintf(str, sizeof(str), fmt, ap);
509  va_end(ap);
510 
511  if (!ctx->js_warnings)
512  ctx->js_warnings = json_array();
513  if (ctx->js_warnings)
514  json_array_append_new(ctx->js_warnings, json_string(str));
515 }
516 
517 #define CHECK(pat) if (strlen((pat)) <= len && memcmp((pat), buf, MIN(len, strlen((pat)))) == 0) return true;
518 
519 static bool LooksLikeHTTPMethod(const uint8_t *buf, uint16_t len)
520 {
521  CHECK("GET /");
522  CHECK("POST /");
523  CHECK("HEAD /");
524  CHECK("PUT /");
525  return false;
526 }
527 
528 static bool LooksLikeHTTPUA(const uint8_t *buf, uint16_t len)
529 {
530  CHECK("User-Agent: ");
531  CHECK("\nUser-Agent: ");
532  return false;
533 }
534 
535 static void DumpMatches(RuleAnalyzer *ctx, json_t *js, const SigMatchData *smd)
536 {
537  json_t *js_matches = json_array();
538  if (js_matches == NULL) {
539  return;
540  }
541  do {
542  json_t *js_match = json_object();
543  if (js_match != NULL) {
544  const char *mname = sigmatch_table[smd->type].name;
545  json_object_set_new(js_match, "name", json_string(mname));
546 
547  switch (smd->type) {
548  case DETECT_CONTENT: {
549  const DetectContentData *cd = (const DetectContentData *)smd->ctx;
550  uint8_t *pat = SCMalloc(cd->content_len + 1);
551  if (unlikely(pat == NULL)) {
552  SCLogError(SC_ERR_MEM_ALLOC, "Error allocating memory");
553  exit(EXIT_FAILURE);
554  }
555  memcpy(pat, cd->content, cd->content_len);
556  pat[cd->content_len] = '\0';
557 
558  json_t *js_match_content = json_object();
559  if (js_match_content != NULL) {
560  json_object_set_new(js_match_content, "pattern", SCJsonString((const char *)pat));
561  json_object_set_new(js_match_content, "nocase", json_boolean(cd->flags & DETECT_CONTENT_NOCASE));
562  json_object_set_new(js_match_content, "negated", json_boolean(cd->flags & DETECT_CONTENT_NEGATED));
563  json_object_set_new(js_match_content, "starts_with", json_boolean(cd->flags & DETECT_CONTENT_STARTS_WITH));
564  json_object_set_new(js_match_content, "ends_with", json_boolean(cd->flags & DETECT_CONTENT_ENDS_WITH));
565  json_object_set_new(js_match_content, "is_mpm", json_boolean(cd->flags & DETECT_CONTENT_MPM));
566  if (cd->flags & DETECT_CONTENT_OFFSET) {
567  json_object_set_new(js_match_content, "offset", json_integer(cd->offset));
568  }
569  if (cd->flags & DETECT_CONTENT_DEPTH) {
570  json_object_set_new(js_match_content, "depth", json_integer(cd->depth));
571  }
572  if (cd->flags & DETECT_CONTENT_DISTANCE) {
573  json_object_set_new(js_match_content, "distance", json_integer(cd->distance));
574  }
575  if (cd->flags & DETECT_CONTENT_WITHIN) {
576  json_object_set_new(js_match_content, "within", json_integer(cd->within));
577  }
578 
579  json_object_set_new(js_match_content, "fast_pattern", json_boolean(cd->flags & DETECT_CONTENT_FAST_PATTERN));
581  AnalyzerNote(ctx, (char *)"'fast_pattern:only' option is silently ignored and is intepreted as regular 'fast_pattern'");
582  }
583 
584  json_object_set_new(js_match, "content", js_match_content);
585  }
586 
587  if (LooksLikeHTTPMethod(cd->content, cd->content_len)) {
588  AnalyzerWarning(ctx, (char *)"pattern looks like it inspects HTTP, use http_request_line or http_method and http_uri instead for improved performance");
589  }
590  if (LooksLikeHTTPUA(cd->content, cd->content_len)) {
591  AnalyzerWarning(ctx, (char *)"pattern looks like it inspects HTTP, use http_user_agent or http_header for improved performance");
592  }
593 
594  SCFree(pat);
595  break;
596  }
597  }
598  }
599  json_array_append_new(js_matches, js_match);
600 
601  if (smd->is_last)
602  break;
603  smd++;
604  } while (1);
605  json_object_set_new(js, "matches", js_matches);
606 }
607 
608 SCMutex g_rules_analyzer_write_m = SCMUTEX_INITIALIZER;
609 void EngineAnalysisRules2(const DetectEngineCtx *de_ctx, const Signature *s)
610 {
611  SCEnter();
612 
613  RuleAnalyzer ctx = { NULL, NULL, NULL };
614 
615  ctx.js = json_object();
616  if (ctx.js == NULL)
617  SCReturn;
618 
619  json_object_set_new(ctx.js, "raw", json_string(s->sig_str));
620  json_object_set_new(ctx.js, "id", json_integer(s->id));
621  json_object_set_new(ctx.js, "gid", json_integer(s->gid));
622  json_object_set_new(ctx.js, "rev", json_integer(s->rev));
623  json_object_set_new(ctx.js, "msg", json_string(s->msg));
624 
625  const char *alproto = AppProtoToString(s->alproto);
626  json_object_set_new(ctx.js, "app_proto", json_string(alproto));
627 
628  json_t *js_flags = json_array();
629  if (js_flags != NULL) {
630  if (s->mask & SIG_MASK_REQUIRE_PAYLOAD) {
631  json_array_append_new(js_flags, json_string("payload"));
632  }
634  json_array_append_new(js_flags, json_string("no_payload"));
635  }
636  if (s->mask & SIG_MASK_REQUIRE_FLOW) {
637  json_array_append_new(js_flags, json_string("flow"));
638  }
640  json_array_append_new(js_flags, json_string("tcp_flags_init_deinit"));
641  }
643  json_array_append_new(js_flags, json_string("tcp_flags_unusual"));
644  }
645  if (s->mask & SIG_MASK_REQUIRE_DCERPC) {
646  json_array_append_new(js_flags, json_string("dcerpc"));
647  }
649  json_array_append_new(js_flags, json_string("engine_event"));
650  }
651  json_object_set_new(ctx.js, "requirements", js_flags);
652  }
653 
654  js_flags = json_array();
655  if (js_flags != NULL) {
656  if (s->flags & SIG_FLAG_SRC_ANY) {
657  json_array_append_new(js_flags, json_string("src_any"));
658  }
659  if (s->flags & SIG_FLAG_DST_ANY) {
660  json_array_append_new(js_flags, json_string("dst_any"));
661  }
662  if (s->flags & SIG_FLAG_SP_ANY) {
663  json_array_append_new(js_flags, json_string("sp_any"));
664  }
665  if (s->flags & SIG_FLAG_DP_ANY) {
666  json_array_append_new(js_flags, json_string("dp_any"));
667  }
668  if (s->flags & SIG_FLAG_NOALERT) {
669  json_array_append_new(js_flags, json_string("noalert"));
670  }
671  if (s->flags & SIG_FLAG_DSIZE) {
672  json_array_append_new(js_flags, json_string("dsize"));
673  }
674  if (s->flags & SIG_FLAG_APPLAYER) {
675  json_array_append_new(js_flags, json_string("applayer"));
676  }
677  if (s->flags & SIG_FLAG_IPONLY) {
678  json_array_append_new(js_flags, json_string("ip_only"));
679  }
680  if (s->flags & SIG_FLAG_REQUIRE_PACKET) {
681  json_array_append_new(js_flags, json_string("need_packet"));
682  }
683  if (s->flags & SIG_FLAG_REQUIRE_STREAM) {
684  json_array_append_new(js_flags, json_string("need_stream"));
685  }
686  if (s->flags & SIG_FLAG_MPM_NEG) {
687  json_array_append_new(js_flags, json_string("negated_mpm"));
688  }
689  if (s->flags & SIG_FLAG_FLUSH) {
690  json_array_append_new(js_flags, json_string("flush"));
691  }
692  if (s->flags & SIG_FLAG_REQUIRE_FLOWVAR) {
693  json_array_append_new(js_flags, json_string("need_flowvar"));
694  }
695  if (s->flags & SIG_FLAG_FILESTORE) {
696  json_array_append_new(js_flags, json_string("filestore"));
697  }
698  if (s->flags & SIG_FLAG_TOSERVER) {
699  json_array_append_new(js_flags, json_string("toserver"));
700  }
701  if (s->flags & SIG_FLAG_TOCLIENT) {
702  json_array_append_new(js_flags, json_string("toclient"));
703  }
704  if (s->flags & SIG_FLAG_TLSSTORE) {
705  json_array_append_new(js_flags, json_string("tlsstore"));
706  }
707  if (s->flags & SIG_FLAG_BYPASS) {
708  json_array_append_new(js_flags, json_string("bypass"));
709  }
710  if (s->flags & SIG_FLAG_PREFILTER) {
711  json_array_append_new(js_flags, json_string("prefilter"));
712  }
713  if (s->flags & SIG_FLAG_PDONLY) {
714  json_array_append_new(js_flags, json_string("proto_detect_only"));
715  }
716  if (s->flags & SIG_FLAG_SRC_IS_TARGET) {
717  json_array_append_new(js_flags, json_string("src_is_target"));
718  }
719  if (s->flags & SIG_FLAG_DEST_IS_TARGET) {
720  json_array_append_new(js_flags, json_string("dst_is_target"));
721  }
722  json_object_set_new(ctx.js, "flags", js_flags);
723  }
724 
726  bool has_stream = false;
727  bool has_client_body_mpm = false;
728  bool has_file_data_mpm = false;
729 
730  json_t *js_array = json_array();
732  for ( ; app != NULL; app = app->next) {
733  const char *name = DetectBufferTypeGetNameById(de_ctx, app->sm_list);
734  if (name == NULL) {
735  switch (app->sm_list) {
737  name = "stream";
738  break;
739  default:
740  name = "unknown";
741  break;
742  }
743  }
744 
745  if (app->sm_list == DETECT_SM_LIST_PMATCH && !app->mpm) {
746  has_stream = true;
747  } else if (app->mpm && strcmp(name, "http_client_body") == 0) {
748  has_client_body_mpm = true;
749  } else if (app->mpm && strcmp(name, "file_data") == 0) {
750  has_file_data_mpm = true;
751  }
752 
753  json_t *js_engine = json_object();
754  if (js_engine != NULL) {
755  json_object_set_new(js_engine, "name", json_string(name));
756 
757  const char *direction = app->dir == 0 ? "toserver" : "toclient";
758  json_object_set_new(js_engine, "direction", json_string(direction));
759  json_object_set_new(js_engine, "is_mpm", json_boolean(app->mpm));
760  json_object_set_new(js_engine, "app_proto", json_string(AppProtoToString(app->alproto)));
761  json_object_set_new(js_engine, "progress", json_integer(app->progress));
762 
763  DumpMatches(&ctx, js_engine, app->smd);
764 
765  json_array_append_new(js_array, js_engine);
766  }
767  }
768  json_object_set_new(ctx.js, "engines", js_array);
769 
770  if (has_stream && has_client_body_mpm)
771  AnalyzerNote(&ctx, (char *)"mpm in http_client_body combined with stream match leads to stream buffering");
772  if (has_stream && has_file_data_mpm)
773  AnalyzerNote(&ctx, (char *)"mpm in file_data combined with stream match leads to stream buffering");
774  }
775 
776  json_t *js_lists = json_object();
777  for (int i = 0; i < DETECT_SM_LIST_MAX; i++) {
778  if (s->sm_arrays[i] != NULL) {
779  json_t *js_list = json_object();
780  if (js_list != NULL) {
781  DumpMatches(&ctx, js_list, s->sm_arrays[i]);
782  json_object_set_new(js_lists, DetectSigmatchListEnumToString(i), js_list);
783  }
784  }
785  }
786  json_object_set_new(ctx.js, "lists", js_lists);
787 
788  if (ctx.js_warnings) {
789  json_object_set_new(ctx.js, "warnings", ctx.js_warnings);
790  }
791  if (ctx.js_notes) {
792  json_object_set_new(ctx.js, "notes", ctx.js_notes);
793  }
794 
795  const char *filename = "rules.json";
796  const char *log_dir = ConfigGetLogDirectory();
797  char json_path[PATH_MAX] = "";
798  snprintf(json_path, sizeof(json_path), "%s/%s", log_dir, filename);
799 
800  MemBuffer *mbuf = MemBufferCreateNew(4096);
801  if (mbuf != NULL) {
802  OutputJSONMemBufferWrapper wrapper = {
803  .buffer = &mbuf,
804  .expand_by = 4096,
805  };
806 
807  int r = json_dump_callback(ctx.js, OutputJSONMemBufferCallback, &wrapper,
808  JSON_PRESERVE_ORDER|JSON_COMPACT|JSON_ENSURE_ASCII|
809  JSON_ESCAPE_SLASH);
810  if (r != 0) {
811  SCLogWarning(SC_ERR_SOCKET, "unable to serialize JSON object");
812  } else {
813  MemBufferWriteString(mbuf, "\n");
814  SCMutexLock(&g_rules_analyzer_write_m);
815  FILE *fp = fopen(json_path, "a");
816  if (fp != NULL) {
817  MemBufferPrintToFPAsString(mbuf, fp);
818  fclose(fp);
819  }
820  SCMutexUnlock(&g_rules_analyzer_write_m);
821  }
822 
823  MemBufferFree(mbuf);
824  }
825  json_object_clear(ctx.js);
826  json_decref(ctx.js);
827  SCReturn;
828 }
829 #endif /* HAVE_LIBJANSSON */
830 
831 /**
832  * \brief Prints analysis of loaded rules.
833  *
834  * Warns if potential rule issues are detected. For example,
835  * warns if a rule uses a construct that may perform poorly,
836  * e.g. pcre without content or with http_method content only;
837  * warns if a rule uses a construct that may not be consistent with intent,
838  * e.g. client side ports only, http and content without any http_* modifiers, etc.
839  *
840  * \param s Pointer to the signature.
841  */
843  const Signature *s, const char *line)
844 {
845  uint32_t rule_bidirectional = 0;
846  uint32_t rule_pcre = 0;
847  uint32_t rule_pcre_http = 0;
848  uint32_t rule_content = 0;
849  uint32_t rule_flow = 0;
850  uint32_t rule_flags = 0;
851  uint32_t rule_flow_toserver = 0;
852  uint32_t rule_flow_toclient = 0;
853  uint32_t rule_flow_nostream = 0;
854  uint32_t rule_ipv4_only = 0;
855  uint32_t rule_ipv6_only = 0;
856  uint32_t rule_flowbits = 0;
857  uint32_t rule_flowint = 0;
858  //uint32_t rule_flowvar = 0;
859  uint32_t rule_content_http = 0;
860  uint32_t rule_content_offset_depth = 0;
861  int32_t list_id = 0;
862  uint32_t rule_warning = 0;
863  uint32_t raw_http_buf = 0;
864  uint32_t norm_http_buf = 0;
865  uint32_t stream_buf = 0;
866  uint32_t packet_buf = 0;
867  uint32_t http_header_buf = 0;
868  uint32_t http_uri_buf = 0;
869  uint32_t http_method_buf = 0;
870  uint32_t http_cookie_buf = 0;
871  uint32_t http_client_body_buf = 0;
872  uint32_t http_server_body_buf = 0;
873  uint32_t http_stat_code_buf = 0;
874  uint32_t http_stat_msg_buf = 0;
875  uint32_t http_raw_header_buf = 0;
876  uint32_t http_raw_uri_buf = 0;
877  uint32_t http_ua_buf = 0;
878  uint32_t http_host_buf = 0;
879  uint32_t http_rawhost_buf = 0;
880  uint32_t http_headernames_buf = 0;
881  uint32_t http_referer_buf = 0;
882  uint32_t warn_pcre_no_content = 0;
883  uint32_t warn_pcre_http_content = 0;
884  uint32_t warn_pcre_http = 0;
885  uint32_t warn_content_http_content = 0;
886  uint32_t warn_content_http = 0;
887  uint32_t warn_tcp_no_flow = 0;
888  uint32_t warn_client_ports = 0;
889  uint32_t warn_direction = 0;
890  uint32_t warn_method_toclient = 0;
891  uint32_t warn_method_serverbody = 0;
892  uint32_t warn_pcre_method = 0;
893  uint32_t warn_encoding_norm_http_buf = 0;
894  uint32_t warn_offset_depth_pkt_stream = 0;
895  uint32_t warn_offset_depth_alproto = 0;
896  uint32_t warn_non_alproto_fp_for_alproto_sig = 0;
897  uint32_t warn_no_direction = 0;
898  uint32_t warn_both_direction = 0;
899 
900  const int nlists = de_ctx->buffer_type_id;
901  const int filedata_id = DetectBufferTypeGetByName("file_data");
902  const int httpmethod_id = DetectBufferTypeGetByName("http_method");
903  const int httpuri_id = DetectBufferTypeGetByName("http_uri");
904  const int httpuseragent_id = DetectBufferTypeGetByName("http_user_agent");
905  const int httpcookie_id = DetectBufferTypeGetByName("http_cookie");
906  const int httpstatcode_id = DetectBufferTypeGetByName("http_stat_code");
907  const int httpstatmsg_id = DetectBufferTypeGetByName("http_stat_msg");
908  const int httpheader_id = DetectBufferTypeGetByName("http_header");
909  const int httprawheader_id = DetectBufferTypeGetByName("http_raw_header");
910  const int httpclientbody_id = DetectBufferTypeGetByName("http_client_body");
911  const int httprawuri_id = DetectBufferTypeGetByName("http_raw_uri");
912  const int httphost_id = DetectBufferTypeGetByName("http_host");
913  const int httprawhost_id = DetectBufferTypeGetByName("http_raw_host");
914  const int httpreferer_id = DetectBufferTypeGetByName("http_referer");
915  const int httpheadernames_id = DetectBufferTypeGetByName("http_header_names");
916 
918  rule_bidirectional = 1;
919  }
920 
921  if (s->flags & SIG_FLAG_REQUIRE_PACKET) {
922  packet_buf += 1;
923  }
924  if (s->flags & SIG_FLAG_REQUIRE_STREAM) {
925  stream_buf += 1;
926  }
927 
928  if (s->proto.flags & DETECT_PROTO_IPV4) {
929  rule_ipv4_only += 1;
930  }
931  if (s->proto.flags & DETECT_PROTO_IPV6) {
932  rule_ipv6_only += 1;
933  }
934 
935  for (list_id = 0; list_id < nlists; list_id++) {
936  SigMatch *sm = NULL;
937  for (sm = s->init_data->smlists[list_id]; sm != NULL; sm = sm->next) {
938  if (sm->type == DETECT_PCRE) {
939  if (list_id == httpclientbody_id) {
940  rule_pcre_http += 1;
941  http_client_body_buf += 1;
942  raw_http_buf += 1;
943  }
944  else if (list_id == httpuri_id) {
945  rule_pcre_http += 1;
946  norm_http_buf += 1;
947  http_uri_buf += 1;
948  }
949  else if (list_id == httpheader_id) {
950  rule_pcre_http += 1;
951  norm_http_buf += 1;
952  http_header_buf += 1;
953  }
954  else if (list_id == httpcookie_id) {
955  rule_pcre_http += 1;
956  norm_http_buf += 1;
957  http_cookie_buf += 1;
958  }
959  else if (list_id == filedata_id) {
960  rule_pcre_http += 1;
961  http_server_body_buf += 1;
962  raw_http_buf += 1;
963  }
964  else if (list_id == httprawheader_id) {
965  rule_pcre_http += 1;
966  raw_http_buf += 1;
967  http_raw_header_buf += 1;
968  }
969  else if (list_id == httpmethod_id) {
970  rule_pcre_http += 1;
971  raw_http_buf += 1;
972  http_method_buf += 1;
973  }
974  else if (list_id == httprawuri_id) {
975  rule_pcre_http += 1;
976  raw_http_buf += 1;
977  http_raw_uri_buf += 1;
978  }
979  else if (list_id == httpstatmsg_id) {
980  rule_pcre_http += 1;
981  raw_http_buf += 1;
982  http_stat_msg_buf += 1;
983  }
984  else if (list_id == httpstatcode_id) {
985  rule_pcre_http += 1;
986  raw_http_buf += 1;
987  http_stat_code_buf += 1;
988  }
989  else if (list_id == httpuseragent_id) {
990  rule_pcre_http += 1;
991  norm_http_buf += 1;
992  http_ua_buf += 1;
993  }
994  else if (list_id == httphost_id) {
995  rule_pcre_http += 1;
996  norm_http_buf += 1;
997  http_host_buf += 1;
998  }
999  else if (list_id == httprawhost_id) {
1000  rule_pcre_http += 1;
1001  raw_http_buf += 1;
1002  http_rawhost_buf += 1;
1003  }
1004  else if (list_id == httpheadernames_id) {
1005  rule_pcre_http += 1;
1006  raw_http_buf += 1;
1007  http_headernames_buf += 1;
1008  }
1009  else if (list_id == httpreferer_id) {
1010  rule_pcre_http += 1;
1011  raw_http_buf += 1;
1012  http_referer_buf += 1;
1013  }
1014  else {
1015  rule_pcre += 1;
1016  }
1017  }
1018  else if (sm->type == DETECT_CONTENT) {
1019 
1020  if (list_id == httpuri_id
1021  || list_id == httpheader_id
1022  || list_id == httpcookie_id) {
1023  rule_content_http += 1;
1024  norm_http_buf += 1;
1026  if (cd != NULL && PerCentEncodingMatch(cd->content, cd->content_len) > 0) {
1027  warn_encoding_norm_http_buf += 1;
1028  rule_warning += 1;
1029  }
1030  if (list_id == httpuri_id) {
1031  http_uri_buf += 1;
1032  }
1033  else if (list_id == httpheader_id) {
1034  http_header_buf += 1;
1035  }
1036  else if (list_id == httpcookie_id) {
1037  http_cookie_buf += 1;
1038  }
1039  }
1040  else if (list_id == httpclientbody_id) {
1041  rule_content_http += 1;
1042  raw_http_buf += 1;
1043  http_client_body_buf += 1;
1044  }
1045  else if (list_id == filedata_id) {
1046  rule_content_http += 1;
1047  raw_http_buf += 1;
1048  http_server_body_buf += 1;
1049  }
1050  else if (list_id == httprawheader_id) {
1051  rule_content_http += 1;
1052  raw_http_buf += 1;
1053  http_raw_header_buf += 1;
1054  }
1055  else if (list_id == httprawuri_id) {
1056  rule_content_http += 1;
1057  raw_http_buf += 1;
1058  http_raw_uri_buf += 1;
1059  }
1060  else if (list_id == httpstatmsg_id) {
1061  rule_content_http += 1;
1062  raw_http_buf += 1;
1063  http_stat_msg_buf += 1;
1064  }
1065  else if (list_id == httpstatcode_id) {
1066  rule_content_http += 1;
1067  raw_http_buf += 1;
1068  http_stat_code_buf += 1;
1069  }
1070  else if (list_id == httpmethod_id) {
1071  rule_content_http += 1;
1072  raw_http_buf += 1;
1073  http_method_buf += 1;
1074  }
1075  else if (list_id == httphost_id) {
1076  rule_content_http += 1;
1077  raw_http_buf += 1;
1078  http_host_buf += 1;
1079  }
1080  else if (list_id == httpuseragent_id) {
1081  rule_content_http += 1;
1082  norm_http_buf += 1;
1083  http_ua_buf += 1;
1084  }
1085  else if (list_id == httprawhost_id) {
1086  rule_content_http += 1;
1087  raw_http_buf += 1;
1088  http_rawhost_buf += 1;
1089  }
1090  else if (list_id == httpheadernames_id) {
1091  rule_content_http += 1;
1092  raw_http_buf += 1;
1093  http_headernames_buf += 1;
1094  }
1095  else if (list_id == httpreferer_id) {
1096  rule_content_http += 1;
1097  raw_http_buf += 1;
1098  http_referer_buf += 1;
1099  }
1100  else if (list_id == DETECT_SM_LIST_PMATCH) {
1101  rule_content += 1;
1103  if (cd->flags &
1105  rule_content_offset_depth++;
1106  }
1107  } else {
1108  rule_content += 1;
1109  }
1110  }
1111  else if (sm->type == DETECT_FLOW) {
1112  rule_flow += 1;
1113  if ((s->flags & SIG_FLAG_TOSERVER) && !(s->flags & SIG_FLAG_TOCLIENT)) {
1114  rule_flow_toserver = 1;
1115  }
1116  else if ((s->flags & SIG_FLAG_TOCLIENT) && !(s->flags & SIG_FLAG_TOSERVER)) {
1117  rule_flow_toclient = 1;
1118  }
1119  DetectFlowData *fd = (DetectFlowData *)sm->ctx;
1120  if (fd != NULL) {
1121  if (fd->flags & DETECT_FLOW_FLAG_NOSTREAM)
1122  rule_flow_nostream = 1;
1123  }
1124  }
1125  else if (sm->type == DETECT_FLOWBITS) {
1126  if (list_id == DETECT_SM_LIST_MATCH) {
1127  rule_flowbits += 1;
1128  }
1129  }
1130  else if (sm->type == DETECT_FLOWINT) {
1131  if (list_id == DETECT_SM_LIST_MATCH) {
1132  rule_flowint += 1;
1133  }
1134  }
1135  else if (sm->type == DETECT_FLAGS) {
1136  DetectFlagsData *fd = (DetectFlagsData *)sm->ctx;
1137  if (fd != NULL) {
1138  rule_flags = 1;
1139  }
1140  }
1141  } /* for (sm = s->sm_lists[list_id]; sm != NULL; sm = sm->next) */
1142 
1143  } /* for ( ; list_id < DETECT_SM_LIST_MAX; list_id++) */
1144 
1145 
1146  if (rule_pcre > 0 && rule_content == 0 && rule_content_http == 0) {
1147  rule_warning += 1;
1148  warn_pcre_no_content = 1;
1149  }
1150 
1151  if (rule_content_http > 0 && rule_pcre > 0 && rule_pcre_http == 0) {
1152  rule_warning += 1;
1153  warn_pcre_http_content = 1;
1154  }
1155  else if (s->alproto == ALPROTO_HTTP && rule_pcre > 0 && rule_pcre_http == 0) {
1156  rule_warning += 1;
1157  warn_pcre_http = 1;
1158  }
1159 
1160  if (rule_content > 0 && rule_content_http > 0) {
1161  rule_warning += 1;
1162  warn_content_http_content = 1;
1163  }
1164  if (s->alproto == ALPROTO_HTTP && rule_content > 0 && rule_content_http == 0) {
1165  rule_warning += 1;
1166  warn_content_http = 1;
1167  }
1168  if (rule_content == 1) {
1169  //todo: warning if content is weak, separate warning for pcre + weak content
1170  }
1171  if (rule_flow == 0 && rule_flags == 0
1172  && !(s->proto.flags & DETECT_PROTO_ANY) && DetectProtoContainsProto(&s->proto, IPPROTO_TCP)
1173  && (rule_content || rule_content_http || rule_pcre || rule_pcre_http || rule_flowbits)) {
1174  rule_warning += 1;
1175  warn_tcp_no_flow = 1;
1176  }
1177  if (rule_flow && !rule_bidirectional && (rule_flow_toserver || rule_flow_toclient)
1178  && !((s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY))) {
1179  if (((s->flags & SIG_FLAG_TOSERVER) && !(s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY))
1180  || ((s->flags & SIG_FLAG_TOCLIENT) && !(s->flags & SIG_FLAG_DP_ANY) && (s->flags & SIG_FLAG_SP_ANY))) {
1181  rule_warning += 1;
1182  warn_client_ports = 1;
1183  }
1184  }
1185  if (rule_flow && rule_bidirectional && (rule_flow_toserver || rule_flow_toclient)) {
1186  rule_warning += 1;
1187  warn_direction = 1;
1188  }
1189  if (http_method_buf) {
1190  if (rule_flow && rule_flow_toclient) {
1191  rule_warning += 1;
1192  warn_method_toclient = 1;
1193  }
1194  if (http_server_body_buf) {
1195  rule_warning += 1;
1196  warn_method_serverbody = 1;
1197  }
1198  if (rule_content == 0 && rule_content_http == 0 && (rule_pcre > 0 || rule_pcre_http > 0)) {
1199  rule_warning += 1;
1200  warn_pcre_method = 1;
1201  }
1202  }
1203  if (rule_content_offset_depth > 0 && stream_buf && packet_buf) {
1204  rule_warning += 1;
1205  warn_offset_depth_pkt_stream = 1;
1206  }
1207  if (rule_content_offset_depth > 0 && !stream_buf && packet_buf && s->alproto != ALPROTO_UNKNOWN) {
1208  rule_warning += 1;
1209  warn_offset_depth_alproto = 1;
1210  }
1211  if (s->init_data->mpm_sm != NULL && s->alproto == ALPROTO_HTTP &&
1213  rule_warning += 1;
1214  warn_non_alproto_fp_for_alproto_sig = 1;
1215  }
1216 
1217  if ((s->flags & (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) == 0) {
1218  warn_no_direction += 1;
1219  rule_warning += 1;
1220  }
1222  warn_both_direction += 1;
1223  rule_warning += 1;
1224  }
1225 
1226  if (!rule_warnings_only || (rule_warnings_only && rule_warning > 0)) {
1227  fprintf(rule_engine_analysis_FD, "== Sid: %u ==\n", s->id);
1228  fprintf(rule_engine_analysis_FD, "%s\n", line);
1229 
1230  if (s->flags & SIG_FLAG_IPONLY) fprintf(rule_engine_analysis_FD, " Rule is ip only.\n");
1231  if (s->flags & SIG_FLAG_PDONLY) fprintf(rule_engine_analysis_FD, " Rule is PD only.\n");
1232  if (rule_ipv6_only) fprintf(rule_engine_analysis_FD, " Rule is IPv6 only.\n");
1233  if (rule_ipv4_only) fprintf(rule_engine_analysis_FD, " Rule is IPv4 only.\n");
1234  if (packet_buf) fprintf(rule_engine_analysis_FD, " Rule matches on packets.\n");
1235  if (!rule_flow_nostream && stream_buf && (rule_flow || rule_flowbits || rule_content || rule_pcre)) {
1236  fprintf(rule_engine_analysis_FD, " Rule matches on reassembled stream.\n");
1237  }
1238  if (http_uri_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http uri buffer.\n");
1239  if (http_header_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http header buffer.\n");
1240  if (http_cookie_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http cookie buffer.\n");
1241  if (http_raw_uri_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http raw uri buffer.\n");
1242  if (http_raw_header_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http raw header buffer.\n");
1243  if (http_method_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http method buffer.\n");
1244  if (http_server_body_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http server body buffer.\n");
1245  if (http_client_body_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http client body buffer.\n");
1246  if (http_stat_msg_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http stat msg buffer.\n");
1247  if (http_stat_code_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http stat code buffer.\n");
1248  if (http_ua_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http user agent buffer.\n");
1249  if (http_host_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http host buffer.\n");
1250  if (http_rawhost_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http rawhost buffer.\n");
1251  if (http_headernames_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http header names buffer.\n");
1252  if (http_referer_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http header referer buffer.\n");
1253  if (s->alproto != ALPROTO_UNKNOWN) {
1254  fprintf(rule_engine_analysis_FD, " App layer protocol is %s.\n", AppProtoToString(s->alproto));
1255  }
1256  if (rule_content || rule_content_http || rule_pcre || rule_pcre_http) {
1257  fprintf(rule_engine_analysis_FD, " Rule contains %d content options, %d http content options, %d pcre options, and %d pcre options with http modifiers.\n", rule_content, rule_content_http, rule_pcre, rule_pcre_http);
1258  }
1259 
1260  /* print fast pattern info */
1261  if (s->init_data->prefilter_sm) {
1262  fprintf(rule_engine_analysis_FD, " Prefilter on: %s.\n",
1264  } else {
1265  EngineAnalysisRulesPrintFP(de_ctx, s);
1266  }
1267 
1268  /* this is where the warnings start */
1269  if (warn_pcre_no_content /*rule_pcre > 0 && rule_content == 0 && rule_content_http == 0*/) {
1270  fprintf(rule_engine_analysis_FD, " Warning: Rule uses pcre without a content option present.\n"
1271  " -Consider adding a content to improve performance of this rule.\n");
1272  }
1273  if (warn_pcre_http_content /*rule_content_http > 0 && rule_pcre > 0 && rule_pcre_http == 0*/) {
1274  fprintf(rule_engine_analysis_FD, " Warning: Rule uses content options with http_* and pcre options without http modifiers.\n"
1275  " -Consider adding http pcre modifier.\n");
1276  }
1277  else if (warn_pcre_http /*s->alproto == ALPROTO_HTTP && rule_pcre > 0 && rule_pcre_http == 0*/) {
1278  fprintf(rule_engine_analysis_FD, " Warning: Rule app layer protocol is http, but pcre options do not have http modifiers.\n"
1279  " -Consider adding http pcre modifiers.\n");
1280  }
1281  if (warn_content_http_content /*rule_content > 0 && rule_content_http > 0*/) {
1282  fprintf(rule_engine_analysis_FD, " Warning: Rule contains content with http_* and content without http_*.\n"
1283  " -Consider adding http content modifiers.\n");
1284  }
1285  if (warn_content_http /*s->alproto == ALPROTO_HTTP && rule_content > 0 && rule_content_http == 0*/) {
1286  fprintf(rule_engine_analysis_FD, " Warning: Rule app layer protocol is http, but content options do not have http_* modifiers.\n"
1287  " -Consider adding http content modifiers.\n");
1288  }
1289  if (rule_content == 1) {
1290  //todo: warning if content is weak, separate warning for pcre + weak content
1291  }
1292  if (warn_encoding_norm_http_buf) {
1293  fprintf(rule_engine_analysis_FD, " Warning: Rule may contain percent encoded content for a normalized http buffer match.\n");
1294  }
1295  if (warn_tcp_no_flow /*rule_flow == 0 && rule_flags == 0
1296  && !(s->proto.flags & DETECT_PROTO_ANY) && DetectProtoContainsProto(&s->proto, IPPROTO_TCP)*/) {
1297  fprintf(rule_engine_analysis_FD, " Warning: TCP rule without a flow or flags option.\n"
1298  " -Consider adding flow or flags to improve performance of this rule.\n");
1299  }
1300  if (warn_client_ports /*rule_flow && !rule_bidirectional && (rule_flow_toserver || rule_flow_toclient)
1301  && !((s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY)))
1302  if (((s->flags & SIG_FLAG_TOSERVER) && !(s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY))
1303  || ((s->flags & SIG_FLAG_TOCLIENT) && !(s->flags & SIG_FLAG_DP_ANY) && (s->flags & SIG_FLAG_SP_ANY))*/) {
1304  fprintf(rule_engine_analysis_FD, " Warning: Rule contains ports or port variables only on the client side.\n"
1305  " -Flow direction possibly inconsistent with rule.\n");
1306  }
1307  if (warn_direction /*rule_flow && rule_bidirectional && (rule_flow_toserver || rule_flow_toclient)*/) {
1308  fprintf(rule_engine_analysis_FD, " Warning: Rule is bidirectional and has a flow option with a specific direction.\n");
1309  }
1310  if (warn_method_toclient /*http_method_buf && rule_flow && rule_flow_toclient*/) {
1311  fprintf(rule_engine_analysis_FD, " Warning: Rule uses content or pcre for http_method with flow:to_client or from_server\n");
1312  }
1313  if (warn_method_serverbody /*http_method_buf && http_server_body_buf*/) {
1314  fprintf(rule_engine_analysis_FD, " Warning: Rule uses content or pcre for http_method with content or pcre for http_server_body.\n");
1315  }
1316  if (warn_pcre_method /*http_method_buf && rule_content == 0 && rule_content_http == 0
1317  && (rule_pcre > 0 || rule_pcre_http > 0)*/) {
1318  fprintf(rule_engine_analysis_FD, " Warning: Rule uses pcre with only a http_method content; possible performance issue.\n");
1319  }
1320  if (warn_offset_depth_pkt_stream) {
1321  fprintf(rule_engine_analysis_FD, " Warning: Rule has depth"
1322  "/offset with raw content keywords. Please note the "
1323  "offset/depth will be checked against both packet "
1324  "payloads and stream. If you meant to have the offset/"
1325  "depth checked against just the payload, you can update "
1326  "the signature as \"alert tcp-pkt...\"\n");
1327  }
1328  if (warn_offset_depth_alproto) {
1329  fprintf(rule_engine_analysis_FD, " Warning: Rule has "
1330  "offset/depth set along with a match on a specific "
1331  "app layer protocol - %d. This can lead to FNs if we "
1332  "have a offset/depth content match on a packet payload "
1333  "before we can detect the app layer protocol for the "
1334  "flow.\n", s->alproto);
1335  }
1336  if (warn_non_alproto_fp_for_alproto_sig) {
1337  fprintf(rule_engine_analysis_FD, " Warning: Rule app layer "
1338  "protocol is http, but the fast_pattern is set on the raw "
1339  "stream. Consider adding fast_pattern over a http "
1340  "buffer for increased performance.");
1341  }
1342  if (warn_no_direction) {
1343  fprintf(rule_engine_analysis_FD, " Warning: Rule has no direction indicator.\n");
1344  }
1345  if (warn_both_direction) {
1346  fprintf(rule_engine_analysis_FD, " Warning: Rule is inspecting both the request and the response.\n");
1347  }
1348  if (rule_warning == 0) {
1349  fprintf(rule_engine_analysis_FD, " No warnings for this rule.\n");
1350  }
1351  fprintf(rule_engine_analysis_FD, "\n");
1352  }
1353  return;
1354 }
#define SIG_FLAG_FILESTORE
Definition: detect.h:239
MemBuffer * MemBufferCreateNew(uint32_t size)
Definition: util-buffer.c:32
void CleanupFPAnalyzer(void)
#define SCMutex
SigTableElmt sigmatch_table[DETECT_TBLSIZE]
Definition: detect.h:1409
DetectProto proto
Definition: detect.h:513
SignatureInitData * init_data
Definition: detect.h:564
#define DETECT_PROTO_IPV6
#define SIG_FLAG_PDONLY
Definition: detect.h:252
int PerCentEncodingMatch(uint8_t *content, uint8_t content_len)
Checks for % encoding in content.
#define SIG_FLAG_PREFILTER
Definition: detect.h:248
#define MemBufferWriteString(dst,...)
Write a string buffer to the Membuffer dst.
Definition: util-buffer.h:162
SigMatch * prefilter_sm
Definition: detect.h:469
uint32_t flags
Definition: detect.h:497
char * msg
Definition: detect.h:553
uint32_t id
Definition: detect.h:529
#define DETECT_PROTO_ANY
#define DETECT_CONTENT_FAST_PATTERN
#define unlikely(expr)
Definition: util-optimize.h:35
uint8_t is_last
Definition: detect.h:333
int ConfGetBool(const char *name, int *val)
Retrieve a configuration value as an boolen.
Definition: conf.c:517
int buffer_type_id
Definition: detect.h:885
#define SIG_FLAG_REQUIRE_STREAM
Definition: detect.h:229
#define DETECT_PERCENT_ENCODING_REGEX
Data needed for Match()
Definition: detect.h:331
uint16_t flags
Definition: detect-flow.h:38
#define DETECT_CONTENT_DISTANCE
#define SIG_FLAG_REQUIRE_FLOWVAR
Definition: detect.h:237
#define SIG_FLAG_REQUIRE_PACKET
Definition: detect.h:228
#define SIG_FLAG_TLSSTORE
Definition: detect.h:244
const char * name
Definition: detect.h:1164
#define SIG_FLAG_DEST_IS_TARGET
Definition: detect.h:256
Signature container.
Definition: detect.h:496
#define SIG_MASK_REQUIRE_ENGINE_EVENT
Definition: detect.h:279
#define DETECT_CONTENT_DEPTH
#define SCMutexLock(mut)
#define SIG_FLAG_APPLAYER
Definition: detect.h:223
#define SIG_FLAG_SRC_IS_TARGET
Definition: detect.h:254
struct SigMatch_ * next
Definition: detect.h:326
main detection engine ctx
Definition: detect.h:724
#define SIG_MASK_REQUIRE_FLAGS_INITDEINIT
Definition: detect.h:274
#define SIG_FLAG_DST_ANY
Definition: detect.h:217
typedef __attribute__
DNP3 application header.
#define SIG_FLAG_MPM_NEG
Definition: detect.h:231
#define SIG_FLAG_INIT_BIDIREC
Definition: detect.h:264
int DetectBufferTypeGetByName(const char *name)
#define str(s)
const char * ConfNodeLookupChildValue(const ConfNode *node, const char *name)
Lookup the value of a child configuration node by name.
Definition: conf.c:843
#define SCMutexUnlock(mut)
#define SIG_FLAG_TOCLIENT
Definition: detect.h:242
struct tm * SCLocalTime(time_t timep, struct tm *result)
Definition: util-time.c:232
#define SIG_FLAG_SP_ANY
Definition: detect.h:218
#define SIG_FLAG_IPONLY
Definition: detect.h:224
#define SCMUTEX_INITIALIZER
#define SIG_MASK_REQUIRE_FLOW
Definition: detect.h:273
void CleanupRuleAnalyzer(void)
const char * AppProtoToString(AppProto alproto)
Maps the ALPROTO_*, to its string equivalent.
struct FpPatternStats_ FpPatternStats
struct DetectEngineAppInspectionEngine_ * next
Definition: detect.h:425
#define SIG_FLAG_FLUSH
Definition: detect.h:233
#define SCLogError(err_code,...)
Macro used to log ERROR messages.
Definition: util-debug.h:294
void EngineAnalysisRules(const DetectEngineCtx *de_ctx, const Signature *s, const char *line)
Prints analysis of loaded rules.
#define MemBufferPrintToFPAsString(mem_buffer, fp)
Write a buffer to the file pointer as a printable char string.
Definition: util-buffer.h:93
#define SIG_MASK_REQUIRE_FLAGS_UNUSUAL
Definition: detect.h:275
#define SIG_FLAG_TOSERVER
Definition: detect.h:241
#define DETECT_CONTENT_STARTS_WITH
#define SCEnter(...)
Definition: util-debug.h:337
#define MAX_ENCODED_CHARS
SigMatchData * sm_arrays[DETECT_SM_LIST_MAX]
Definition: detect.h:548
int SignatureHasPacketContent(const Signature *s)
check if a signature has patterns that are to be inspected against a packets payload (as opposed to t...
AppProto alproto
Definition: detect.h:500
void PrintRawUriFp(FILE *fp, uint8_t *buf, uint32_t buflen)
Definition: util-print.c:93
int PerCentEncodingSetup()
Compiles regex for rule analysis.
const char * DetectSigmatchListEnumToString(enum DetectSigmatchListEnum type)
uint32_t gid
Definition: detect.h:530
uint8_t type
Definition: detect.h:323
#define DETECT_CONTENT_FAST_PATTERN_ONLY
#define SIG_FLAG_INIT_STATE_MATCH
Definition: detect.h:267
#define DETECT_PROTO_IPV4
#define SCLogWarning(err_code,...)
Macro used to log WARNING messages.
Definition: util-debug.h:281
#define DETECT_CONTENT_ENDS_WITH
int ConfValIsTrue(const char *val)
Check if a value is true.
Definition: conf.c:566
struct SigMatch_ ** smlists
Definition: detect.h:490
void EngineAnalysisRulesFailure(char *line, char *file, int lineno)
#define SIG_MASK_REQUIRE_PAYLOAD
Definition: detect.h:272
#define DETECT_CONTENT_MPM
Definition: conf.h:32
void EngineAnalysisFP(const DetectEngineCtx *de_ctx, const Signature *s, char *line)
SigMatchCtx * ctx
Definition: detect.h:325
const char * ConfigGetLogDirectory()
Definition: util-conf.c:36
#define SCMalloc(a)
Definition: util-mem.h:166
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:254
uint8_t type
Definition: detect.h:332
#define DETECT_CONTENT_NEGATED
char * sig_str
Definition: detect.h:562
#define SCFree(a)
Definition: util-mem.h:228
#define SIG_FLAG_NOALERT
Definition: detect.h:221
#define SIG_FLAG_DSIZE
Definition: detect.h:222
uint32_t init_flags
Definition: detect.h:460
DetectEngineAppInspectionEngine * app_inspect
Definition: detect.h:544
uint32_t rev
Definition: detect.h:531
const char * DetectBufferTypeGetDescriptionById(const DetectEngineCtx *de_ctx, const int id)
#define SIG_FLAG_BYPASS
Definition: detect.h:246
ConfNode * ConfGetNode(const char *name)
Get a ConfNode by name.
Definition: conf.c:176
#define DETECT_CONTENT_WITHIN
int SignatureHasStreamContent(const Signature *s)
check if a signature has patterns that are to be inspected against the stream payload (as opposed to ...
int SetupFPAnalyzer(void)
Sets up the fast pattern analyzer according to the config.
#define SIG_FLAG_DP_ANY
Definition: detect.h:219
#define DETECT_CONTENT_FAST_PATTERN_CHOP
#define DETECT_CONTENT_NOCASE
#define SCReturn
Definition: util-debug.h:339
uint8_t len
SignatureMask mask
Definition: detect.h:505
int SigMatchListSMBelongsTo(const Signature *s, const SigMatch *key_sm)
Definition: detect-parse.c:561
#define DETECT_FLOW_FLAG_NOSTREAM
Definition: detect-flow.h:33
#define SIG_FLAG_SRC_ANY
Definition: detect.h:216
#define SIG_MASK_REQUIRE_DCERPC
Definition: detect.h:277
const char * DetectBufferTypeGetNameById(const DetectEngineCtx *de_ctx, const int id)
#define SIG_MASK_REQUIRE_NO_PAYLOAD
Definition: detect.h:276
SigMatch * mpm_sm
Definition: detect.h:467
#define DETECT_CONTENT_OFFSET
int DetectProtoContainsProto(const DetectProto *dp, int proto)
see if a DetectProto contains a certain proto
a single match condition for a signature
Definition: detect.h:322
int SetupRuleAnalyzer(void)
Sets up the rule analyzer according to the config.
void MemBufferFree(MemBuffer *buffer)
Definition: util-buffer.c:82
SigMatchCtx * ctx
Definition: detect.h:334