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