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 
43  const Signature *, const SigMatchCtx *);
44 static int DetectDatasetSetup (DetectEngineCtx *, Signature *, const char *);
45 void DetectDatasetFree (DetectEngineCtx *, void *);
46 
48 {
49  sigmatch_table[DETECT_DATASET].name = "dataset";
50  sigmatch_table[DETECT_DATASET].desc = "match sticky buffer against datasets (experimental)";
51  sigmatch_table[DETECT_DATASET].url = "/rules/dataset-keywords.html#dataset";
52  sigmatch_table[DETECT_DATASET].Setup = DetectDatasetSetup;
54 }
55 
56 /*
57  1 match
58  0 no match
59  -1 can't match
60  */
62  const DetectDatasetData *sd,
63  const uint8_t *data, const uint32_t data_len)
64 {
65  if (data == NULL || data_len == 0)
66  return 0;
67 
68  switch (sd->cmd) {
70  //PrintRawDataFp(stdout, data, data_len);
71  int r = DatasetLookup(sd->set, data, data_len);
72  SCLogDebug("r %d", r);
73  if (r == 1)
74  return 1;
75  break;
76  }
78  //PrintRawDataFp(stdout, data, data_len);
79  int r = DatasetLookup(sd->set, data, data_len);
80  SCLogDebug("r %d", r);
81  if (r < 1)
82  return 1;
83  break;
84  }
86  //PrintRawDataFp(stdout, data, data_len);
87  int r = DatasetAdd(sd->set, data, data_len);
88  if (r == 1)
89  return 1;
90  break;
91  }
92  default:
93  abort();
94  }
95  return 0;
96 }
97 
98 static int DetectDatasetParse(const char *str, char *cmd, int cmd_len, char *name, int name_len,
99  enum DatasetTypes *type, char *load, size_t load_size, char *save, size_t save_size,
100  uint64_t *memcap, uint32_t *hashsize)
101 {
102  bool cmd_set = false;
103  bool name_set = false;
104  bool load_set = false;
105  bool save_set = false;
106  bool state_set = false;
107 
108  char copy[strlen(str)+1];
109  strlcpy(copy, str, sizeof(copy));
110  char *xsaveptr = NULL;
111  char *key = strtok_r(copy, ",", &xsaveptr);
112  while (key != NULL) {
113  while (*key != '\0' && isblank(*key)) {
114  key++;
115  }
116  char *val = strchr(key, ' ');
117  if (val != NULL) {
118  *val++ = '\0';
119  while (*val != '\0' && isblank(*val)) {
120  val++;
121  SCLogDebug("cmd %s val %s", key, val);
122  }
123  } else {
124  SCLogDebug("cmd %s", key);
125  }
126 
127  if (strlen(key) == 0) {
128  goto next;
129  }
130 
131  if (!cmd_set) {
132  if (val && strlen(val) != 0) {
133  return -1;
134  }
135  strlcpy(cmd, key, cmd_len);
136  cmd_set = true;
137  } else if (!name_set) {
138  if (val && strlen(val) != 0) {
139  return -1;
140  }
141  strlcpy(name, key, name_len);
142  name_set = true;
143  } else {
144  if (val == NULL) {
145  return -1;
146  }
147 
148  if (strcmp(key, "type") == 0) {
149  SCLogDebug("type %s", val);
150 
151  if (strcmp(val, "md5") == 0) {
153  } else if (strcmp(val, "sha256") == 0) {
155  } else if (strcmp(val, "string") == 0) {
157  } else {
158  SCLogError(SC_ERR_INVALID_SIGNATURE, "bad type %s", val);
159  return -1;
160  }
161 
162  } else if (strcmp(key, "save") == 0) {
163  if (save_set) {
165  "'save' can only appear once");
166  return -1;
167  }
168  SCLogDebug("save %s", val);
169  strlcpy(save, val, save_size);
170  save_set = true;
171  } else if (strcmp(key, "load") == 0) {
172  if (load_set) {
174  "'load' can only appear once");
175  return -1;
176  }
177  SCLogDebug("load %s", val);
178  strlcpy(load, val, load_size);
179  load_set = true;
180  } else if (strcmp(key, "state") == 0) {
181  if (state_set) {
183  "'state' can only appear once");
184  return -1;
185  }
186  SCLogDebug("state %s", val);
187  strlcpy(load, val, load_size);
188  strlcpy(save, val, save_size);
189  state_set = true;
190  }
191  if (strcmp(key, "memcap") == 0) {
192  if (ParseSizeStringU64(val, memcap) < 0) {
194  "invalid value for memcap: %s,"
195  " resetting to default",
196  val);
197  *memcap = 0;
198  }
199  }
200  if (strcmp(key, "hashsize") == 0) {
201  if (ParseSizeStringU32(val, hashsize) < 0) {
203  "invalid value for hashsize: %s,"
204  " resetting to default",
205  val);
206  *hashsize = 0;
207  }
208  }
209  }
210 
211  SCLogDebug("key: %s, value: %s", key, val);
212 
213  next:
214  key = strtok_r(NULL, ",", &xsaveptr);
215  }
216 
217  if ((load_set || save_set) && state_set) {
219  "'state' can not be mixed with 'load' and 'save'");
220  return -1;
221  }
222 
223  /* Trim trailing whitespace. */
224  while (strlen(name) > 0 && isblank(name[strlen(name) - 1])) {
225  name[strlen(name) - 1] = '\0';
226  }
227 
228  /* Validate name, spaces are not allowed. */
229  for (size_t i = 0; i < strlen(name); i++) {
230  if (isblank(name[i])) {
232  "spaces not allowed in dataset names");
233  return 0;
234  }
235  }
236 
237  return 1;
238 }
239 
240 /** \brief wrapper around dirname that does leave input untouched */
241 static void GetDirName(const char *in, char *out, size_t outs)
242 {
243  if (strlen(in) == 0) {
244  return;
245  }
246 
247  size_t size = strlen(in) + 1;
248  char tmp[size];
249  strlcpy(tmp, in, size);
250 
251  char *dir = dirname(tmp);
252  BUG_ON(dir == NULL);
253  strlcpy(out, dir, outs);
254  return;
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  if (PathIsAbsolute(save)) {
306  return 0;
307  }
308 
309  // data dir
310  const char *dir = ConfigGetDataDirectory();
311  BUG_ON(dir == NULL); // should not be able to fail
312  char path[PATH_MAX];
313  if (snprintf(path, sizeof(path), "%s/%s", dir, save) >= (int)sizeof(path)) // TODO windows path
314  return -1;
315 
316  /* TODO check if location exists and is writable */
317 
318  strlcpy(save, path, save_size);
319 
320  return 0;
321 }
322 
323 int DetectDatasetSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr)
324 {
325  DetectDatasetData *cd = NULL;
326  SigMatch *sm = NULL;
327  uint8_t cmd = 0;
328  uint64_t memcap = 0;
329  uint32_t hashsize = 0;
330  char cmd_str[16] = "", name[DATASET_NAME_MAX_LEN + 1] = "";
332  char load[PATH_MAX] = "";
333  char save[PATH_MAX] = "";
334 
335  if (DetectBufferGetActiveList(de_ctx, s) == -1) {
337  "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) {
344  "datasets are only supported for sticky buffers");
345  SCReturnInt(-1);
346  }
347 
348  if (!DetectDatasetParse(rawstr, cmd_str, sizeof(cmd_str), name, sizeof(name), &type, load,
349  sizeof(load), save, sizeof(save), &memcap, &hashsize)) {
350  return -1;
351  }
352 
353  if (strcmp(cmd_str,"isset") == 0) {
355  } else if (strcmp(cmd_str,"isnotset") == 0) {
357  } else if (strcmp(cmd_str,"set") == 0) {
359  } else if (strcmp(cmd_str,"unset") == 0) {
361  } else {
363  "dataset action \"%s\" is not supported.", cmd_str);
364  return -1;
365  }
366 
367  /* if just 'load' is set, we load data from the same dir as the
368  * rule file. If load+save is used, we use data dir */
369  if (strlen(save) == 0 && strlen(load) != 0) {
370  if (SetupLoadPath(de_ctx, load, sizeof(load)) != 0)
371  return -1;
372  /* if just 'save' is set, we use either full path or the
373  * data-dir */
374  } else if (strlen(save) != 0 && strlen(load) == 0) {
375  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
376  return -1;
377  /* use 'save' logic for 'state', but put the resulting
378  * path into 'load' as well. */
379  } else if (strlen(save) != 0 && strlen(load) != 0 &&
380  strcmp(save, load) == 0) {
381  if (SetupSavePath(de_ctx, save, sizeof(save)) != 0)
382  return -1;
383  strlcpy(load, save, sizeof(load));
384  }
385 
386  SCLogDebug("name '%s' load '%s' save '%s'", name, load, save);
387  Dataset *set = DatasetGet(name, type, save, load, memcap, hashsize);
388  if (set == NULL) {
390  "failed to set up dataset '%s'.", name);
391  return -1;
392  }
393  if (set->hash && SC_ATOMIC_GET(set->hash->memcap_reached)) {
394  SCLogError(SC_ERR_THASH_INIT, "dataset too large for set memcap");
395  return -1;
396  }
397 
398  cd = SCCalloc(1, sizeof(DetectDatasetData));
399  if (unlikely(cd == NULL))
400  goto error;
401 
402  cd->set = set;
403  cd->cmd = cmd;
404 
405  SCLogDebug("cmd %s, name %s",
406  cmd_str, strlen(name) ? name : "(none)");
407 
408  /* Okay so far so good, lets get this into a SigMatch
409  * and put it in the Signature. */
410  sm = SigMatchAlloc();
411  if (sm == NULL)
412  goto error;
413 
414  sm->type = DETECT_DATASET;
415  sm->ctx = (SigMatchCtx *)cd;
416  SigMatchAppendSMToList(s, sm, list);
417  return 0;
418 
419 error:
420  if (cd != NULL)
421  SCFree(cd);
422  if (sm != NULL)
423  SCFree(sm);
424  return -1;
425 }
426 
428 {
430  if (fd == NULL)
431  return;
432 
433  SCFree(fd);
434 }
DetectDatasetData_
Definition: detect-dataset.h:36
SigTableElmt_::url
const char * url
Definition: detect.h:1270
detect-engine.h
DetectDatasetData_::cmd
uint8_t cmd
Definition: detect-dataset.h:38
SigTableElmt_::desc
const char * desc
Definition: detect.h:1269
SC_ERR_INVALID_VALUE
@ SC_ERR_INVALID_VALUE
Definition: util-error.h:160
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1257
SigTableElmt_::name
const char * name
Definition: detect.h:1267
DetectEngineCtx_::rule_file
char * rule_file
Definition: detect.h:916
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:298
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:44
threads.h
DETECT_DATASET_CMD_SET
#define DETECT_DATASET_CMD_SET
Definition: detect-dataset.h:29
DetectEngineCtx_
main detection engine ctx
Definition: detect.h:811
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:1304
SigTableElmt_::Setup
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition: detect.h:1252
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:425
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:1105
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:17
DetectEngineThreadCtx_
Definition: detect.h:1060
SC_ERR_UNKNOWN_VALUE
@ SC_ERR_UNKNOWN_VALUE
Definition: util-error.h:159
DetectDatasetFree
void DetectDatasetFree(DetectEngineCtx *, void *)
Definition: detect-dataset.c:427
DATASET_TYPE_NOTSET
#define DATASET_TYPE_NOTSET
Definition: datasets.h:31
SignatureInitData_::list
int list
Definition: detect.h:525
util-print.h
detect-engine-mpm.h
detect.h
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:58
SigMatch_::ctx
SigMatchCtx * ctx
Definition: detect.h:324
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:281
DetectDatasetRegister
void DetectDatasetRegister(void)
Definition: detect-dataset.c:47
Packet_
Definition: decode.h:427
DETECT_DATASET_CMD_ISSET
#define DETECT_DATASET_CMD_ISSET
Definition: detect-dataset.h:32
Signature_::init_data
SignatureInitData * init_data
Definition: detect.h:619
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:956
detect-engine-state.h
Data structures and function prototypes for keeping state for the detection engine.
SigMatchAlloc
SigMatch * SigMatchAlloc(void)
Definition: detect-parse.c:235
SigMatchCtx_
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition: detect.h:316
DETECT_SM_LIST_NOTSET
#define DETECT_SM_LIST_NOTSET
Definition: detect.h:115
SCPathExists
bool SCPathExists(const char *path)
Check if a path exists.
Definition: util-path.c:170
DetectDatasetBufferMatch
int DetectDatasetBufferMatch(DetectEngineThreadCtx *det_ctx, const DetectDatasetData *sd, const uint8_t *data, const uint32_t data_len)
Definition: detect-dataset.c:61
DatasetTypes
DatasetTypes
Definition: datasets.h:30
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:322
DATASET_NAME_MAX_LEN
#define DATASET_NAME_MAX_LEN
Definition: datasets.h:37
sigmatch_table
SigTableElmt sigmatch_table[DETECT_TBLSIZE]
Definition: detect-parse.c:73
PathIsAbsolute
int PathIsAbsolute(const char *path)
Check if a path is absolute.
Definition: util-path.c:45
SCLogError
#define SCLogError(err_code,...)
Macro used to log ERROR messages.
Definition: util-debug.h:257
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:272
SCLogWarning
#define SCLogWarning(err_code,...)
Macro used to log WARNING messages.
Definition: util-debug.h:244
SCFree
#define SCFree(p)
Definition: util-mem.h:61
detect-parse.h
Signature_
Signature container.
Definition: detect.h:548
SigMatch_
a single match condition for a signature
Definition: detect.h:321
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:60
DetectDatasetMatch
int DetectDatasetMatch(ThreadVars *, DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *)
Dataset
Definition: datasets.h:38
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:304
SigMatchAppendSMToList
void SigMatchAppendSMToList(Signature *s, SigMatch *new, int list)
Append a SigMatch to the list type.
Definition: detect-parse.c:349
ConfigGetDataDirectory
const char * ConfigGetDataDirectory()
Definition: util-conf.c:82
DETECT_DATASET
@ DETECT_DATASET
Definition: detect-engine-register.h:99