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  int ov[MAX_SUBSTRINGS];
162  const char *str_ptr = NULL;
163 
164  ret = DetectParsePcreExec(&parse_regex, tagstr, 0, 0, ov, MAX_SUBSTRINGS);
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 = pcre_get_substring((char *)tagstr, ov, MAX_SUBSTRINGS, 1, &str_ptr);
171  if (res < 0 || str_ptr == NULL) {
172  SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_get_substring 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  pcre_free_substring(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 = pcre_get_substring((char *)tagstr, ov, MAX_SUBSTRINGS, 3, &str_ptr);
195  if (res < 0 || str_ptr == NULL) {
196  SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_get_substring failed");
197  goto error;
198  }
199 
200  /* count */
201  if (StringParseUint32(&td.count, 10, strlen(str_ptr),
202  str_ptr) <= 0) {
203  SCLogError(SC_ERR_INVALID_VALUE, "Invalid argument for count. Must be a value in the range of 0 to %"PRIu32" (%s)", UINT32_MAX, tagstr);
204  goto error;
205  }
206 
207  pcre_free_substring(str_ptr);
208  str_ptr = NULL;
209 
210  res = pcre_get_substring((char *)tagstr, ov, MAX_SUBSTRINGS, 4, &str_ptr);
211  if (res < 0 || str_ptr == NULL) {
212  SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_get_substring failed");
213  goto error;
214  }
215 
216  /* metric */
217  if (strcasecmp("packets", str_ptr) == 0) {
221  /* TODO: load DETECT_TAG_MAX_PKTS from config */
222  } else if (strcasecmp("seconds", str_ptr) == 0) {
224  } else if (strcasecmp("bytes", str_ptr) == 0) {
226  } else {
227  SCLogError(SC_ERR_INVALID_VALUE, "Invalid argument metric. Must be one of \"seconds\", \"packets\" or \"bytes\" (%s)", tagstr);
228  goto error;
229  }
230 
231  pcre_free_substring(str_ptr);
232  str_ptr = NULL;
233 
234  /* if specified, overwrite it */
235  if (ret == 7) {
236  res = pcre_get_substring((char *)tagstr, ov, MAX_SUBSTRINGS, 6, &str_ptr);
237  if (res < 0 || str_ptr == NULL) {
238  SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_get_substring failed");
239  goto error;
240  }
241 
242  /* metric */
243  if (strcasecmp("src", str_ptr) == 0) {
245  } else if (strcasecmp("dst", str_ptr) == 0) {
247  } else {
248  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);
249  goto error;
250  }
251 
252  if (td.type != DETECT_TAG_TYPE_HOST) {
253  SCLogWarning(SC_ERR_INVALID_VALUE, "Argument direction doesn't make sense for type \"session\" (%s [%"PRIu8"])", tagstr, td.type);
254  }
255 
256  pcre_free_substring(str_ptr);
257  str_ptr = NULL;
258  }
259  }
260 
261  DetectTagData *real_td = SCMalloc(sizeof(DetectTagData));
262  if (unlikely(real_td == NULL)) {
263  SCLogError(SC_ERR_MEM_ALLOC, "Error allocating memory");
264  goto error;
265  }
266 
267  memcpy(real_td, &td, sizeof(DetectTagData));
268  return real_td;
269 
270 error:
271  if (str_ptr != NULL)
272  pcre_free_substring(str_ptr);
273  return NULL;
274 }
275 
276 /**
277  * \brief this function is used to add the parsed tag data into the current signature
278  *
279  * \param de_ctx pointer to the Detection Engine Context
280  * \param s pointer to the Current Signature
281  * \param tagstr pointer to the user provided tag options
282  *
283  * \retval 0 on Success
284  * \retval -1 on Failure
285  */
286 int DetectTagSetup(DetectEngineCtx *de_ctx, Signature *s, const char *tagstr)
287 {
288  DetectTagData *td = DetectTagParse(tagstr);
289  if (td == NULL)
290  return -1;
291 
292  SigMatch *sm = SigMatchAlloc();
293  if (sm == NULL) {
295  return -1;
296  }
297 
298  sm->type = DETECT_TAG;
299  sm->ctx = (SigMatchCtx *)td;
300 
301  /* Append it to the list of tags */
303  return 0;
304 }
305 
306 /** \internal
307  * \brief this function will free memory associated with
308  * DetectTagDataEntry
309  *
310  * \param td pointer to DetectTagDataEntry
311  */
312 static void DetectTagDataEntryFree(void *ptr)
313 {
314  if (ptr != NULL) {
316  SCFree(dte);
317  }
318 }
319 
320 
321 /**
322  * \brief this function will free all the entries of a list
323  * DetectTagDataEntry
324  *
325  * \param td pointer to DetectTagDataEntryList
326  */
327 void DetectTagDataListFree(void *ptr)
328 {
329  if (ptr != NULL) {
330  DetectTagDataEntry *entry = ptr;
331 
332  while (entry != NULL) {
333  DetectTagDataEntry *next_entry = entry->next;
334  DetectTagDataEntryFree(entry);
335  (void) SC_ATOMIC_SUB(num_tags, 1);
336  entry = next_entry;
337  }
338  }
339 }
340 
341 /**
342  * \brief this function will free memory associated with DetectTagData
343  *
344  * \param td pointer to DetectTagData
345  */
347 {
348  DetectTagData *td = (DetectTagData *)ptr;
349  SCFree(td);
350 }
351 
352 #ifdef UNITTESTS
353 
354 /**
355  * \test DetectTagTestParse01 is a test to make sure that we return "something"
356  * when given valid tag opt
357  */
358 static int DetectTagTestParse01(void)
359 {
360  int result = 0;
361  DetectTagData *td = NULL;
362  td = DetectTagParse("session, 123, packets");
363  if (td != NULL && td->type == DETECT_TAG_TYPE_SESSION
364  && td->count == 123
365  && td->metric == DETECT_TAG_METRIC_PACKET) {
366  DetectTagDataFree(NULL, td);
367  result = 1;
368  }
369 
370  return result;
371 }
372 
373 /**
374  * \test DetectTagTestParse02 is a test to check that we parse tag correctly
375  */
376 static int DetectTagTestParse02(void)
377 {
378  int result = 0;
379  DetectTagData *td = NULL;
380  td = DetectTagParse("host, 200, bytes, src");
381  if (td != NULL && td->type == DETECT_TAG_TYPE_HOST
382  && td->count == 200
384  && td->direction == DETECT_TAG_DIR_SRC) {
385  result = 1;
386  DetectTagDataFree(NULL, td);
387  }
388 
389  return result;
390 }
391 
392 /**
393  * \test DetectTagTestParse03 is a test for setting the stateless tag opt
394  */
395 static int DetectTagTestParse03(void)
396 {
397  int result = 0;
398  DetectTagData *td = NULL;
399  td = DetectTagParse("host, 200, bytes, dst");
400  if (td != NULL && td->type == DETECT_TAG_TYPE_HOST
401  && td->count == 200
403  && td->direction == DETECT_TAG_DIR_DST) {
404  result = 1;
405  DetectTagDataFree(NULL, td);
406  }
407 
408  return result;
409 }
410 
411 /**
412  * \test DetectTagTestParse04 is a test for default opts
413  */
414 static int DetectTagTestParse04(void)
415 {
416  int result = 0;
417  DetectTagData *td = NULL;
418  td = DetectTagParse("session");
419  if (td != NULL && td->type == DETECT_TAG_TYPE_SESSION
420  && td->count == DETECT_TAG_MAX_PKTS
421  && td->metric == DETECT_TAG_METRIC_PACKET) {
422  result = 1;
423  DetectTagDataFree(NULL, td);
424  }
425 
426  return result;
427 }
428 
429 /**
430  * \test DetectTagTestParse05 is a test for default opts
431  */
432 static int DetectTagTestParse05(void)
433 {
434  int result = 0;
435  DetectTagData *td = NULL;
436  td = DetectTagParse("host");
437  if (td != NULL && td->type == DETECT_TAG_TYPE_HOST
438  && td->count == DETECT_TAG_MAX_PKTS
440  && td->direction == DETECT_TAG_DIR_DST) {
441  result = 1;
442  DetectTagDataFree(NULL, td);
443  }
444 
445  return result;
446 }
447 
448 /**
449  * \brief this function registers unit tests for DetectTag
450  */
451 void DetectTagRegisterTests(void)
452 {
453  UtRegisterTest("DetectTagTestParse01", DetectTagTestParse01);
454  UtRegisterTest("DetectTagTestParse02", DetectTagTestParse02);
455  UtRegisterTest("DetectTagTestParse03", DetectTagTestParse03);
456  UtRegisterTest("DetectTagTestParse04", DetectTagTestParse04);
457  UtRegisterTest("DetectTagTestParse05", DetectTagTestParse05);
458 
460 }
461 #endif /* UNITTESTS */
util-byte.h
detect-engine.h
SC_ERR_INVALID_VALUE
@ SC_ERR_INVALID_VALUE
Definition: util-error.h:160
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1201
flow-util.h
DetectTagDataEntry_::last_ts
uint32_t last_ts
Definition: detect-tag.h:87
SigTableElmt_::name
const char * name
Definition: detect.h:1211
MAX_SUBSTRINGS
#define MAX_SUBSTRINGS
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
DETECT_TAG_METRIC_SECONDS
@ DETECT_TAG_METRIC_SECONDS
Definition: detect-tag.h:59
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:298
DetectTagDataEntry_
Definition: detect-tag.h:73
threads.h
DetectTagDataEntry_::sid
uint32_t sid
Definition: detect-tag.h:80
SigTableElmt_::flags
uint16_t flags
Definition: detect.h:1205
DetectEngineCtx_
main detection engine ctx
Definition: detect.h:767
DetectTagDataListFree
void DetectTagDataListFree(void *ptr)
this function will free all the entries of a list DetectTagDataEntry
Definition: detect-tag.c:327
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:1196
util-unittest.h
DetectTagDataEntry_::flags
uint8_t flags
Definition: detect-tag.h:74
util-unittest-helper.h
DETECT_TAG_DIR_SRC
@ DETECT_TAG_DIR_SRC
Definition: detect-tag.h:52
DetectTagDataEntry_::gid
uint32_t gid
Definition: detect-tag.h:81
Signature_::gid
uint32_t gid
Definition: detect.h:562
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:1010
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:2493
DETECT_TAG_METRIC_BYTES
@ DETECT_TAG_METRIC_BYTES
Definition: detect-tag.h:60
detect.h
DetectTagData_::metric
uint32_t metric
Definition: detect-tag.h:69
util-time.h
app-layer-parser.h
SigMatch_::ctx
SigMatchCtx * ctx
Definition: detect.h:323
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:282
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)
DetectParsePcreExec
int DetectParsePcreExec(DetectParseRegex *parse_regex, const char *str, int start_offset, int options, int *ovector, int ovector_size)
Definition: detect-parse.c:2423
Packet_
Definition: decode.h:414
DETECT_TAG_TYPE_SESSION
@ DETECT_TAG_TYPE_SESSION
Definition: detect-tag.h:46
stream-tcp-private.h
DETECT_TAG_TYPE_HOST
@ DETECT_TAG_TYPE_HOST
Definition: detect-tag.h:47
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:1179
SigMatchAlloc
SigMatch * SigMatchAlloc(void)
Definition: detect-parse.c:235
DETECT_TAG_DIR_DST
@ DETECT_TAG_DIR_DST
Definition: detect-tag.h:53
SigMatch_::type
uint8_t type
Definition: detect.h:321
SigMatchCtx_
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition: detect.h:315
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
StringParseUint32
int StringParseUint32(uint32_t *res, int base, uint16_t len, const char *str)
Definition: util-byte.c:313
Packet_::flow
struct Flow_ * flow
Definition: decode.h:451
Packet_::ts
struct timeval ts
Definition: decode.h:457
suricata-common.h
sigmatch_table
SigTableElmt sigmatch_table[DETECT_TBLSIZE]
Definition: detect-parse.c:73
DetectParseRegex_
Definition: detect-parse.h:42
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:57
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
DETECT_TAG_METRIC_PACKET
@ DETECT_TAG_METRIC_PACKET
Definition: detect-tag.h:58
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:561
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:528
SigMatch_
a single match condition for a signature
Definition: detect.h:320
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:1382
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:346
SigTableElmt_::RegisterTests
void(* RegisterTests)(void)
Definition: detect.h:1203