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 warn_pcre_no_content = 0;
880  uint32_t warn_pcre_http_content = 0;
881  uint32_t warn_pcre_http = 0;
882  uint32_t warn_content_http_content = 0;
883  uint32_t warn_content_http = 0;
884  uint32_t warn_tcp_no_flow = 0;
885  uint32_t warn_client_ports = 0;
886  uint32_t warn_direction = 0;
887  uint32_t warn_method_toclient = 0;
888  uint32_t warn_method_serverbody = 0;
889  uint32_t warn_pcre_method = 0;
890  uint32_t warn_encoding_norm_http_buf = 0;
891  uint32_t warn_offset_depth_pkt_stream = 0;
892  uint32_t warn_offset_depth_alproto = 0;
893  uint32_t warn_non_alproto_fp_for_alproto_sig = 0;
894  uint32_t warn_no_direction = 0;
895  uint32_t warn_both_direction = 0;
896 
897  const int nlists = de_ctx->buffer_type_id;
898  const int filedata_id = DetectBufferTypeGetByName("file_data");
899  const int httpmethod_id = DetectBufferTypeGetByName("http_method");
900  const int httpuri_id = DetectBufferTypeGetByName("http_uri");
901  const int httpuseragent_id = DetectBufferTypeGetByName("http_user_agent");
902  const int httpcookie_id = DetectBufferTypeGetByName("http_cookie");
903  const int httpstatcode_id = DetectBufferTypeGetByName("http_stat_code");
904  const int httpstatmsg_id = DetectBufferTypeGetByName("http_stat_msg");
905  const int httpheader_id = DetectBufferTypeGetByName("http_header");
906  const int httprawheader_id = DetectBufferTypeGetByName("http_raw_header");
907  const int httpclientbody_id = DetectBufferTypeGetByName("http_client_body");
908  const int httprawuri_id = DetectBufferTypeGetByName("http_raw_uri");
909  const int httphost_id = DetectBufferTypeGetByName("http_host");
910 
912  rule_bidirectional = 1;
913  }
914 
915  if (s->flags & SIG_FLAG_REQUIRE_PACKET) {
916  packet_buf += 1;
917  }
918  if (s->flags & SIG_FLAG_REQUIRE_STREAM) {
919  stream_buf += 1;
920  }
921 
922  if (s->proto.flags & DETECT_PROTO_IPV4) {
923  rule_ipv4_only += 1;
924  }
925  if (s->proto.flags & DETECT_PROTO_IPV6) {
926  rule_ipv6_only += 1;
927  }
928 
929  for (list_id = 0; list_id < nlists; list_id++) {
930  SigMatch *sm = NULL;
931  for (sm = s->init_data->smlists[list_id]; sm != NULL; sm = sm->next) {
932  if (sm->type == DETECT_PCRE) {
933  if (list_id == httpclientbody_id) {
934  rule_pcre_http += 1;
935  http_client_body_buf += 1;
936  raw_http_buf += 1;
937  }
938  else if (list_id == httpuri_id) {
939  rule_pcre_http += 1;
940  norm_http_buf += 1;
941  http_uri_buf += 1;
942  }
943  else if (list_id == httpheader_id) {
944  rule_pcre_http += 1;
945  norm_http_buf += 1;
946  http_header_buf += 1;
947  }
948  else if (list_id == httpcookie_id) {
949  rule_pcre_http += 1;
950  norm_http_buf += 1;
951  http_cookie_buf += 1;
952  }
953  else if (list_id == filedata_id) {
954  rule_pcre_http += 1;
955  http_server_body_buf += 1;
956  raw_http_buf += 1;
957  }
958  else if (list_id == httprawheader_id) {
959  rule_pcre_http += 1;
960  raw_http_buf += 1;
961  http_raw_header_buf += 1;
962  }
963  else if (list_id == httpmethod_id) {
964  rule_pcre_http += 1;
965  raw_http_buf += 1;
966  http_method_buf += 1;
967  }
968  else if (list_id == httprawuri_id) {
969  rule_pcre_http += 1;
970  raw_http_buf += 1;
971  http_raw_uri_buf += 1;
972  }
973  else if (list_id == httpstatmsg_id) {
974  rule_pcre_http += 1;
975  raw_http_buf += 1;
976  http_stat_msg_buf += 1;
977  }
978  else if (list_id == httpstatcode_id) {
979  rule_pcre_http += 1;
980  raw_http_buf += 1;
981  http_stat_code_buf += 1;
982  }
983  else if (list_id == httpuseragent_id) {
984  rule_pcre_http += 1;
985  norm_http_buf += 1;
986  http_ua_buf += 1;
987  }
988  else if (list_id == httphost_id) {
989  rule_pcre_http += 1;
990  norm_http_buf += 1;
991  http_host_buf += 1;
992  }
993  else {
994  rule_pcre += 1;
995  }
996  }
997  else if (sm->type == DETECT_CONTENT) {
998 
999  if (list_id == httpuri_id
1000  || list_id == httpheader_id
1001  || list_id == httpcookie_id) {
1002  rule_content_http += 1;
1003  norm_http_buf += 1;
1005  if (cd != NULL && PerCentEncodingMatch(cd->content, cd->content_len) > 0) {
1006  warn_encoding_norm_http_buf += 1;
1007  rule_warning += 1;
1008  }
1009  if (list_id == httpuri_id) {
1010  http_uri_buf += 1;
1011  }
1012  else if (list_id == httpheader_id) {
1013  http_header_buf += 1;
1014  }
1015  else if (list_id == httpcookie_id) {
1016  http_cookie_buf += 1;
1017  }
1018  }
1019  else if (list_id == httpclientbody_id) {
1020  rule_content_http += 1;
1021  raw_http_buf += 1;
1022  http_client_body_buf += 1;
1023  }
1024  else if (list_id == filedata_id) {
1025  rule_content_http += 1;
1026  raw_http_buf += 1;
1027  http_server_body_buf += 1;
1028  }
1029  else if (list_id == httprawheader_id) {
1030  rule_content_http += 1;
1031  raw_http_buf += 1;
1032  http_raw_header_buf += 1;
1033  }
1034  else if (list_id == httprawuri_id) {
1035  rule_content_http += 1;
1036  raw_http_buf += 1;
1037  http_raw_uri_buf += 1;
1038  }
1039  else if (list_id == httpstatmsg_id) {
1040  rule_content_http += 1;
1041  raw_http_buf += 1;
1042  http_stat_msg_buf += 1;
1043  }
1044  else if (list_id == httpstatcode_id) {
1045  rule_content_http += 1;
1046  raw_http_buf += 1;
1047  http_stat_code_buf += 1;
1048  }
1049  else if (list_id == httpmethod_id) {
1050  rule_content_http += 1;
1051  raw_http_buf += 1;
1052  http_method_buf += 1;
1053  }
1054  else if (list_id == httphost_id) {
1055  rule_content_http += 1;
1056  raw_http_buf += 1;
1057  http_host_buf += 1;
1058  }
1059  else if (list_id == DETECT_SM_LIST_PMATCH) {
1060  rule_content += 1;
1062  if (cd->flags &
1064  rule_content_offset_depth++;
1065  }
1066  }
1067  }
1068  else if (sm->type == DETECT_FLOW) {
1069  rule_flow += 1;
1070  if ((s->flags & SIG_FLAG_TOSERVER) && !(s->flags & SIG_FLAG_TOCLIENT)) {
1071  rule_flow_toserver = 1;
1072  }
1073  else if ((s->flags & SIG_FLAG_TOCLIENT) && !(s->flags & SIG_FLAG_TOSERVER)) {
1074  rule_flow_toclient = 1;
1075  }
1076  DetectFlowData *fd = (DetectFlowData *)sm->ctx;
1077  if (fd != NULL) {
1078  if (fd->flags & DETECT_FLOW_FLAG_NOSTREAM)
1079  rule_flow_nostream = 1;
1080  }
1081  }
1082  else if (sm->type == DETECT_FLOWBITS) {
1083  if (list_id == DETECT_SM_LIST_MATCH) {
1084  rule_flowbits += 1;
1085  }
1086  }
1087  else if (sm->type == DETECT_FLOWINT) {
1088  if (list_id == DETECT_SM_LIST_MATCH) {
1089  rule_flowint += 1;
1090  }
1091  }
1092  else if (sm->type == DETECT_FLAGS) {
1093  DetectFlagsData *fd = (DetectFlagsData *)sm->ctx;
1094  if (fd != NULL) {
1095  rule_flags = 1;
1096  }
1097  }
1098  } /* for (sm = s->sm_lists[list_id]; sm != NULL; sm = sm->next) */
1099 
1100  } /* for ( ; list_id < DETECT_SM_LIST_MAX; list_id++) */
1101 
1102 
1103  if (rule_pcre > 0 && rule_content == 0 && rule_content_http == 0) {
1104  rule_warning += 1;
1105  warn_pcre_no_content = 1;
1106  }
1107 
1108  if (rule_content_http > 0 && rule_pcre > 0 && rule_pcre_http == 0) {
1109  rule_warning += 1;
1110  warn_pcre_http_content = 1;
1111  }
1112  else if (s->alproto == ALPROTO_HTTP && rule_pcre > 0 && rule_pcre_http == 0) {
1113  rule_warning += 1;
1114  warn_pcre_http = 1;
1115  }
1116 
1117  if (rule_content > 0 && rule_content_http > 0) {
1118  rule_warning += 1;
1119  warn_content_http_content = 1;
1120  }
1121  if (s->alproto == ALPROTO_HTTP && rule_content > 0 && rule_content_http == 0) {
1122  rule_warning += 1;
1123  warn_content_http = 1;
1124  }
1125  if (rule_content == 1) {
1126  //todo: warning if content is weak, separate warning for pcre + weak content
1127  }
1128  if (rule_flow == 0 && rule_flags == 0
1129  && !(s->proto.flags & DETECT_PROTO_ANY) && DetectProtoContainsProto(&s->proto, IPPROTO_TCP)
1130  && (rule_content || rule_content_http || rule_pcre || rule_pcre_http || rule_flowbits)) {
1131  rule_warning += 1;
1132  warn_tcp_no_flow = 1;
1133  }
1134  if (rule_flow && !rule_bidirectional && (rule_flow_toserver || rule_flow_toclient)
1135  && !((s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY))) {
1136  if (((s->flags & SIG_FLAG_TOSERVER) && !(s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY))
1137  || ((s->flags & SIG_FLAG_TOCLIENT) && !(s->flags & SIG_FLAG_DP_ANY) && (s->flags & SIG_FLAG_SP_ANY))) {
1138  rule_warning += 1;
1139  warn_client_ports = 1;
1140  }
1141  }
1142  if (rule_flow && rule_bidirectional && (rule_flow_toserver || rule_flow_toclient)) {
1143  rule_warning += 1;
1144  warn_direction = 1;
1145  }
1146  if (http_method_buf) {
1147  if (rule_flow && rule_flow_toclient) {
1148  rule_warning += 1;
1149  warn_method_toclient = 1;
1150  }
1151  if (http_server_body_buf) {
1152  rule_warning += 1;
1153  warn_method_serverbody = 1;
1154  }
1155  if (rule_content == 0 && rule_content_http == 0 && (rule_pcre > 0 || rule_pcre_http > 0)) {
1156  rule_warning += 1;
1157  warn_pcre_method = 1;
1158  }
1159  }
1160  if (rule_content_offset_depth > 0 && stream_buf && packet_buf) {
1161  rule_warning += 1;
1162  warn_offset_depth_pkt_stream = 1;
1163  }
1164  if (rule_content_offset_depth > 0 && !stream_buf && packet_buf && s->alproto != ALPROTO_UNKNOWN) {
1165  rule_warning += 1;
1166  warn_offset_depth_alproto = 1;
1167  }
1168  if (s->init_data->mpm_sm != NULL && s->alproto == ALPROTO_HTTP &&
1170  rule_warning += 1;
1171  warn_non_alproto_fp_for_alproto_sig = 1;
1172  }
1173 
1174  if ((s->flags & (SIG_FLAG_TOSERVER|SIG_FLAG_TOCLIENT)) == 0) {
1175  warn_no_direction += 1;
1176  rule_warning += 1;
1177  }
1179  warn_both_direction += 1;
1180  rule_warning += 1;
1181  }
1182 
1183  if (!rule_warnings_only || (rule_warnings_only && rule_warning > 0)) {
1184  fprintf(rule_engine_analysis_FD, "== Sid: %u ==\n", s->id);
1185  fprintf(rule_engine_analysis_FD, "%s\n", line);
1186 
1187  if (s->flags & SIG_FLAG_IPONLY) fprintf(rule_engine_analysis_FD, " Rule is ip only.\n");
1188  if (s->flags & SIG_FLAG_PDONLY) fprintf(rule_engine_analysis_FD, " Rule is PD only.\n");
1189  if (rule_ipv6_only) fprintf(rule_engine_analysis_FD, " Rule is IPv6 only.\n");
1190  if (rule_ipv4_only) fprintf(rule_engine_analysis_FD, " Rule is IPv4 only.\n");
1191  if (packet_buf) fprintf(rule_engine_analysis_FD, " Rule matches on packets.\n");
1192  if (!rule_flow_nostream && stream_buf && (rule_flow || rule_flowbits || rule_content || rule_pcre)) {
1193  fprintf(rule_engine_analysis_FD, " Rule matches on reassembled stream.\n");
1194  }
1195  if (http_uri_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http uri buffer.\n");
1196  if (http_header_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http header buffer.\n");
1197  if (http_cookie_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http cookie buffer.\n");
1198  if (http_raw_uri_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http raw uri buffer.\n");
1199  if (http_raw_header_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http raw header buffer.\n");
1200  if (http_method_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http method buffer.\n");
1201  if (http_server_body_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http server body buffer.\n");
1202  if (http_client_body_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http client body buffer.\n");
1203  if (http_stat_msg_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http stat msg buffer.\n");
1204  if (http_stat_code_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http stat code buffer.\n");
1205  if (http_ua_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http user agent buffer.\n");
1206  if (http_host_buf) fprintf(rule_engine_analysis_FD, " Rule matches on http host buffer.\n");
1207  if (s->alproto != ALPROTO_UNKNOWN) {
1208  fprintf(rule_engine_analysis_FD, " App layer protocol is %s.\n", AppProtoToString(s->alproto));
1209  }
1210  if (rule_content || rule_content_http || rule_pcre || rule_pcre_http) {
1211  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);
1212  }
1213 
1214  /* print fast pattern info */
1215  if (s->init_data->prefilter_sm) {
1216  fprintf(rule_engine_analysis_FD, " Prefilter on: %s.\n",
1218  } else {
1219  EngineAnalysisRulesPrintFP(de_ctx, s);
1220  }
1221 
1222  /* this is where the warnings start */
1223  if (warn_pcre_no_content /*rule_pcre > 0 && rule_content == 0 && rule_content_http == 0*/) {
1224  fprintf(rule_engine_analysis_FD, " Warning: Rule uses pcre without a content option present.\n"
1225  " -Consider adding a content to improve performance of this rule.\n");
1226  }
1227  if (warn_pcre_http_content /*rule_content_http > 0 && rule_pcre > 0 && rule_pcre_http == 0*/) {
1228  fprintf(rule_engine_analysis_FD, " Warning: Rule uses content options with http_* and pcre options without http modifiers.\n"
1229  " -Consider adding http pcre modifier.\n");
1230  }
1231  else if (warn_pcre_http /*s->alproto == ALPROTO_HTTP && rule_pcre > 0 && rule_pcre_http == 0*/) {
1232  fprintf(rule_engine_analysis_FD, " Warning: Rule app layer protocol is http, but pcre options do not have http modifiers.\n"
1233  " -Consider adding http pcre modifiers.\n");
1234  }
1235  if (warn_content_http_content /*rule_content > 0 && rule_content_http > 0*/) {
1236  fprintf(rule_engine_analysis_FD, " Warning: Rule contains content with http_* and content without http_*.\n"
1237  " -Consider adding http content modifiers.\n");
1238  }
1239  if (warn_content_http /*s->alproto == ALPROTO_HTTP && rule_content > 0 && rule_content_http == 0*/) {
1240  fprintf(rule_engine_analysis_FD, " Warning: Rule app layer protocol is http, but content options do not have http_* modifiers.\n"
1241  " -Consider adding http content modifiers.\n");
1242  }
1243  if (rule_content == 1) {
1244  //todo: warning if content is weak, separate warning for pcre + weak content
1245  }
1246  if (warn_encoding_norm_http_buf) {
1247  fprintf(rule_engine_analysis_FD, " Warning: Rule may contain percent encoded content for a normalized http buffer match.\n");
1248  }
1249  if (warn_tcp_no_flow /*rule_flow == 0 && rule_flow == 0
1250  && !(s->proto.flags & DETECT_PROTO_ANY) && DetectProtoContainsProto(&s->proto, IPPROTO_TCP)*/) {
1251  fprintf(rule_engine_analysis_FD, " Warning: TCP rule without a flow or flags option.\n"
1252  " -Consider adding flow or flags to improve performance of this rule.\n");
1253  }
1254  if (warn_client_ports /*rule_flow && !rule_bidirectional && (rule_flow_toserver || rule_flow_toclient)
1255  && !((s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY)))
1256  if (((s->flags & SIG_FLAG_TOSERVER) && !(s->flags & SIG_FLAG_SP_ANY) && (s->flags & SIG_FLAG_DP_ANY))
1257  || ((s->flags & SIG_FLAG_TOCLIENT) && !(s->flags & SIG_FLAG_DP_ANY) && (s->flags & SIG_FLAG_SP_ANY))*/) {
1258  fprintf(rule_engine_analysis_FD, " Warning: Rule contains ports or port variables only on the client side.\n"
1259  " -Flow direction possibly inconsistent with rule.\n");
1260  }
1261  if (warn_direction /*rule_flow && rule_bidirectional && (rule_flow_toserver || rule_flow_toclient)*/) {
1262  fprintf(rule_engine_analysis_FD, " Warning: Rule is bidirectional and has a flow option with a specific direction.\n");
1263  }
1264  if (warn_method_toclient /*http_method_buf && rule_flow && rule_flow_toclient*/) {
1265  fprintf(rule_engine_analysis_FD, " Warning: Rule uses content or pcre for http_method with flow:to_client or from_server\n");
1266  }
1267  if (warn_method_serverbody /*http_method_buf && http_server_body_buf*/) {
1268  fprintf(rule_engine_analysis_FD, " Warning: Rule uses content or pcre for http_method with content or pcre for http_server_body.\n");
1269  }
1270  if (warn_pcre_method /*http_method_buf && rule_content == 0 && rule_content_http == 0
1271  && (rule_pcre > 0 || rule_pcre_http > 0)*/) {
1272  fprintf(rule_engine_analysis_FD, " Warning: Rule uses pcre with only a http_method content; possible performance issue.\n");
1273  }
1274  if (warn_offset_depth_pkt_stream) {
1275  fprintf(rule_engine_analysis_FD, " Warning: Rule has depth"
1276  "/offset with raw content keywords. Please note the "
1277  "offset/depth will be checked against both packet "
1278  "payloads and stream. If you meant to have the offset/"
1279  "depth checked against just the payload, you can update "
1280  "the signature as \"alert tcp-pkt...\"\n");
1281  }
1282  if (warn_offset_depth_alproto) {
1283  fprintf(rule_engine_analysis_FD, " Warning: Rule has "
1284  "offset/depth set along with a match on a specific "
1285  "app layer protocol - %d. This can lead to FNs if we "
1286  "have a offset/depth content match on a packet payload "
1287  "before we can detect the app layer protocol for the "
1288  "flow.\n", s->alproto);
1289  }
1290  if (warn_non_alproto_fp_for_alproto_sig) {
1291  fprintf(rule_engine_analysis_FD, " Warning: Rule app layer "
1292  "protocol is http, but the fast_pattern is set on the raw "
1293  "stream. Consider adding fast_pattern over a http "
1294  "buffer for increased performance.");
1295  }
1296  if (warn_no_direction) {
1297  fprintf(rule_engine_analysis_FD, " Warning: Rule has no direction indicator.\n");
1298  }
1299  if (warn_both_direction) {
1300  fprintf(rule_engine_analysis_FD, " Warning: Rule is inspecting both directions.\n");
1301  }
1302  if (rule_warning == 0) {
1303  fprintf(rule_engine_analysis_FD, " No warnings for this rule.\n");
1304  }
1305  fprintf(rule_engine_analysis_FD, "\n");
1306  }
1307  return;
1308 }
#define SIG_FLAG_FILESTORE
Definition: detect.h:241
MemBuffer * MemBufferCreateNew(uint32_t size)
Definition: util-buffer.c:32
void CleanupFPAnalyzer(void)
SigTableElmt sigmatch_table[DETECT_TBLSIZE]
Definition: detect.h:1403
DetectProto proto
Definition: detect.h:509
SignatureInitData * init_data
Definition: detect.h:560
#define DETECT_PROTO_IPV6
#define SIG_FLAG_PDONLY
Definition: detect.h:254
int PerCentEncodingMatch(uint8_t *content, uint8_t content_len)
Checks for % encoding in content.
#define SIG_FLAG_PREFILTER
Definition: detect.h:250
#define MemBufferWriteString(dst,...)
Write a string buffer to the Membuffer dst.
Definition: util-buffer.h:162
SigMatch * prefilter_sm
Definition: detect.h:465
uint32_t flags
Definition: detect.h:493
char * msg
Definition: detect.h:549
uint32_t id
Definition: detect.h:525
#define DETECT_PROTO_ANY
#define DETECT_CONTENT_FAST_PATTERN
#define unlikely(expr)
Definition: util-optimize.h:35
uint8_t is_last
Definition: detect.h:335
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:881
#define SIG_FLAG_REQUIRE_STREAM
Definition: detect.h:231
#define DETECT_PERCENT_ENCODING_REGEX
Data needed for Match()
Definition: detect.h:333
uint16_t flags
Definition: detect-flow.h:38
#define DETECT_CONTENT_DISTANCE
#define SIG_FLAG_REQUIRE_FLOWVAR
Definition: detect.h:239
#define SIG_FLAG_REQUIRE_PACKET
Definition: detect.h:230
#define SIG_FLAG_TLSSTORE
Definition: detect.h:246
const char * name
Definition: detect.h:1160
#define SIG_FLAG_DEST_IS_TARGET
Definition: detect.h:258
Signature container.
Definition: detect.h:492
#define SIG_MASK_REQUIRE_ENGINE_EVENT
Definition: detect.h:281
#define DETECT_CONTENT_DEPTH
typedef __attribute__
DNP3 application header.
#define SIG_FLAG_APPLAYER
Definition: detect.h:225
#define SIG_FLAG_SRC_IS_TARGET
Definition: detect.h:256
struct SigMatch_ * next
Definition: detect.h:328
main detection engine ctx
Definition: detect.h:720
#define SIG_MASK_REQUIRE_FLAGS_INITDEINIT
Definition: detect.h:276
#define SIG_FLAG_DST_ANY
Definition: detect.h:219
#define SIG_FLAG_MPM_NEG
Definition: detect.h:233
#define SIG_FLAG_INIT_BIDIREC
Definition: detect.h:266
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:244
struct tm * SCLocalTime(time_t timep, struct tm *result)
Definition: util-time.c:232
#define SIG_FLAG_SP_ANY
Definition: detect.h:220
#define SIG_FLAG_IPONLY
Definition: detect.h:226
#define SIG_MASK_REQUIRE_FLOW
Definition: detect.h:275
void CleanupRuleAnalyzer(void)
const char * AppProtoToString(AppProto alproto)
Maps the ALPROTO_*, to its string equivalent.
struct FpPatternStats_ FpPatternStats
struct DetectEngineAppInspectionEngine_ * next
Definition: detect.h:426
#define SIG_FLAG_FLUSH
Definition: detect.h:235
#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:277
#define SIG_FLAG_TOSERVER
Definition: detect.h:243
#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:544
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:496
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:526
uint8_t type
Definition: detect.h:325
#define DETECT_CONTENT_FAST_PATTERN_ONLY
#define SIG_FLAG_INIT_STATE_MATCH
Definition: detect.h:269
#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:486
void EngineAnalysisRulesFailure(char *line, char *file, int lineno)
#define SIG_MASK_REQUIRE_PAYLOAD
Definition: detect.h:274
#define DETECT_CONTENT_MPM
Definition: conf.h:32
void EngineAnalysisFP(const DetectEngineCtx *de_ctx, const Signature *s, char *line)
SigMatchCtx * ctx
Definition: detect.h:327
const char * ConfigGetLogDirectory()
Definition: util-conf.c:36
#define SCMalloc(a)
Definition: util-mem.h:174
#define SCLogInfo(...)
Macro used to log INFORMATIONAL messages.
Definition: util-debug.h:254
uint8_t type
Definition: detect.h:334
#define DETECT_CONTENT_NEGATED
char * sig_str
Definition: detect.h:558
#define SCFree(a)
Definition: util-mem.h:236
#define SIG_FLAG_NOALERT
Definition: detect.h:223
#define SIG_FLAG_DSIZE
Definition: detect.h:224
uint32_t init_flags
Definition: detect.h:456
#define SCMutex
DetectEngineAppInspectionEngine * app_inspect
Definition: detect.h:540
#define SCMutexLock(mut)
uint32_t rev
Definition: detect.h:527
const char * DetectBufferTypeGetDescriptionById(const DetectEngineCtx *de_ctx, const int id)
#define SIG_FLAG_BYPASS
Definition: detect.h:248
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:221
#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:501
int SigMatchListSMBelongsTo(const Signature *s, const SigMatch *key_sm)
Definition: detect-parse.c:555
#define DETECT_FLOW_FLAG_NOSTREAM
Definition: detect-flow.h:33
#define SIG_FLAG_SRC_ANY
Definition: detect.h:218
#define SIG_MASK_REQUIRE_DCERPC
Definition: detect.h:279
const char * DetectBufferTypeGetNameById(const DetectEngineCtx *de_ctx, const int id)
#define SIG_MASK_REQUIRE_NO_PAYLOAD
Definition: detect.h:278
SigMatch * mpm_sm
Definition: detect.h:463
#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:324
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:336
#define SCMUTEX_INITIALIZER