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 #include "util-validate.h"
44 
45 #define DETECT_DATASET_CMD_SET 0
46 #define DETECT_DATASET_CMD_UNSET 1
47 #define DETECT_DATASET_CMD_ISNOTSET 2
48 #define DETECT_DATASET_CMD_ISSET 3
49 
50 static int DetectDatasetSetup (DetectEngineCtx *, Signature *, const char *);
51 void DetectDatasetFree (DetectEngineCtx *, void *);
52 
54 {
55  sigmatch_table[DETECT_DATASET].name = "dataset";
56  sigmatch_table[DETECT_DATASET].desc = "match sticky buffer against datasets (experimental)";
57  sigmatch_table[DETECT_DATASET].url = "/rules/dataset-keywords.html#dataset";
58  sigmatch_table[DETECT_DATASET].Setup = DetectDatasetSetup;
60 }
61 
62 /*
63  1 match
64  0 no match
65  -1 can't match
66  */
68  const DetectDatasetData *sd,
69  const uint8_t *data, const uint32_t data_len)
70 {
71  if (data == NULL || data_len == 0)
72  return 0;
73 
74  switch (sd->cmd) {
76  //PrintRawDataFp(stdout, data, data_len);
77  int r = DatasetLookup(sd->set, data, data_len);
78  SCLogDebug("r %d", r);
79  if (r == 1)
80  return 1;
81  break;
82  }
84  //PrintRawDataFp(stdout, data, data_len);
85  int r = DatasetLookup(sd->set, data, data_len);
86  SCLogDebug("r %d", r);
87  if (r < 1)
88  return 1;
89  break;
90  }
92  //PrintRawDataFp(stdout, data, data_len);
93  int r = DatasetAdd(sd->set, data, data_len);
94  if (r == 1)
95  return 1;
96  break;
97  }
99  int r = DatasetRemove(sd->set, data, data_len);
100  if (r == 1)
101  return 1;
102  break;
103  }
104  default:
105  DEBUG_VALIDATE_BUG_ON("unknown dataset command");
106  }
107  return 0;
108 }
109 
110 static int DetectDatasetParse(const char *str, char *cmd, int cmd_len, char *name, int name_len,
111  enum DatasetTypes *type, char *load, size_t load_size, char *save, size_t save_size,
112  uint64_t *memcap, uint32_t *hashsize)
113 {
114  bool cmd_set = false;
115  bool name_set = false;
116  bool load_set = false;
117  bool save_set = false;
118  bool state_set = false;
119 
120  char copy[strlen(str)+1];
121  strlcpy(copy, str, sizeof(copy));
122  char *xsaveptr = NULL;
123  char *key = strtok_r(copy, ",", &xsaveptr);
124  while (key != NULL) {
125  while (*key != '\0' && isblank(*key)) {
126  key++;
127  }
128  char *val = strchr(key, ' ');
129  if (val != NULL) {
130  *val++ = '\0';
131  while (*val != '\0' && isblank(*val)) {
132  val++;
133  SCLogDebug("cmd %s val %s", key, val);
134  }
135  } else {
136  SCLogDebug("cmd %s", key);
137  }
138 
139  if (strlen(key) == 0) {
140  goto next;
141  }
142 
143  if (!cmd_set) {
144  if (val && strlen(val) != 0) {
145  return -1;
146  }
147  strlcpy(cmd, key, cmd_len);
148  cmd_set = true;
149  } else if (!name_set) {
150  if (val && strlen(val) != 0) {
151  return -1;
152  }
153  strlcpy(name, key, name_len);
154  name_set = true;
155  } else {
156  if (val == NULL) {
157  return -1;
158  }
159 
160  if (strcmp(key, "type") == 0) {
161  SCLogDebug("type %s", val);
162 
163  if (strcmp(val, "md5") == 0) {
165  } else if (strcmp(val, "sha256") == 0) {
167  } else if (strcmp(val, "string") == 0) {
169  } else if (strcmp(val, "ipv4") == 0) {
171  } else if (strcmp(val, "ipv6") == 0) {
173  } else if (strcmp(val, "ip") == 0) {
175  } else {
176  SCLogError("bad type %s", val);
177  return -1;
178  }
179 
180  } else if (strcmp(key, "save") == 0) {
181  if (save_set) {
182  SCLogWarning("'save' can only appear once");
183  return -1;
184  }
185  SCLogDebug("save %s", val);
186  strlcpy(save, val, save_size);
187  save_set = true;
188  } else if (strcmp(key, "load") == 0) {
189  if (load_set) {
190  SCLogWarning("'load' can only appear once");
191  return -1;
192  }
193  SCLogDebug("load %s", val);
194  strlcpy(load, val, load_size);
195  load_set = true;
196  } else if (strcmp(key, "state") == 0) {
197  if (state_set) {
198  SCLogWarning("'state' can only appear once");
199  return -1;
200  }
201  SCLogDebug("state %s", val);
202  strlcpy(load, val, load_size);
203  strlcpy(save, val, save_size);
204  state_set = true;
205  }
206  if (strcmp(key, "memcap") == 0) {
207  if (ParseSizeStringU64(val, memcap) < 0) {
208  SCLogWarning("invalid value for memcap: %s,"
209  " resetting to default",
210  val);
211  *memcap = 0;
212  }
213  }
214  if (strcmp(key, "hashsize") == 0) {
215  if (ParseSizeStringU32(val, hashsize) < 0) {
216  SCLogWarning("invalid value for hashsize: %s,"
217  " resetting to default",
218  val);
219  *hashsize = 0;
220  }
221  }
222  }
223 
224  SCLogDebug("key: %s, value: %s", key, val);
225 
226  next:
227  key = strtok_r(NULL, ",", &xsaveptr);
228  }
229 
230  if ((load_set || save_set) && state_set) {
231  SCLogWarning("'state' can not be mixed with 'load' and 'save'");
232  return -1;
233  }
234 
235  /* Trim trailing whitespace. */
236  while (strlen(name) > 0 && isblank(name[strlen(name) - 1])) {
237  name[strlen(name) - 1] = '\0';
238  }
239 
240  /* Validate name, spaces are not allowed. */
241  for (size_t i = 0; i < strlen(name); i++) {
242  if (isblank(name[i])) {
243  SCLogError("spaces not allowed in dataset names");
244  return 0;
245  }
246  }
247 
248  return 1;
249 }
250 
251 /** \brief wrapper around dirname that does leave input untouched */
252 static void GetDirName(const char *in, char *out, size_t outs)
253 {
254  if (strlen(in) == 0) {
255  return;
256  }
257 
258  size_t size = strlen(in) + 1;
259  char tmp[size];
260  strlcpy(tmp, in, size);
261 
262  char *dir = dirname(tmp);
263  BUG_ON(dir == NULL);
264  strlcpy(out, dir, outs);
265 }
266 
267 static int SetupLoadPath(const DetectEngineCtx *de_ctx,
268  char *load, size_t load_size)
269 {
270  SCLogDebug("load %s", load);
271 
272  if (PathIsAbsolute(load)) {
273  return 0;
274  }
275 
276  bool done = false;
277 #ifdef HAVE_LIBGEN_H
278  BUG_ON(de_ctx->rule_file == NULL);
279 
280  char dir[PATH_MAX] = "";
281  GetDirName(de_ctx->rule_file, dir, sizeof(dir));
282 
283  SCLogDebug("rule_file %s dir %s", de_ctx->rule_file, dir);
284  char path[PATH_MAX];
285  if (snprintf(path, sizeof(path), "%s/%s", dir, load) >= (int)sizeof(path)) // TODO windows path
286  return -1;
287 
288  if (SCPathExists(path)) {
289  done = true;
290  strlcpy(load, path, load_size);
291  SCLogDebug("using path '%s' (HAVE_LIBGEN_H)", load);
292  }
293 #endif
294  if (!done) {
295  char *loadp = DetectLoadCompleteSigPath(de_ctx, load);
296  if (loadp == NULL) {
297  return -1;
298  }
299  SCLogDebug("loadp %s", loadp);
300 
301  if (SCPathExists(loadp)) {
302  strlcpy(load, loadp, load_size);
303  SCLogDebug("using path '%s' (non-HAVE_LIBGEN_H)", load);
304  }
305  SCFree(loadp);
306  }
307  return 0;
308 }
309 
310 static int SetupSavePath(const DetectEngineCtx *de_ctx,
311  char *save, size_t save_size)
312 {
313  SCLogDebug("save %s", save);
314 
315  int allow_save = 1;
316  if (ConfGetBool("datasets.rules.allow-write", &allow_save)) {
317  if (!allow_save) {
318  SCLogError("Rules containing save/state datasets have been disabled");
319  return -1;
320  }
321  }
322 
323  int allow_absolute = 0;
324  (void)ConfGetBool("datasets.rules.allow-absolute-filenames", &allow_absolute);
325  if (allow_absolute) {
326  SCLogNotice("Allowing absolute filename for dataset rule: %s", save);
327  } else {
328  if (PathIsAbsolute(save)) {
329  SCLogError("Absolute paths not allowed: %s", save);
330  return -1;
331  }
332 
333  if (SCPathContainsTraversal(save)) {
334  SCLogError("Directory traversals not allowed: %s", save);
335  return -1;
336  }
337  }
338 
339  // data dir
340  const char *dir = ConfigGetDataDirectory();
341  BUG_ON(dir == NULL); // should not be able to fail
342  char path[PATH_MAX];
343  if (snprintf(path, sizeof(path), "%s/%s", dir, save) >= (int)sizeof(path)) // TODO windows path
344  return -1;
345 
346  /* TODO check if location exists and is writable */
347 
348  strlcpy(save, path, save_size);
349 
350  return 0;
351 }
352 
353 int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr)
354 {
355  DetectDatasetData *cd = NULL;
356  uint8_t cmd = 0;
357  uint64_t memcap = 0;
358  uint32_t hashsize = 0;
359  char cmd_str[16] = "", name[DATASET_NAME_MAX_LEN + 1] = "";
361  char load[PATH_MAX] = "";
362  char save[PATH_MAX] = "";
363 
364  if (DetectBufferGetActiveList(de_ctx, s) == -1) {
365  SCLogError("datasets are only supported for sticky buffers");
366  SCReturnInt(-1);
367  }
368 
369  int list = s->init_data->list;
370  if (list == DETECT_SM_LIST_NOTSET) {
371  SCLogError("datasets are only supported for sticky buffers");
372  SCReturnInt(-1);
373  }
374 
375  if (!DetectDatasetParse(rawstr, cmd_str, sizeof(cmd_str), name, sizeof(name), &type, load,
376  sizeof(load), save, sizeof(save), &memcap, &hashsize)) {
377  return -1;
378  }
379 
380  if (strcmp(cmd_str,"isset") == 0) {
382  } else if (strcmp(cmd_str,"isnotset") == 0) {
384  } else if (strcmp(cmd_str,"set") == 0) {
386  } else if (strcmp(cmd_str,"unset") == 0) {
388  } else {
389  SCLogError("dataset action \"%s\" is not supported.", cmd_str);
390  return -1;
391  }
392 
393  /* if just 'load' is set, we load data from the same dir as the
394  * rule file. If load+save is used, we use data dir */
395  if (strlen(save) == 0 && strlen(load) != 0) {
396  if (SetupLoadPath(de_ctx, load, sizeof(load)) != 0)
397  return -1;
398  /* if just 'save' is set, we use either full path or the
399  * data-dir */
400  } else if (strlen(save) != 0 && strlen(load) == 0) {
401  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
402  return -1;
403  /* use 'save' logic for 'state', but put the resulting
404  * path into 'load' as well. */
405  } else if (strlen(save) != 0 && strlen(load) != 0 &&
406  strcmp(save, load) == 0) {
407  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
408  return -1;
409  strlcpy(load, save, sizeof(load));
410  }
411 
412  SCLogDebug("name '%s' load '%s' save '%s'", name, load, save);
413  Dataset *set = DatasetGet(name, type, save, load, memcap, hashsize);
414  if (set == NULL) {
415  SCLogError("failed to set up dataset '%s'.", name);
416  return -1;
417  }
418 
419  cd = SCCalloc(1, sizeof(DetectDatasetData));
420  if (unlikely(cd == NULL))
421  goto error;
422 
423  cd->set = set;
424  cd->cmd = cmd;
425 
426  SCLogDebug("cmd %s, name %s",
427  cmd_str, strlen(name) ? name : "(none)");
428 
429  /* Okay so far so good, lets get this into a SigMatch
430  * and put it in the Signature. */
431 
432  if (SigMatchAppendSMToList(de_ctx, s, DETECT_DATASET, (SigMatchCtx *)cd, list) == NULL) {
433  goto error;
434  }
435  return 0;
436 
437 error:
438  if (cd != NULL)
439  SCFree(cd);
440  return -1;
441 }
442 
444 {
446  if (fd == NULL)
447  return;
448 
449  SCFree(fd);
450 }
DetectDatasetData_
Definition: detect-dataset.h:29
SigTableElmt_::url
const char * url
Definition: detect.h:1322
detect-engine.h
DetectDatasetData_::cmd
uint8_t cmd
Definition: detect-dataset.h:31
SigTableElmt_::desc
const char * desc
Definition: detect.h:1321
sigmatch_table
SigTableElmt * sigmatch_table
Definition: detect-parse.c:153
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1309
SigTableElmt_::name
const char * name
Definition: detect.h:1319
ConfGetBool
int ConfGetBool(const char *name, int *val)
Retrieve a configuration value as a boolean.
Definition: conf.c:482
DetectEngineCtx_::rule_file
char * rule_file
Definition: detect.h:949
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
DETECT_DATASET_CMD_SET
#define DETECT_DATASET_CMD_SET
Definition: detect-dataset.c:45
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:269
ParseSizeStringU64
int ParseSizeStringU64(const char *size, uint64_t *res)
Definition: util-misc.c:190
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
threads.h
DetectEngineCtx_
main detection engine ctx
Definition: detect.h:854
DATASET_TYPE_SHA256
@ DATASET_TYPE_SHA256
Definition: datasets.h:35
DetectDatasetData_::set
Dataset * set
Definition: detect-dataset.h:30
ConfigGetDataDirectory
const char * ConfigGetDataDirectory(void)
Definition: util-conf.c:80
DetectBufferGetActiveList
int DetectBufferGetActiveList(DetectEngineCtx *de_ctx, Signature *s)
Definition: detect-engine.c:1427
SigTableElmt_::Setup
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition: detect.h:1304
DATASET_TYPE_IPV6
@ DATASET_TYPE_IPV6
Definition: datasets.h:37
DETECT_DATASET_CMD_ISSET
#define DETECT_DATASET_CMD_ISSET
Definition: detect-dataset.c:48
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:324
SCPathContainsTraversal
bool SCPathContainsTraversal(const char *path)
Check for directory traversal.
Definition: util-path.c:307
DatasetRemove
int DatasetRemove(Dataset *set, const uint8_t *data, const uint32_t data_len)
Definition: datasets.c:1448
datasets.h
decode.h
util-debug.h
DatasetAdd
int DatasetAdd(Dataset *set, const uint8_t *data, const uint32_t data_len)
Definition: datasets.c:1249
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:18
DetectEngineThreadCtx_
Definition: detect.h:1109
DetectDatasetFree
void DetectDatasetFree(DetectEngineCtx *, void *)
Definition: detect-dataset.c:443
DATASET_TYPE_NOTSET
#define DATASET_TYPE_NOTSET
Definition: datasets.h:32
SignatureInitData_::list
int list
Definition: detect.h:577
util-print.h
detect-engine-mpm.h
detect.h
SCLogWarning
#define SCLogWarning(...)
Macro used to log WARNING messages.
Definition: util-debug.h:249
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:309
DetectDatasetRegister
void DetectDatasetRegister(void)
Definition: detect-dataset.c:53
type
uint16_t type
Definition: decode-vlan.c:106
Signature_::init_data
SignatureInitData * init_data
Definition: detect.h:683
name
const char * name
Definition: tm-threads.c:2081
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:1014
DATASET_TYPE_IPV4
@ DATASET_TYPE_IPV4
Definition: datasets.h:36
detect-engine-state.h
Data structures and function prototypes for keeping state for the detection engine.
SigMatchCtx_
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition: detect.h:346
DETECT_SM_LIST_NOTSET
#define DETECT_SM_LIST_NOTSET
Definition: detect.h:143
SCPathExists
bool SCPathExists(const char *path)
Check if a path exists.
Definition: util-path.c:219
DetectDatasetBufferMatch
int DetectDatasetBufferMatch(DetectEngineThreadCtx *det_ctx, const DetectDatasetData *sd, const uint8_t *data, const uint32_t data_len)
Definition: detect-dataset.c:67
DatasetTypes
DatasetTypes
Definition: datasets.h:31
util-conf.h
suricata-common.h
util-path.h
DATASET_NAME_MAX_LEN
#define DATASET_NAME_MAX_LEN
Definition: datasets.h:40
DETECT_DATASET_CMD_UNSET
#define DETECT_DATASET_CMD_UNSET
Definition: detect-dataset.c:46
PathIsAbsolute
int PathIsAbsolute(const char *path)
Check if a path is absolute.
Definition: util-path.c:44
detect-dataset.h
hashsize
#define hashsize(n)
Definition: util-hash-lookup3.h:40
ParseSizeStringU32
int ParseSizeStringU32(const char *size, uint32_t *res)
Definition: util-misc.c:173
util-validate.h
str
#define str(s)
Definition: suricata-common.h:300
SCLogError
#define SCLogError(...)
Macro used to log ERROR messages.
Definition: util-debug.h:261
SCFree
#define SCFree(p)
Definition: util-mem.h:61
detect-parse.h
Signature_
Signature container.
Definition: detect.h:614
DETECT_DATASET_CMD_ISNOTSET
#define DETECT_DATASET_CMD_ISNOTSET
Definition: detect-dataset.c:47
DATASET_TYPE_MD5
@ DATASET_TYPE_MD5
Definition: datasets.h:34
DATASET_TYPE_STRING
@ DATASET_TYPE_STRING
Definition: datasets.h:33
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:62
SigMatchAppendSMToList
SigMatch * SigMatchAppendSMToList(DetectEngineCtx *de_ctx, Signature *s, uint16_t type, SigMatchCtx *ctx, const int list)
Append a SigMatch to the list type.
Definition: detect-parse.c:462
Dataset
Definition: datasets.h:41
util-misc.h
SCLogNotice
#define SCLogNotice(...)
Macro used to log NOTICE messages.
Definition: util-debug.h:237
SCCalloc
#define SCCalloc(nm, sz)
Definition: util-mem.h:53
SCReturnInt
#define SCReturnInt(x)
Definition: util-debug.h:275
DEBUG_VALIDATE_BUG_ON
#define DEBUG_VALIDATE_BUG_ON(exp)
Definition: util-validate.h:102
DETECT_DATASET
@ DETECT_DATASET
Definition: detect-engine-register.h:89