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  if (PathIsAbsolute(save)) {
307  return 0;
308  }
309 
310  // data dir
311  const char *dir = ConfigGetDataDirectory();
312  BUG_ON(dir == NULL); // should not be able to fail
313  char path[PATH_MAX];
314  if (snprintf(path, sizeof(path), "%s/%s", dir, save) >= (int)sizeof(path)) // TODO windows path
315  return -1;
316 
317  /* TODO check if location exists and is writable */
318 
319  strlcpy(save, path, save_size);
320 
321  return 0;
322 }
323 
324 int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr)
325 {
326  DetectDatasetData *cd = NULL;
327  SigMatch *sm = NULL;
328  uint8_t cmd = 0;
329  uint64_t memcap = 0;
330  uint32_t hashsize = 0;
331  char cmd_str[16] = "", name[DATASET_NAME_MAX_LEN + 1] = "";
333  char load[PATH_MAX] = "";
334  char save[PATH_MAX] = "";
335 
336  if (DetectBufferGetActiveList(de_ctx, s) == -1) {
337  SCLogError("datasets are only supported for sticky buffers");
338  SCReturnInt(-1);
339  }
340 
341  int list = s->init_data->list;
342  if (list == DETECT_SM_LIST_NOTSET) {
343  SCLogError("datasets are only supported for sticky buffers");
344  SCReturnInt(-1);
345  }
346 
347  if (!DetectDatasetParse(rawstr, cmd_str, sizeof(cmd_str), name, sizeof(name), &type, load,
348  sizeof(load), save, sizeof(save), &memcap, &hashsize)) {
349  return -1;
350  }
351 
352  if (strcmp(cmd_str,"isset") == 0) {
354  } else if (strcmp(cmd_str,"isnotset") == 0) {
356  } else if (strcmp(cmd_str,"set") == 0) {
358  } else if (strcmp(cmd_str,"unset") == 0) {
360  } else {
361  SCLogError("dataset action \"%s\" is not supported.", cmd_str);
362  return -1;
363  }
364 
365  /* if just 'load' is set, we load data from the same dir as the
366  * rule file. If load+save is used, we use data dir */
367  if (strlen(save) == 0 && strlen(load) != 0) {
368  if (SetupLoadPath(de_ctx, load, sizeof(load)) != 0)
369  return -1;
370  /* if just 'save' is set, we use either full path or the
371  * data-dir */
372  } else if (strlen(save) != 0 && strlen(load) == 0) {
373  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
374  return -1;
375  /* use 'save' logic for 'state', but put the resulting
376  * path into 'load' as well. */
377  } else if (strlen(save) != 0 && strlen(load) != 0 &&
378  strcmp(save, load) == 0) {
379  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
380  return -1;
381  strlcpy(load, save, sizeof(load));
382  }
383 
384  SCLogDebug("name '%s' load '%s' save '%s'", name, load, save);
385  Dataset *set = DatasetGet(name, type, save, load, memcap, hashsize);
386  if (set == NULL) {
387  SCLogError("failed to set up dataset '%s'.", name);
388  return -1;
389  }
390  if (set->hash && SC_ATOMIC_GET(set->hash->memcap_reached)) {
391  SCLogError("dataset too large for set memcap");
392  return -1;
393  }
394 
395  cd = SCCalloc(1, sizeof(DetectDatasetData));
396  if (unlikely(cd == NULL))
397  goto error;
398 
399  cd->set = set;
400  cd->cmd = cmd;
401 
402  SCLogDebug("cmd %s, name %s",
403  cmd_str, strlen(name) ? name : "(none)");
404 
405  /* Okay so far so good, lets get this into a SigMatch
406  * and put it in the Signature. */
407  sm = SigMatchAlloc();
408  if (sm == NULL)
409  goto error;
410 
411  sm->type = DETECT_DATASET;
412  sm->ctx = (SigMatchCtx *)cd;
413  SigMatchAppendSMToList(s, sm, list);
414  return 0;
415 
416 error:
417  if (cd != NULL)
418  SCFree(cd);
419  if (sm != NULL)
420  SCFree(sm);
421  return -1;
422 }
423 
425 {
427  if (fd == NULL)
428  return;
429 
430  SCFree(fd);
431 }
DetectDatasetData_
Definition: detect-dataset.h:36
SigTableElmt_::url
const char * url
Definition: detect.h:1243
detect-engine.h
DetectDatasetData_::cmd
uint8_t cmd
Definition: detect-dataset.h:38
SigTableElmt_::desc
const char * desc
Definition: detect.h:1242
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1230
SigTableElmt_::name
const char * name
Definition: detect.h:1240
DetectEngineCtx_::rule_file
char * rule_file
Definition: detect.h:892
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
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:787
DATASET_TYPE_SHA256
@ DATASET_TYPE_SHA256
Definition: datasets.h:34
DetectDatasetData_::set
Dataset * set
Definition: detect-dataset.h:37
ConfigGetDataDirectory
const char * ConfigGetDataDirectory(void)
Definition: util-conf.c:84
DetectBufferGetActiveList
int DetectBufferGetActiveList(DetectEngineCtx *de_ctx, Signature *s)
Definition: detect-engine.c:1306
SigTableElmt_::Setup
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition: detect.h:1225
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
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:1526
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:17
DetectEngineThreadCtx_
Definition: detect.h:1027
DetectDatasetFree
void DetectDatasetFree(DetectEngineCtx *, void *)
Definition: detect-dataset.c:424
DATASET_TYPE_NOTSET
#define DATASET_TYPE_NOTSET
Definition: datasets.h:31
SignatureInitData_::list
int list
Definition: detect.h:519
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
SigMatch_::ctx
SigMatchCtx * ctx
Definition: detect.h:318
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:613
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:1291
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:241
SigMatchCtx_
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition: detect.h:310
DETECT_SM_LIST_NOTSET
#define DETECT_SM_LIST_NOTSET
Definition: detect.h:106
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:316
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
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:280
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:542
SigMatch_
a single match condition for a signature
Definition: detect.h:315
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:275
SigMatchAppendSMToList
void SigMatchAppendSMToList(Signature *s, SigMatch *new, int list)
Append a SigMatch to the list type.
Definition: detect-parse.c:356
DETECT_DATASET
@ DETECT_DATASET
Definition: detect-engine-register.h:101