suricata
detect-tag.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2020 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 detect-tag.c
20  *
21  * \author Pablo Rincon <pablo.rincon.crespo@gmail.com>
22  * \author Victor Julien <victor@inliniac.net>
23  *
24  * Implements the tag keyword
25  *
26  */
27 
28 #include "suricata-common.h"
29 #include "detect.h"
30 #include "detect-parse.h"
31 #include "detect-tag.h"
32 #include "detect-engine-tag.h"
33 #include "detect-engine.h"
34 #include "detect-engine-state.h"
35 #include "app-layer-parser.h"
36 
37 #include "decode.h"
38 
39 #include "flow.h"
40 #include "flow-var.h"
41 #include "flow-util.h"
42 #include "stream-tcp-private.h"
43 
44 #include "util-time.h"
45 #include "util-byte.h"
46 #include "util-unittest.h"
47 #include "util-unittest-helper.h"
48 #include "util-debug.h"
49 #include "threads.h"
50 
51 SC_ATOMIC_EXTERN(unsigned int, num_tags);
52 
53 /* format: tag: <type>, <count>, <metric>, [direction]; */
54 #define PARSE_REGEX "^\\s*(host|session)\\s*(,\\s*(\\d+)\\s*,\\s*(packets|bytes|seconds)\\s*(,\\s*(src|dst))?\\s*)?$"
55 
56 static DetectParseRegex parse_regex;
57 
58 static int DetectTagMatch(DetectEngineThreadCtx *, Packet *,
59  const Signature *, const SigMatchCtx *);
60 static int DetectTagSetup(DetectEngineCtx *, Signature *, const char *);
61 #ifdef UNITTESTS
62 static void DetectTagRegisterTests(void);
63 #endif
64 void DetectTagDataFree(DetectEngineCtx *, void *);
65 
66 /**
67  * \brief Registration function for keyword tag
68  */
70 {
72  sigmatch_table[DETECT_TAG].Match = DetectTagMatch;
73  sigmatch_table[DETECT_TAG].Setup = DetectTagSetup;
75 #ifdef UNITTESTS
76  sigmatch_table[DETECT_TAG].RegisterTests = DetectTagRegisterTests;
77 #endif
79 
80  DetectSetupParseRegexes(PARSE_REGEX, &parse_regex);
81 }
82 
83 /**
84  * \brief This function is used to setup a tag for session/host
85  *
86  * \param t pointer to thread vars
87  * \param det_ctx pointer to the pattern matcher thread
88  * \param p pointer to the current packet
89  * \param m pointer to the sigmatch that we will cast into DetectTagData
90  *
91  * \retval 0 no match
92  * \retval 1 match
93  */
94 static int DetectTagMatch(DetectEngineThreadCtx *det_ctx, Packet *p,
95  const Signature *s, const SigMatchCtx *ctx)
96 {
97  const DetectTagData *td = (const DetectTagData *)ctx;
99  memset(&tde, 0, sizeof(DetectTagDataEntry));
100 
101  switch (td->type) {
103 #ifdef DEBUG
105 #endif
106 
107  tde.sid = s->id;
108  tde.gid = s->gid;
109  tde.last_ts = tde.first_ts = SCTIME_SECS(p->ts);
110  tde.metric = td->metric;
111  tde.count = td->count;
112  if (td->direction == DETECT_TAG_DIR_SRC)
114  else if (td->direction == DETECT_TAG_DIR_DST)
116 
117  SCLogDebug("Tagging Host with sid %"PRIu32":%"PRIu32"", s->id, s->gid);
118  TagHashAddTag(&tde, p);
119  break;
121  if (p->flow != NULL) {
122  SCLogDebug("Setting up tag for flow");
123  /* If it already exists it will be updated */
124  tde.sid = s->id;
125  tde.gid = s->gid;
126  tde.last_ts = tde.first_ts = SCTIME_SECS(p->ts);
127  tde.metric = td->metric;
128  tde.count = td->count;
129 
130  SCLogDebug("Adding to or updating flow; first_ts %u count %u",
131  tde.first_ts, tde.count);
132  TagFlowAdd(p, &tde);
133  } else {
134  SCLogDebug("No flow to append the session tag");
135  }
136  break;
137 #ifdef DEBUG
138  default:
139  SCLogDebug("unknown type of a tag keyword (not session nor host)");
140  BUG_ON(1);
141  break;
142 #endif
143  }
144 
145  return 1;
146 }
147 
148 /**
149  * \brief This function is used to parse tag options passed to tag keyword
150  *
151  * \param tagstr Pointer to the user provided tag options
152  *
153  * \retval td pointer to DetectTagData on success
154  * \retval NULL on failure
155  */
156 static DetectTagData *DetectTagParse(const char *tagstr)
157 {
158  DetectTagData td;
159  int ret = 0, res = 0;
160  size_t pcre2_len;
161  const char *str_ptr = NULL;
162 
163  ret = DetectParsePcreExec(&parse_regex, tagstr, 0, 0);
164  if (ret < 1) {
165  SCLogError("parse error, ret %" PRId32 ", string %s", ret, tagstr);
166  goto error;
167  }
168 
169  res = pcre2_substring_get_bynumber(parse_regex.match, 1, (PCRE2_UCHAR8 **)&str_ptr, &pcre2_len);
170  if (res < 0 || str_ptr == NULL) {
171  SCLogError("pcre2_substring_get_bynumber failed");
172  goto error;
173  }
174 
175  /* Type */
176  if (strcasecmp("session", str_ptr) == 0) {
178  } else if (strcasecmp("host", str_ptr) == 0) {
180  } else {
181  SCLogError("Invalid argument type. Must be session or host (%s)", tagstr);
182  goto error;
183  }
184  pcre2_substring_free((PCRE2_UCHAR *)str_ptr);
185  str_ptr = NULL;
186 
187  /* default tag is 256 packets from session or dst host */
191 
192  if (ret > 4) {
193  res = pcre2_substring_get_bynumber(
194  parse_regex.match, 3, (PCRE2_UCHAR8 **)&str_ptr, &pcre2_len);
195  if (res < 0 || str_ptr == NULL) {
196  SCLogError("pcre2_substring_get_bynumber failed");
197  goto error;
198  }
199 
200  /* count */
201  if (StringParseUint32(&td.count, 10, strlen(str_ptr),
202  str_ptr) <= 0) {
203  SCLogError("Invalid argument for count. Must be a value in the range of 0 to %" PRIu32
204  " (%s)",
205  UINT32_MAX, tagstr);
206  goto error;
207  }
208 
209  pcre2_substring_free((PCRE2_UCHAR *)str_ptr);
210  str_ptr = NULL;
211 
212  res = pcre2_substring_get_bynumber(
213  parse_regex.match, 4, (PCRE2_UCHAR8 **)&str_ptr, &pcre2_len);
214  if (res < 0 || str_ptr == NULL) {
215  SCLogError("pcre2_substring_get_bynumber failed");
216  goto error;
217  }
218 
219  /* metric */
220  if (strcasecmp("packets", str_ptr) == 0) {
224  /* TODO: load DETECT_TAG_MAX_PKTS from config */
225  } else if (strcasecmp("seconds", str_ptr) == 0) {
227  } else if (strcasecmp("bytes", str_ptr) == 0) {
229  } else {
230  SCLogError(
231  "Invalid argument metric. Must be one of \"seconds\", \"packets\" or \"bytes\" "
232  "(%s)",
233  tagstr);
234  goto error;
235  }
236 
237  pcre2_substring_free((PCRE2_UCHAR *)str_ptr);
238  str_ptr = NULL;
239 
240  /* if specified, overwrite it */
241  if (ret == 7) {
242  res = pcre2_substring_get_bynumber(
243  parse_regex.match, 6, (PCRE2_UCHAR8 **)&str_ptr, &pcre2_len);
244  if (res < 0 || str_ptr == NULL) {
245  SCLogError("pcre2_substring_get_bynumber failed");
246  goto error;
247  }
248 
249  /* metric */
250  if (strcasecmp("src", str_ptr) == 0) {
252  } else if (strcasecmp("dst", str_ptr) == 0) {
254  } else {
255  SCLogError(
256  "Invalid argument direction. Must be one of \"src\" or \"dst\" (only valid "
257  "for tag host type, not sessions) (%s)",
258  tagstr);
259  goto error;
260  }
261 
262  if (td.type != DETECT_TAG_TYPE_HOST) {
263  SCLogWarning(
264  "Argument direction doesn't make sense for type \"session\" (%s [%" PRIu8
265  "])",
266  tagstr, td.type);
267  }
268 
269  pcre2_substring_free((PCRE2_UCHAR *)str_ptr);
270  str_ptr = NULL;
271  }
272  }
273 
274  DetectTagData *real_td = SCMalloc(sizeof(DetectTagData));
275  if (unlikely(real_td == NULL)) {
276  SCLogError("Error allocating memory");
277  goto error;
278  }
279 
280  memcpy(real_td, &td, sizeof(DetectTagData));
281  return real_td;
282 
283 error:
284  if (str_ptr != NULL)
285  pcre2_substring_free((PCRE2_UCHAR *)str_ptr);
286  return NULL;
287 }
288 
289 /**
290  * \brief this function is used to add the parsed tag data into the current signature
291  *
292  * \param de_ctx pointer to the Detection Engine Context
293  * \param s pointer to the Current Signature
294  * \param tagstr pointer to the user provided tag options
295  *
296  * \retval 0 on Success
297  * \retval -1 on Failure
298  */
299 int DetectTagSetup(DetectEngineCtx *de_ctx, Signature *s, const char *tagstr)
300 {
301  DetectTagData *td = DetectTagParse(tagstr);
302  if (td == NULL)
303  return -1;
304 
305  SigMatch *sm = SigMatchAlloc();
306  if (sm == NULL) {
308  return -1;
309  }
310 
311  sm->type = DETECT_TAG;
312  sm->ctx = (SigMatchCtx *)td;
313 
314  /* Append it to the list of tags */
316  return 0;
317 }
318 
319 /** \internal
320  * \brief this function will free memory associated with
321  * DetectTagDataEntry
322  *
323  * \param td pointer to DetectTagDataEntry
324  */
325 static void DetectTagDataEntryFree(void *ptr)
326 {
327  if (ptr != NULL) {
329  SCFree(dte);
330  }
331 }
332 
333 
334 /**
335  * \brief this function will free all the entries of a list
336  * DetectTagDataEntry
337  *
338  * \param td pointer to DetectTagDataEntryList
339  */
340 void DetectTagDataListFree(void *ptr)
341 {
342  if (ptr != NULL) {
343  DetectTagDataEntry *entry = ptr;
344 
345  while (entry != NULL) {
346  DetectTagDataEntry *next_entry = entry->next;
347  DetectTagDataEntryFree(entry);
348  (void) SC_ATOMIC_SUB(num_tags, 1);
349  entry = next_entry;
350  }
351  }
352 }
353 
354 /**
355  * \brief this function will free memory associated with DetectTagData
356  *
357  * \param td pointer to DetectTagData
358  */
360 {
361  DetectTagData *td = (DetectTagData *)ptr;
362  SCFree(td);
363 }
364 
365 #ifdef UNITTESTS
366 
367 /**
368  * \test DetectTagTestParse01 is a test to make sure that we return "something"
369  * when given valid tag opt
370  */
371 static int DetectTagTestParse01(void)
372 {
373  int result = 0;
374  DetectTagData *td = NULL;
375  td = DetectTagParse("session, 123, packets");
376  if (td != NULL && td->type == DETECT_TAG_TYPE_SESSION
377  && td->count == 123
378  && td->metric == DETECT_TAG_METRIC_PACKET) {
379  DetectTagDataFree(NULL, td);
380  result = 1;
381  }
382 
383  return result;
384 }
385 
386 /**
387  * \test DetectTagTestParse02 is a test to check that we parse tag correctly
388  */
389 static int DetectTagTestParse02(void)
390 {
391  int result = 0;
392  DetectTagData *td = NULL;
393  td = DetectTagParse("host, 200, bytes, src");
394  if (td != NULL && td->type == DETECT_TAG_TYPE_HOST
395  && td->count == 200
397  && td->direction == DETECT_TAG_DIR_SRC) {
398  result = 1;
399  DetectTagDataFree(NULL, td);
400  }
401 
402  return result;
403 }
404 
405 /**
406  * \test DetectTagTestParse03 is a test for setting the stateless tag opt
407  */
408 static int DetectTagTestParse03(void)
409 {
410  int result = 0;
411  DetectTagData *td = NULL;
412  td = DetectTagParse("host, 200, bytes, dst");
413  if (td != NULL && td->type == DETECT_TAG_TYPE_HOST
414  && td->count == 200
416  && td->direction == DETECT_TAG_DIR_DST) {
417  result = 1;
418  DetectTagDataFree(NULL, td);
419  }
420 
421  return result;
422 }
423 
424 /**
425  * \test DetectTagTestParse04 is a test for default opts
426  */
427 static int DetectTagTestParse04(void)
428 {
429  int result = 0;
430  DetectTagData *td = NULL;
431  td = DetectTagParse("session");
432  if (td != NULL && td->type == DETECT_TAG_TYPE_SESSION
433  && td->count == DETECT_TAG_MAX_PKTS
434  && td->metric == DETECT_TAG_METRIC_PACKET) {
435  result = 1;
436  DetectTagDataFree(NULL, td);
437  }
438 
439  return result;
440 }
441 
442 /**
443  * \test DetectTagTestParse05 is a test for default opts
444  */
445 static int DetectTagTestParse05(void)
446 {
447  int result = 0;
448  DetectTagData *td = NULL;
449  td = DetectTagParse("host");
450  if (td != NULL && td->type == DETECT_TAG_TYPE_HOST
451  && td->count == DETECT_TAG_MAX_PKTS
453  && td->direction == DETECT_TAG_DIR_DST) {
454  result = 1;
455  DetectTagDataFree(NULL, td);
456  }
457 
458  return result;
459 }
460 
461 /**
462  * \brief this function registers unit tests for DetectTag
463  */
464 void DetectTagRegisterTests(void)
465 {
466  UtRegisterTest("DetectTagTestParse01", DetectTagTestParse01);
467  UtRegisterTest("DetectTagTestParse02", DetectTagTestParse02);
468  UtRegisterTest("DetectTagTestParse03", DetectTagTestParse03);
469  UtRegisterTest("DetectTagTestParse04", DetectTagTestParse04);
470  UtRegisterTest("DetectTagTestParse05", DetectTagTestParse05);
471 
473 }
474 #endif /* UNITTESTS */
util-byte.h
DetectParseRegex::match
pcre2_match_data * match
Definition: detect-parse.h:47
DETECT_TAG_METRIC_PACKET
@ DETECT_TAG_METRIC_PACKET
Definition: detect-tag.h:56
detect-engine.h
DetectParsePcreExec
int DetectParsePcreExec(DetectParseRegex *parse_regex, const char *str, int start_offset, int options)
Definition: detect-parse.c:2477
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1230
flow-util.h
DetectParseRegex
Definition: detect-parse.h:44
DetectTagDataEntry_::last_ts
uint32_t last_ts
Definition: detect-tag.h:85
SigTableElmt_::name
const char * name
Definition: detect.h:1240
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
UtRegisterTest
void UtRegisterTest(const char *name, int(*TestFn)(void))
Register unit test.
Definition: util-unittest.c:103
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:269
DetectTagDataEntry_
Definition: detect-tag.h:71
DETECT_TAG_TYPE_SESSION
@ DETECT_TAG_TYPE_SESSION
Definition: detect-tag.h:44
threads.h
DETECT_TAG_METRIC_BYTES
@ DETECT_TAG_METRIC_BYTES
Definition: detect-tag.h:58
DetectTagDataEntry_::sid
uint32_t sid
Definition: detect-tag.h:78
SigTableElmt_::flags
uint16_t flags
Definition: detect.h:1234
DetectEngineCtx_
main detection engine ctx
Definition: detect.h:787
DetectTagDataListFree
void DetectTagDataListFree(void *ptr)
this function will free all the entries of a list DetectTagDataEntry
Definition: detect-tag.c:340
DETECT_TAG_METRIC_SECONDS
@ DETECT_TAG_METRIC_SECONDS
Definition: detect-tag.h:57
DETECT_TAG_TYPE_HOST
@ DETECT_TAG_TYPE_HOST
Definition: detect-tag.h:45
TAG_ENTRY_FLAG_DIR_SRC
#define TAG_ENTRY_FLAG_DIR_SRC
Definition: detect-tag.h:93
DetectTagDataEntry_::metric
uint8_t metric
Definition: detect-tag.h:73
detect-tag.h
DetectTagData_::direction
uint8_t direction
Definition: detect-tag.h:65
SigTableElmt_::Setup
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition: detect.h:1225
util-unittest.h
DetectTagDataEntry_::flags
uint8_t flags
Definition: detect-tag.h:72
util-unittest-helper.h
DetectTagDataEntry_::gid
uint32_t gid
Definition: detect-tag.h:79
Signature_::gid
uint32_t gid
Definition: detect.h:577
DetectTagDataEntry_::count
uint32_t count
Definition: detect-tag.h:77
decode.h
util-debug.h
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:17
TAG_ENTRY_FLAG_DIR_DST
#define TAG_ENTRY_FLAG_DIR_DST
Definition: detect-tag.h:94
DetectEngineThreadCtx_
Definition: detect.h:1027
Packet_::ts
SCTime_t ts
Definition: decode.h:471
DetectTagDataEntry_::first_ts
uint32_t first_ts
Definition: detect-tag.h:84
DetectSetupParseRegexes
void DetectSetupParseRegexes(const char *parse_str, DetectParseRegex *detect_parse)
Definition: detect-parse.c:2598
detect.h
DETECT_TAG_DIR_DST
@ DETECT_TAG_DIR_DST
Definition: detect-tag.h:51
StringParseUint32
int StringParseUint32(uint32_t *res, int base, size_t len, const char *str)
Definition: util-byte.c:313
util-time.h
SCLogWarning
#define SCLogWarning(...)
Macro used to log WARNING messages.
Definition: util-debug.h:249
app-layer-parser.h
SigMatch_::ctx
SigMatchCtx * ctx
Definition: detect.h:318
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:289
detect-engine-tag.h
SC_ATOMIC_SUB
#define SC_ATOMIC_SUB(name, val)
sub a value from our atomic variable
Definition: util-atomic.h:342
SC_ATOMIC_EXTERN
SC_ATOMIC_EXTERN(unsigned int, num_tags)
Packet_
Definition: decode.h:428
DETECT_TAG_DIR_SRC
@ DETECT_TAG_DIR_SRC
Definition: detect-tag.h:50
stream-tcp-private.h
detect-engine-state.h
Data structures and function prototypes for keeping state for the detection engine.
SigTableElmt_::Match
int(* Match)(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *)
Definition: detect.h:1208
SigMatchAlloc
SigMatch * SigMatchAlloc(void)
Definition: detect-parse.c:241
SigMatchCtx_
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition: detect.h:310
DetectTagRegister
void DetectTagRegister(void)
Registration function for keyword tag.
Definition: detect-tag.c:69
DETECT_TAG_MAX_PKTS
#define DETECT_TAG_MAX_PKTS
Definition: detect-tag.h:40
Packet_::flow
struct Flow_ * flow
Definition: decode.h:465
suricata-common.h
SigMatch_::type
uint16_t type
Definition: detect.h:316
sigmatch_table
SigTableElmt sigmatch_table[DETECT_TBLSIZE]
Definition: detect-parse.c:76
SCTIME_SECS
#define SCTIME_SECS(t)
Definition: util-time.h:57
DETECT_TAG
@ DETECT_TAG
Definition: detect-engine-register.h:60
DETECT_SM_LIST_TMATCH
@ DETECT_SM_LIST_TMATCH
Definition: detect.h:91
SCMalloc
#define SCMalloc(sz)
Definition: util-mem.h:47
DetectTagData_::count
uint32_t count
Definition: detect-tag.h:66
DetectEngineTagRegisterTests
void DetectEngineTagRegisterTests(void)
this function registers unit tests for DetectTag
Definition: detect-engine-tag.c:1377
SCLogError
#define SCLogError(...)
Macro used to log ERROR messages.
Definition: util-debug.h:261
SCFree
#define SCFree(p)
Definition: util-mem.h:61
Signature_::id
uint32_t id
Definition: detect.h:576
TagFlowAdd
int TagFlowAdd(Packet *p, DetectTagDataEntry *tde)
This function is used to add a tag to a session (type session) or update it if it's already installed...
Definition: detect-engine-tag.c:124
detect-parse.h
Signature_
Signature container.
Definition: detect.h:542
SigMatch_
a single match condition for a signature
Definition: detect.h:315
TagHashAddTag
int TagHashAddTag(DetectTagDataEntry *tde, Packet *p)
Add a tag entry for a host. If it already exist, update it.
Definition: detect-engine-tag.c:181
DetectTagDataEntry_::next
struct DetectTagDataEntry_ * next
Definition: detect-tag.h:89
DetectTagData_
Definition: detect-tag.h:63
DetectTagData_::type
uint8_t type
Definition: detect-tag.h:64
PARSE_REGEX
#define PARSE_REGEX
Definition: detect-tag.c:54
DetectTagData_::metric
uint8_t metric
Definition: detect-tag.h:67
flow.h
flow-var.h
SIGMATCH_IPONLY_COMPAT
#define SIGMATCH_IPONLY_COMPAT
Definition: detect.h:1427
SigMatchAppendSMToList
void SigMatchAppendSMToList(Signature *s, SigMatch *new, int list)
Append a SigMatch to the list type.
Definition: detect-parse.c:356
DetectTagDataFree
void DetectTagDataFree(DetectEngineCtx *, void *)
this function will free memory associated with DetectTagData
Definition: detect-tag.c:359
SigTableElmt_::RegisterTests
void(* RegisterTests)(void)
Definition: detect.h:1232