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 }
256 
257 static int SetupLoadPath(const DetectEngineCtx *de_ctx,
258  char *load, size_t load_size)
259 {
260  SCLogDebug("load %s", load);
261 
262  if (PathIsAbsolute(load)) {
263  return 0;
264  }
265 
266  bool done = false;
267 #ifdef HAVE_LIBGEN_H
268  BUG_ON(de_ctx->rule_file == NULL);
269 
270  char dir[PATH_MAX] = "";
271  GetDirName(de_ctx->rule_file, dir, sizeof(dir));
272 
273  SCLogDebug("rule_file %s dir %s", de_ctx->rule_file, dir);
274  char path[PATH_MAX];
275  if (snprintf(path, sizeof(path), "%s/%s", dir, load) >= (int)sizeof(path)) // TODO windows path
276  return -1;
277 
278  if (SCPathExists(path)) {
279  done = true;
280  strlcpy(load, path, load_size);
281  SCLogDebug("using path '%s' (HAVE_LIBGEN_H)", load);
282  }
283 #endif
284  if (!done) {
285  char *loadp = DetectLoadCompleteSigPath(de_ctx, load);
286  if (loadp == NULL) {
287  return -1;
288  }
289  SCLogDebug("loadp %s", loadp);
290 
291  if (SCPathExists(loadp)) {
292  strlcpy(load, loadp, load_size);
293  SCLogDebug("using path '%s' (non-HAVE_LIBGEN_H)", load);
294  }
295  SCFree(loadp);
296  }
297  return 0;
298 }
299 
300 static int SetupSavePath(const DetectEngineCtx *de_ctx,
301  char *save, size_t save_size)
302 {
303  SCLogDebug("save %s", save);
304 
305  int allow_save = 1;
306  if (ConfGetBool("datasets.rules.allow-write", &allow_save)) {
307  if (!allow_save) {
308  SCLogError("Rules containing save/state datasets have been disabled");
309  return -1;
310  }
311  }
312 
313  int allow_absolute = 0;
314  (void)ConfGetBool("datasets.rules.allow-absolute-filenames", &allow_absolute);
315  if (allow_absolute) {
316  SCLogNotice("Allowing absolute filename for dataset rule: %s", save);
317  } else {
318  if (PathIsAbsolute(save)) {
319  SCLogError("Absolute paths not allowed: %s", save);
320  return -1;
321  }
322 
323  if (SCPathContainsTraversal(save)) {
324  SCLogError("Directory traversals not allowed: %s", save);
325  return -1;
326  }
327  }
328 
329  // data dir
330  const char *dir = ConfigGetDataDirectory();
331  BUG_ON(dir == NULL); // should not be able to fail
332  char path[PATH_MAX];
333  if (snprintf(path, sizeof(path), "%s/%s", dir, save) >= (int)sizeof(path)) // TODO windows path
334  return -1;
335 
336  /* TODO check if location exists and is writable */
337 
338  strlcpy(save, path, save_size);
339 
340  return 0;
341 }
342 
343 int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr)
344 {
345  DetectDatasetData *cd = NULL;
346  uint8_t cmd = 0;
347  uint64_t memcap = 0;
348  uint32_t hashsize = 0;
349  char cmd_str[16] = "", name[DATASET_NAME_MAX_LEN + 1] = "";
351  char load[PATH_MAX] = "";
352  char save[PATH_MAX] = "";
353 
354  if (DetectBufferGetActiveList(de_ctx, s) == -1) {
355  SCLogError("datasets are only supported for sticky buffers");
356  SCReturnInt(-1);
357  }
358 
359  int list = s->init_data->list;
360  if (list == DETECT_SM_LIST_NOTSET) {
361  SCLogError("datasets are only supported for sticky buffers");
362  SCReturnInt(-1);
363  }
364 
365  if (!DetectDatasetParse(rawstr, cmd_str, sizeof(cmd_str), name, sizeof(name), &type, load,
366  sizeof(load), save, sizeof(save), &memcap, &hashsize)) {
367  return -1;
368  }
369 
370  if (strcmp(cmd_str,"isset") == 0) {
372  } else if (strcmp(cmd_str,"isnotset") == 0) {
374  } else if (strcmp(cmd_str,"set") == 0) {
376  } else if (strcmp(cmd_str,"unset") == 0) {
378  } else {
379  SCLogError("dataset action \"%s\" is not supported.", cmd_str);
380  return -1;
381  }
382 
383  /* if just 'load' is set, we load data from the same dir as the
384  * rule file. If load+save is used, we use data dir */
385  if (strlen(save) == 0 && strlen(load) != 0) {
386  if (SetupLoadPath(de_ctx, load, sizeof(load)) != 0)
387  return -1;
388  /* if just 'save' is set, we use either full path or the
389  * data-dir */
390  } else if (strlen(save) != 0 && strlen(load) == 0) {
391  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
392  return -1;
393  /* use 'save' logic for 'state', but put the resulting
394  * path into 'load' as well. */
395  } else if (strlen(save) != 0 && strlen(load) != 0 &&
396  strcmp(save, load) == 0) {
397  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
398  return -1;
399  strlcpy(load, save, sizeof(load));
400  }
401 
402  SCLogDebug("name '%s' load '%s' save '%s'", name, load, save);
403  Dataset *set = DatasetGet(name, type, save, load, memcap, hashsize);
404  if (set == NULL) {
405  SCLogError("failed to set up dataset '%s'.", name);
406  return -1;
407  }
408 
409  cd = SCCalloc(1, sizeof(DetectDatasetData));
410  if (unlikely(cd == NULL))
411  goto error;
412 
413  cd->set = set;
414  cd->cmd = cmd;
415 
416  SCLogDebug("cmd %s, name %s",
417  cmd_str, strlen(name) ? name : "(none)");
418 
419  /* Okay so far so good, lets get this into a SigMatch
420  * and put it in the Signature. */
421 
422  if (SigMatchAppendSMToList(de_ctx, s, DETECT_DATASET, (SigMatchCtx *)cd, list) == NULL) {
423  goto error;
424  }
425  return 0;
426 
427 error:
428  if (cd != NULL)
429  SCFree(cd);
430  return -1;
431 }
432 
434 {
436  if (fd == NULL)
437  return;
438 
439  SCFree(fd);
440 }
DetectDatasetData_
Definition: detect-dataset.h:34
SigTableElmt_::url
const char * url
Definition: detect.h:1304
detect-engine.h
DetectDatasetData_::cmd
uint8_t cmd
Definition: detect-dataset.h:36
SigTableElmt_::desc
const char * desc
Definition: detect.h:1303
sigmatch_table
SigTableElmt * sigmatch_table
Definition: detect-parse.c:127
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1291
SigTableElmt_::name
const char * name
Definition: detect.h:1301
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:930
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:190
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:841
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:1422
SigTableElmt_::Setup
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition: detect.h:1286
DATASET_TYPE_IPV6
@ DATASET_TYPE_IPV6
Definition: datasets.h:36
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:633
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:1558
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:17
DetectEngineThreadCtx_
Definition: detect.h:1090
DetectDatasetFree
void DetectDatasetFree(DetectEngineCtx *, void *)
Definition: detect-dataset.c:433
DATASET_TYPE_NOTSET
#define DATASET_TYPE_NOTSET
Definition: datasets.h:31
SignatureInitData_::list
int list
Definition: detect.h:570
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:479
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:670
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:1323
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:344
DETECT_SM_LIST_NOTSET
#define DETECT_SM_LIST_NOTSET
Definition: detect.h:141
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
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
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:601
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: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:436
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:87