suricata
detect-dataset.c
Go to the documentation of this file.
1 /* Copyright (C) 2018-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
20  *
21  * \author Victor Julien <victor@inliniac.net>
22  *
23  * Implements the dataset keyword
24  */
25 
26 #include "suricata-common.h"
27 #include "decode.h"
28 #include "detect.h"
29 #include "threads.h"
30 #include "datasets.h"
31 #include "detect-dataset.h"
32 
33 #include "detect-parse.h"
34 #include "detect-engine.h"
35 #include "detect-engine-mpm.h"
36 #include "detect-engine-state.h"
37 
38 #include "util-debug.h"
39 #include "util-print.h"
40 #include "util-misc.h"
41 #include "util-path.h"
42 #include "util-conf.h"
43 
45  const Signature *, const SigMatchCtx *);
46 static int DetectDatasetSetup (DetectEngineCtx *, Signature *, const char *);
47 void DetectDatasetFree (DetectEngineCtx *, void *);
48 
50 {
51  sigmatch_table[DETECT_DATASET].name = "dataset";
52  sigmatch_table[DETECT_DATASET].desc = "match sticky buffer against datasets (experimental)";
53  sigmatch_table[DETECT_DATASET].url = "/rules/dataset-keywords.html#dataset";
54  sigmatch_table[DETECT_DATASET].Setup = DetectDatasetSetup;
56 }
57 
58 /*
59  1 match
60  0 no match
61  -1 can't match
62  */
64  const DetectDatasetData *sd,
65  const uint8_t *data, const uint32_t data_len)
66 {
67  if (data == NULL || data_len == 0)
68  return 0;
69 
70  switch (sd->cmd) {
72  //PrintRawDataFp(stdout, data, data_len);
73  int r = DatasetLookup(sd->set, data, data_len);
74  SCLogDebug("r %d", r);
75  if (r == 1)
76  return 1;
77  break;
78  }
80  //PrintRawDataFp(stdout, data, data_len);
81  int r = DatasetLookup(sd->set, data, data_len);
82  SCLogDebug("r %d", r);
83  if (r < 1)
84  return 1;
85  break;
86  }
88  //PrintRawDataFp(stdout, data, data_len);
89  int r = DatasetAdd(sd->set, data, data_len);
90  if (r == 1)
91  return 1;
92  break;
93  }
94  default:
95  abort();
96  }
97  return 0;
98 }
99 
100 static int DetectDatasetParse(const char *str, char *cmd, int cmd_len, char *name, int name_len,
101  enum DatasetTypes *type, char *load, size_t load_size, char *save, size_t save_size,
102  uint64_t *memcap, uint32_t *hashsize)
103 {
104  bool cmd_set = false;
105  bool name_set = false;
106  bool load_set = false;
107  bool save_set = false;
108  bool state_set = false;
109 
110  char copy[strlen(str)+1];
111  strlcpy(copy, str, sizeof(copy));
112  char *xsaveptr = NULL;
113  char *key = strtok_r(copy, ",", &xsaveptr);
114  while (key != NULL) {
115  while (*key != '\0' && isblank(*key)) {
116  key++;
117  }
118  char *val = strchr(key, ' ');
119  if (val != NULL) {
120  *val++ = '\0';
121  while (*val != '\0' && isblank(*val)) {
122  val++;
123  SCLogDebug("cmd %s val %s", key, val);
124  }
125  } else {
126  SCLogDebug("cmd %s", key);
127  }
128 
129  if (strlen(key) == 0) {
130  goto next;
131  }
132 
133  if (!cmd_set) {
134  if (val && strlen(val) != 0) {
135  return -1;
136  }
137  strlcpy(cmd, key, cmd_len);
138  cmd_set = true;
139  } else if (!name_set) {
140  if (val && strlen(val) != 0) {
141  return -1;
142  }
143  strlcpy(name, key, name_len);
144  name_set = true;
145  } else {
146  if (val == NULL) {
147  return -1;
148  }
149 
150  if (strcmp(key, "type") == 0) {
151  SCLogDebug("type %s", val);
152 
153  if (strcmp(val, "md5") == 0) {
155  } else if (strcmp(val, "sha256") == 0) {
157  } else if (strcmp(val, "string") == 0) {
159  } else if (strcmp(val, "ipv4") == 0) {
161  } else if (strcmp(val, "ipv6") == 0) {
163  } else if (strcmp(val, "ip") == 0) {
165  } else {
166  SCLogError(SC_ERR_INVALID_SIGNATURE, "bad type %s", val);
167  return -1;
168  }
169 
170  } else if (strcmp(key, "save") == 0) {
171  if (save_set) {
173  "'save' can only appear once");
174  return -1;
175  }
176  SCLogDebug("save %s", val);
177  strlcpy(save, val, save_size);
178  save_set = true;
179  } else if (strcmp(key, "load") == 0) {
180  if (load_set) {
182  "'load' can only appear once");
183  return -1;
184  }
185  SCLogDebug("load %s", val);
186  strlcpy(load, val, load_size);
187  load_set = true;
188  } else if (strcmp(key, "state") == 0) {
189  if (state_set) {
191  "'state' can only appear once");
192  return -1;
193  }
194  SCLogDebug("state %s", val);
195  strlcpy(load, val, load_size);
196  strlcpy(save, val, save_size);
197  state_set = true;
198  }
199  if (strcmp(key, "memcap") == 0) {
200  if (ParseSizeStringU64(val, memcap) < 0) {
202  "invalid value for memcap: %s,"
203  " resetting to default",
204  val);
205  *memcap = 0;
206  }
207  }
208  if (strcmp(key, "hashsize") == 0) {
209  if (ParseSizeStringU32(val, hashsize) < 0) {
211  "invalid value for hashsize: %s,"
212  " resetting to default",
213  val);
214  *hashsize = 0;
215  }
216  }
217  }
218 
219  SCLogDebug("key: %s, value: %s", key, val);
220 
221  next:
222  key = strtok_r(NULL, ",", &xsaveptr);
223  }
224 
225  if ((load_set || save_set) && state_set) {
227  "'state' can not be mixed with 'load' and 'save'");
228  return -1;
229  }
230 
231  /* Trim trailing whitespace. */
232  while (strlen(name) > 0 && isblank(name[strlen(name) - 1])) {
233  name[strlen(name) - 1] = '\0';
234  }
235 
236  /* Validate name, spaces are not allowed. */
237  for (size_t i = 0; i < strlen(name); i++) {
238  if (isblank(name[i])) {
240  "spaces not allowed in dataset names");
241  return 0;
242  }
243  }
244 
245  return 1;
246 }
247 
248 /** \brief wrapper around dirname that does leave input untouched */
249 static void GetDirName(const char *in, char *out, size_t outs)
250 {
251  if (strlen(in) == 0) {
252  return;
253  }
254 
255  size_t size = strlen(in) + 1;
256  char tmp[size];
257  strlcpy(tmp, in, size);
258 
259  char *dir = dirname(tmp);
260  BUG_ON(dir == NULL);
261  strlcpy(out, dir, outs);
262  return;
263 }
264 
265 static int SetupLoadPath(const DetectEngineCtx *de_ctx,
266  char *load, size_t load_size)
267 {
268  SCLogDebug("load %s", load);
269 
270  if (PathIsAbsolute(load)) {
271  return 0;
272  }
273 
274  bool done = false;
275 #ifdef HAVE_LIBGEN_H
276  BUG_ON(de_ctx->rule_file == NULL);
277 
278  char dir[PATH_MAX] = "";
279  GetDirName(de_ctx->rule_file, dir, sizeof(dir));
280 
281  SCLogDebug("rule_file %s dir %s", de_ctx->rule_file, dir);
282  char path[PATH_MAX];
283  if (snprintf(path, sizeof(path), "%s/%s", dir, load) >= (int)sizeof(path)) // TODO windows path
284  return -1;
285 
286  if (SCPathExists(path)) {
287  done = true;
288  strlcpy(load, path, load_size);
289  SCLogDebug("using path '%s' (HAVE_LIBGEN_H)", load);
290  }
291 #endif
292  if (!done) {
293  char *loadp = DetectLoadCompleteSigPath(de_ctx, load);
294  if (loadp == NULL) {
295  return -1;
296  }
297  SCLogDebug("loadp %s", loadp);
298 
299  if (SCPathExists(loadp)) {
300  strlcpy(load, loadp, load_size);
301  SCLogDebug("using path '%s' (non-HAVE_LIBGEN_H)", load);
302  }
303  SCFree(loadp);
304  }
305  return 0;
306 }
307 
308 static int SetupSavePath(const DetectEngineCtx *de_ctx,
309  char *save, size_t save_size)
310 {
311  SCLogDebug("save %s", save);
312 
313  if (PathIsAbsolute(save)) {
314  return 0;
315  }
316 
317  // data dir
318  const char *dir = ConfigGetDataDirectory();
319  BUG_ON(dir == NULL); // should not be able to fail
320  char path[PATH_MAX];
321  if (snprintf(path, sizeof(path), "%s/%s", dir, save) >= (int)sizeof(path)) // TODO windows path
322  return -1;
323 
324  /* TODO check if location exists and is writable */
325 
326  strlcpy(save, path, save_size);
327 
328  return 0;
329 }
330 
331 int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr)
332 {
333  DetectDatasetData *cd = NULL;
334  SigMatch *sm = NULL;
335  uint8_t cmd = 0;
336  uint64_t memcap = 0;
337  uint32_t hashsize = 0;
338  char cmd_str[16] = "", name[DATASET_NAME_MAX_LEN + 1] = "";
340  char load[PATH_MAX] = "";
341  char save[PATH_MAX] = "";
342 
343  if (DetectBufferGetActiveList(de_ctx, s) == -1) {
345  "datasets are only supported for sticky buffers");
346  SCReturnInt(-1);
347  }
348 
349  int list = s->init_data->list;
350  if (list == DETECT_SM_LIST_NOTSET) {
352  "datasets are only supported for sticky buffers");
353  SCReturnInt(-1);
354  }
355 
356  if (!DetectDatasetParse(rawstr, cmd_str, sizeof(cmd_str), name, sizeof(name), &type, load,
357  sizeof(load), save, sizeof(save), &memcap, &hashsize)) {
358  return -1;
359  }
360 
361  if (strcmp(cmd_str,"isset") == 0) {
363  } else if (strcmp(cmd_str,"isnotset") == 0) {
365  } else if (strcmp(cmd_str,"set") == 0) {
367  } else if (strcmp(cmd_str,"unset") == 0) {
369  } else {
371  "dataset action \"%s\" is not supported.", cmd_str);
372  return -1;
373  }
374 
375  /* if just 'load' is set, we load data from the same dir as the
376  * rule file. If load+save is used, we use data dir */
377  if (strlen(save) == 0 && strlen(load) != 0) {
378  if (SetupLoadPath(de_ctx, load, sizeof(load)) != 0)
379  return -1;
380  /* if just 'save' is set, we use either full path or the
381  * data-dir */
382  } else if (strlen(save) != 0 && strlen(load) == 0) {
383  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
384  return -1;
385  /* use 'save' logic for 'state', but put the resulting
386  * path into 'load' as well. */
387  } else if (strlen(save) != 0 && strlen(load) != 0 &&
388  strcmp(save, load) == 0) {
389  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
390  return -1;
391  strlcpy(load, save, sizeof(load));
392  }
393 
394  SCLogDebug("name '%s' load '%s' save '%s'", name, load, save);
395  Dataset *set = DatasetGet(name, type, save, load, memcap, hashsize);
396  if (set == NULL) {
398  "failed to set up dataset '%s'.", name);
399  return -1;
400  }
401  if (set->hash && SC_ATOMIC_GET(set->hash->memcap_reached)) {
402  SCLogError(SC_ERR_THASH_INIT, "dataset too large for set memcap");
403  return -1;
404  }
405 
406  cd = SCCalloc(1, sizeof(DetectDatasetData));
407  if (unlikely(cd == NULL))
408  goto error;
409 
410  cd->set = set;
411  cd->cmd = cmd;
412 
413  SCLogDebug("cmd %s, name %s",
414  cmd_str, strlen(name) ? name : "(none)");
415 
416  /* Okay so far so good, lets get this into a SigMatch
417  * and put it in the Signature. */
418  sm = SigMatchAlloc();
419  if (sm == NULL)
420  goto error;
421 
422  sm->type = DETECT_DATASET;
423  sm->ctx = (SigMatchCtx *)cd;
424  SigMatchAppendSMToList(s, sm, list);
425  return 0;
426 
427 error:
428  if (cd != NULL)
429  SCFree(cd);
430  if (sm != NULL)
431  SCFree(sm);
432  return -1;
433 }
434 
436 {
438  if (fd == NULL)
439  return;
440 
441  SCFree(fd);
442 }
DetectDatasetData_
Definition: detect-dataset.h:36
SigTableElmt_::url
const char * url
Definition: detect.h:1238
detect-engine.h
DetectDatasetData_::cmd
uint8_t cmd
Definition: detect-dataset.h:38
SigTableElmt_::desc
const char * desc
Definition: detect.h:1237
SC_ERR_INVALID_VALUE
@ SC_ERR_INVALID_VALUE
Definition: util-error.h:160
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1225
SigTableElmt_::name
const char * name
Definition: detect.h:1235
DetectEngineCtx_::rule_file
char * rule_file
Definition: detect.h:889
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:296
ParseSizeStringU64
int ParseSizeStringU64(const char *size, uint64_t *res)
Definition: util-misc.c:200
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
Dataset::hash
THashTableContext * hash
Definition: datasets.h:46
threads.h
DETECT_DATASET_CMD_SET
#define DETECT_DATASET_CMD_SET
Definition: detect-dataset.h:29
DetectEngineCtx_
main detection engine ctx
Definition: detect.h:784
SC_ERR_INVALID_SIGNATURE
@ SC_ERR_INVALID_SIGNATURE
Definition: util-error.h:69
DATASET_TYPE_SHA256
@ DATASET_TYPE_SHA256
Definition: datasets.h:34
DetectDatasetData_::set
Dataset * set
Definition: detect-dataset.h:37
DetectBufferGetActiveList
int DetectBufferGetActiveList(DetectEngineCtx *de_ctx, Signature *s)
Definition: detect-engine.c:1312
SigTableElmt_::Setup
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition: detect.h:1220
DATASET_TYPE_IPV6
@ DATASET_TYPE_IPV6
Definition: datasets.h:36
hashsize
#define hashsize(n)
Definition: util-hash-lookup3.c:67
strlcpy
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: util-strlcpyu.c:43
DatasetGet
Dataset * DatasetGet(const char *name, enum DatasetTypes type, const char *save, const char *load, uint64_t memcap, uint32_t hashsize)
Definition: datasets.c:655
datasets.h
decode.h
util-debug.h
type
uint8_t type
Definition: decode-icmpv4.h:0
DatasetAdd
int DatasetAdd(Dataset *set, const uint8_t *data, const uint32_t data_len)
Definition: datasets.c:1559
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:17
DetectEngineThreadCtx_
Definition: detect.h:1024
SC_ERR_UNKNOWN_VALUE
@ SC_ERR_UNKNOWN_VALUE
Definition: util-error.h:159
DetectDatasetFree
void DetectDatasetFree(DetectEngineCtx *, void *)
Definition: detect-dataset.c:435
DATASET_TYPE_NOTSET
#define DATASET_TYPE_NOTSET
Definition: datasets.h:31
SignatureInitData_::list
int list
Definition: detect.h:516
util-print.h
detect-engine-mpm.h
detect.h
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:57
SigMatch_::ctx
SigMatchCtx * ctx
Definition: detect.h:316
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:289
DetectDatasetRegister
void DetectDatasetRegister(void)
Definition: detect-dataset.c:49
Packet_
Definition: decode.h:428
DETECT_DATASET_CMD_ISSET
#define DETECT_DATASET_CMD_ISSET
Definition: detect-dataset.h:32
Signature_::init_data
SignatureInitData * init_data
Definition: detect.h:610
DatasetLookup
int DatasetLookup(Dataset *set, const uint8_t *data, const uint32_t data_len)
see if data is part of the set
Definition: datasets.c:1324
DATASET_TYPE_IPV4
@ DATASET_TYPE_IPV4
Definition: datasets.h:35
detect-engine-state.h
Data structures and function prototypes for keeping state for the detection engine.
SigMatchAlloc
SigMatch * SigMatchAlloc(void)
Definition: detect-parse.c:238
SigMatchCtx_
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition: detect.h:308
DETECT_SM_LIST_NOTSET
#define DETECT_SM_LIST_NOTSET
Definition: detect.h:104
SCPathExists
bool SCPathExists(const char *path)
Check if a path exists.
Definition: util-path.c:169
DetectDatasetBufferMatch
int DetectDatasetBufferMatch(DetectEngineThreadCtx *det_ctx, const DetectDatasetData *sd, const uint8_t *data, const uint32_t data_len)
Definition: detect-dataset.c:63
DatasetTypes
DatasetTypes
Definition: datasets.h:30
util-conf.h
DETECT_DATASET_CMD_UNSET
#define DETECT_DATASET_CMD_UNSET
Definition: detect-dataset.h:30
suricata-common.h
SigMatch_::type
uint16_t type
Definition: detect.h:314
util-path.h
DATASET_NAME_MAX_LEN
#define DATASET_NAME_MAX_LEN
Definition: datasets.h:39
sigmatch_table
SigTableElmt sigmatch_table[DETECT_TBLSIZE]
Definition: detect-parse.c:76
PathIsAbsolute
int PathIsAbsolute(const char *path)
Check if a path is absolute.
Definition: util-path.c:44
SCLogError
#define SCLogError(err_code,...)
Macro used to log ERROR messages.
Definition: util-debug.h:255
detect-dataset.h
ParseSizeStringU32
int ParseSizeStringU32(const char *size, uint32_t *res)
Definition: util-misc.c:183
SC_ERR_THASH_INIT
@ SC_ERR_THASH_INIT
Definition: util-error.h:354
DETECT_DATASET_CMD_ISNOTSET
#define DETECT_DATASET_CMD_ISNOTSET
Definition: detect-dataset.h:31
str
#define str(s)
Definition: suricata-common.h:280
SCLogWarning
#define SCLogWarning(err_code,...)
Macro used to log WARNING messages.
Definition: util-debug.h:242
SCFree
#define SCFree(p)
Definition: util-mem.h:61
detect-parse.h
Signature_
Signature container.
Definition: detect.h:539
SigMatch_
a single match condition for a signature
Definition: detect.h:313
DATASET_TYPE_MD5
@ DATASET_TYPE_MD5
Definition: datasets.h:33
DATASET_TYPE_STRING
@ DATASET_TYPE_STRING
Definition: datasets.h:32
DetectLoadCompleteSigPath
char * DetectLoadCompleteSigPath(const DetectEngineCtx *de_ctx, const char *sig_file)
Create the path if default-rule-path was specified.
Definition: detect-engine-loader.c:61
DetectDatasetMatch
int DetectDatasetMatch(ThreadVars *, DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *)
Dataset
Definition: datasets.h:40
SC_ATOMIC_GET
#define SC_ATOMIC_GET(name)
Get the value from the atomic variable.
Definition: util-atomic.h:376
util-misc.h
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
SCReturnInt
#define SCReturnInt(x)
Definition: util-debug.h:302
SigMatchAppendSMToList
void SigMatchAppendSMToList(Signature *s, SigMatch *new, int list)
Append a SigMatch to the list type.
Definition: detect-parse.c:352
ConfigGetDataDirectory
const char * ConfigGetDataDirectory()
Definition: util-conf.c:84
DETECT_DATASET
@ DETECT_DATASET
Definition: detect-engine-register.h:101