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("bad type %s", val);
167  return -1;
168  }
169 
170  } else if (strcmp(key, "save") == 0) {
171  if (save_set) {
172  SCLogWarning("'save' can only appear once");
173  return -1;
174  }
175  SCLogDebug("save %s", val);
176  strlcpy(save, val, save_size);
177  save_set = true;
178  } else if (strcmp(key, "load") == 0) {
179  if (load_set) {
180  SCLogWarning("'load' can only appear once");
181  return -1;
182  }
183  SCLogDebug("load %s", val);
184  strlcpy(load, val, load_size);
185  load_set = true;
186  } else if (strcmp(key, "state") == 0) {
187  if (state_set) {
188  SCLogWarning("'state' can only appear once");
189  return -1;
190  }
191  SCLogDebug("state %s", val);
192  strlcpy(load, val, load_size);
193  strlcpy(save, val, save_size);
194  state_set = true;
195  }
196  if (strcmp(key, "memcap") == 0) {
197  if (ParseSizeStringU64(val, memcap) < 0) {
198  SCLogWarning("invalid value for memcap: %s,"
199  " resetting to default",
200  val);
201  *memcap = 0;
202  }
203  }
204  if (strcmp(key, "hashsize") == 0) {
205  if (ParseSizeStringU32(val, hashsize) < 0) {
206  SCLogWarning("invalid value for hashsize: %s,"
207  " resetting to default",
208  val);
209  *hashsize = 0;
210  }
211  }
212  }
213 
214  SCLogDebug("key: %s, value: %s", key, val);
215 
216  next:
217  key = strtok_r(NULL, ",", &xsaveptr);
218  }
219 
220  if ((load_set || save_set) && state_set) {
221  SCLogWarning("'state' can not be mixed with 'load' and 'save'");
222  return -1;
223  }
224 
225  /* Trim trailing whitespace. */
226  while (strlen(name) > 0 && isblank(name[strlen(name) - 1])) {
227  name[strlen(name) - 1] = '\0';
228  }
229 
230  /* Validate name, spaces are not allowed. */
231  for (size_t i = 0; i < strlen(name); i++) {
232  if (isblank(name[i])) {
233  SCLogError("spaces not allowed in dataset names");
234  return 0;
235  }
236  }
237 
238  return 1;
239 }
240 
241 /** \brief wrapper around dirname that does leave input untouched */
242 static void GetDirName(const char *in, char *out, size_t outs)
243 {
244  if (strlen(in) == 0) {
245  return;
246  }
247 
248  size_t size = strlen(in) + 1;
249  char tmp[size];
250  strlcpy(tmp, in, size);
251 
252  char *dir = dirname(tmp);
253  BUG_ON(dir == NULL);
254  strlcpy(out, dir, outs);
255  return;
256 }
257 
258 static int SetupLoadPath(const DetectEngineCtx *de_ctx,
259  char *load, size_t load_size)
260 {
261  SCLogDebug("load %s", load);
262 
263  if (PathIsAbsolute(load)) {
264  return 0;
265  }
266 
267  bool done = false;
268 #ifdef HAVE_LIBGEN_H
269  BUG_ON(de_ctx->rule_file == NULL);
270 
271  char dir[PATH_MAX] = "";
272  GetDirName(de_ctx->rule_file, dir, sizeof(dir));
273 
274  SCLogDebug("rule_file %s dir %s", de_ctx->rule_file, dir);
275  char path[PATH_MAX];
276  if (snprintf(path, sizeof(path), "%s/%s", dir, load) >= (int)sizeof(path)) // TODO windows path
277  return -1;
278 
279  if (SCPathExists(path)) {
280  done = true;
281  strlcpy(load, path, load_size);
282  SCLogDebug("using path '%s' (HAVE_LIBGEN_H)", load);
283  }
284 #endif
285  if (!done) {
286  char *loadp = DetectLoadCompleteSigPath(de_ctx, load);
287  if (loadp == NULL) {
288  return -1;
289  }
290  SCLogDebug("loadp %s", loadp);
291 
292  if (SCPathExists(loadp)) {
293  strlcpy(load, loadp, load_size);
294  SCLogDebug("using path '%s' (non-HAVE_LIBGEN_H)", load);
295  }
296  SCFree(loadp);
297  }
298  return 0;
299 }
300 
301 static int SetupSavePath(const DetectEngineCtx *de_ctx,
302  char *save, size_t save_size)
303 {
304  SCLogDebug("save %s", save);
305 
306  int allow_save = 1;
307  if (ConfGetBool("datasets.rules.allow-write", &allow_save)) {
308  if (!allow_save) {
309  SCLogError("Rules containing save/state datasets have been disabled");
310  return -1;
311  }
312  }
313 
314  int allow_absolute = 0;
315  (void)ConfGetBool("datasets.rules.allow-absolute-filenames", &allow_absolute);
316  if (allow_absolute) {
317  SCLogNotice("Allowing absolute filename for dataset rule: %s", save);
318  } else {
319  if (PathIsAbsolute(save)) {
320  SCLogError("Absolute paths not allowed: %s", save);
321  return -1;
322  }
323 
324  if (SCPathContainsTraversal(save)) {
325  SCLogError("Directory traversals not allowed: %s", save);
326  return -1;
327  }
328  }
329 
330  // data dir
331  const char *dir = ConfigGetDataDirectory();
332  BUG_ON(dir == NULL); // should not be able to fail
333  char path[PATH_MAX];
334  if (snprintf(path, sizeof(path), "%s/%s", dir, save) >= (int)sizeof(path)) // TODO windows path
335  return -1;
336 
337  /* TODO check if location exists and is writable */
338 
339  strlcpy(save, path, save_size);
340 
341  return 0;
342 }
343 
344 int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr)
345 {
346  DetectDatasetData *cd = NULL;
347  uint8_t cmd = 0;
348  uint64_t memcap = 0;
349  uint32_t hashsize = 0;
350  char cmd_str[16] = "", name[DATASET_NAME_MAX_LEN + 1] = "";
352  char load[PATH_MAX] = "";
353  char save[PATH_MAX] = "";
354 
355  if (DetectBufferGetActiveList(de_ctx, s) == -1) {
356  SCLogError("datasets are only supported for sticky buffers");
357  SCReturnInt(-1);
358  }
359 
360  int list = s->init_data->list;
361  if (list == DETECT_SM_LIST_NOTSET) {
362  SCLogError("datasets are only supported for sticky buffers");
363  SCReturnInt(-1);
364  }
365 
366  if (!DetectDatasetParse(rawstr, cmd_str, sizeof(cmd_str), name, sizeof(name), &type, load,
367  sizeof(load), save, sizeof(save), &memcap, &hashsize)) {
368  return -1;
369  }
370 
371  if (strcmp(cmd_str,"isset") == 0) {
373  } else if (strcmp(cmd_str,"isnotset") == 0) {
375  } else if (strcmp(cmd_str,"set") == 0) {
377  } else if (strcmp(cmd_str,"unset") == 0) {
379  } else {
380  SCLogError("dataset action \"%s\" is not supported.", cmd_str);
381  return -1;
382  }
383 
384  /* if just 'load' is set, we load data from the same dir as the
385  * rule file. If load+save is used, we use data dir */
386  if (strlen(save) == 0 && strlen(load) != 0) {
387  if (SetupLoadPath(de_ctx, load, sizeof(load)) != 0)
388  return -1;
389  /* if just 'save' is set, we use either full path or the
390  * data-dir */
391  } else if (strlen(save) != 0 && strlen(load) == 0) {
392  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
393  return -1;
394  /* use 'save' logic for 'state', but put the resulting
395  * path into 'load' as well. */
396  } else if (strlen(save) != 0 && strlen(load) != 0 &&
397  strcmp(save, load) == 0) {
398  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
399  return -1;
400  strlcpy(load, save, sizeof(load));
401  }
402 
403  SCLogDebug("name '%s' load '%s' save '%s'", name, load, save);
404  Dataset *set = DatasetGet(name, type, save, load, memcap, hashsize);
405  if (set == NULL) {
406  SCLogError("failed to set up dataset '%s'.", name);
407  return -1;
408  }
409 
410  cd = SCCalloc(1, sizeof(DetectDatasetData));
411  if (unlikely(cd == NULL))
412  goto error;
413 
414  cd->set = set;
415  cd->cmd = cmd;
416 
417  SCLogDebug("cmd %s, name %s",
418  cmd_str, strlen(name) ? name : "(none)");
419 
420  /* Okay so far so good, lets get this into a SigMatch
421  * and put it in the Signature. */
422 
423  if (SigMatchAppendSMToList(de_ctx, s, DETECT_DATASET, (SigMatchCtx *)cd, list) == NULL) {
424  goto error;
425  }
426  return 0;
427 
428 error:
429  if (cd != NULL)
430  SCFree(cd);
431  return -1;
432 }
433 
435 {
437  if (fd == NULL)
438  return;
439 
440  SCFree(fd);
441 }
DetectDatasetData_
Definition: detect-dataset.h:34
SigTableElmt_::url
const char * url
Definition: detect.h:1296
detect-engine.h
DetectDatasetData_::cmd
uint8_t cmd
Definition: detect-dataset.h:36
SigTableElmt_::desc
const char * desc
Definition: detect.h:1295
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1283
SigTableElmt_::name
const char * name
Definition: detect.h:1293
ConfGetBool
int ConfGetBool(const char *name, int *val)
Retrieve a configuration value as a boolean.
Definition: conf.c:483
DetectEngineCtx_::rule_file
char * rule_file
Definition: detect.h:926
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:269
ParseSizeStringU64
int ParseSizeStringU64(const char *size, uint64_t *res)
Definition: util-misc.c:198
next
struct HtpBodyChunk_ * next
Definition: app-layer-htp.h:0
threads.h
DETECT_DATASET_CMD_SET
#define DETECT_DATASET_CMD_SET
Definition: detect-dataset.h:29
DetectEngineCtx_
main detection engine ctx
Definition: detect.h:836
DATASET_TYPE_SHA256
@ DATASET_TYPE_SHA256
Definition: datasets.h:34
DetectDatasetData_::set
Dataset * set
Definition: detect-dataset.h:35
ConfigGetDataDirectory
const char * ConfigGetDataDirectory(void)
Definition: util-conf.c:80
DetectBufferGetActiveList
int DetectBufferGetActiveList(DetectEngineCtx *de_ctx, Signature *s)
Definition: detect-engine.c:1403
SigTableElmt_::Setup
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition: detect.h:1278
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:632
SCPathContainsTraversal
bool SCPathContainsTraversal(const char *path)
Check for directory traversal.
Definition: util-path.c:307
datasets.h
decode.h
util-debug.h
DatasetAdd
int DatasetAdd(Dataset *set, const uint8_t *data, const uint32_t data_len)
Definition: datasets.c:1553
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:17
DetectEngineThreadCtx_
Definition: detect.h:1092
DetectDatasetFree
void DetectDatasetFree(DetectEngineCtx *, void *)
Definition: detect-dataset.c:434
DATASET_TYPE_NOTSET
#define DATASET_TYPE_NOTSET
Definition: datasets.h:31
SignatureInitData_::list
int list
Definition: detect.h:562
util-print.h
detect-engine-mpm.h
detect.h
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:57
SCLogWarning
#define SCLogWarning(...)
Macro used to log WARNING messages.
Definition: util-debug.h:249
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:300
DetectDatasetRegister
void DetectDatasetRegister(void)
Definition: detect-dataset.c:49
Packet_
Definition: decode.h:437
type
uint16_t type
Definition: decode-vlan.c:107
DETECT_DATASET_CMD_ISSET
#define DETECT_DATASET_CMD_ISSET
Definition: detect-dataset.h:32
Signature_::init_data
SignatureInitData * init_data
Definition: detect.h:662
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:1318
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.
SigMatchCtx_
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition: detect.h:342
DETECT_SM_LIST_NOTSET
#define DETECT_SM_LIST_NOTSET
Definition: detect.h:138
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: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
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:127
PathIsAbsolute
int PathIsAbsolute(const char *path)
Check if a path is absolute.
Definition: util-path.c:44
detect-dataset.h
ParseSizeStringU32
int ParseSizeStringU32(const char *size, uint32_t *res)
Definition: util-misc.c:181
DETECT_DATASET_CMD_ISNOTSET
#define DETECT_DATASET_CMD_ISNOTSET
Definition: detect-dataset.h:31
str
#define str(s)
Definition: suricata-common.h:291
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:593
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:63
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:447
DetectDatasetMatch
int DetectDatasetMatch(ThreadVars *, DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *)
Dataset
Definition: datasets.h:40
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
DETECT_DATASET
@ DETECT_DATASET
Definition: detect-engine-register.h:101