suricata
detect-datarep.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 datarep 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-datarep.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-byte.h"
39 #include "util-debug.h"
40 #include "util-print.h"
41 #include "util-misc.h"
42 
43 #define PARSE_REGEX "([a-z]+)(?:,\\s*([\\-_A-z0-9\\s\\.]+)){1,4}"
44 static DetectParseRegex parse_regex;
45 
47  const Signature *, const SigMatchCtx *);
48 static int DetectDatarepSetup (DetectEngineCtx *, Signature *, const char *);
49 void DetectDatarepFree (DetectEngineCtx *, void *);
50 
52 {
53  sigmatch_table[DETECT_DATAREP].name = "datarep";
54  sigmatch_table[DETECT_DATAREP].desc = "operate on datasets (experimental)";
55  sigmatch_table[DETECT_DATAREP].url = "/rules/dataset-keywords.html#datarep";
56  sigmatch_table[DETECT_DATAREP].Setup = DetectDatarepSetup;
58 
59  DetectSetupParseRegexes(PARSE_REGEX, &parse_regex);
60 }
61 
62 /*
63  1 match
64  0 no match
65  -1 can't match
66  */
68  const DetectDatarepData *sd,
69  const uint8_t *data, const uint32_t data_len)
70 {
71  if (data == NULL || data_len == 0)
72  return 0;
73 
74  DataRepResultType r = DatasetLookupwRep(sd->set, data, data_len, &sd->rep);
75  if (!r.found)
76  return 0;
77 
78  switch (sd->op) {
79  case DATAREP_OP_GT:
80  if (r.rep.value > sd->rep.value)
81  return 1;
82  break;
83  case DATAREP_OP_LT:
84  if (r.rep.value < sd->rep.value)
85  return 1;
86  break;
87  case DATAREP_OP_EQ:
88  if (r.rep.value == sd->rep.value)
89  return 1;
90  break;
91  }
92  return 0;
93 }
94 
95 static int DetectDatarepParse(const char *str, char *cmd, int cmd_len, char *name, int name_len,
96  enum DatasetTypes *type, char *load, size_t load_size, uint16_t *rep_value,
97  uint64_t *memcap, uint32_t *hashsize)
98 {
99  bool cmd_set = false;
100  bool name_set = false;
101  bool value_set = false;
102 
103  char copy[strlen(str)+1];
104  strlcpy(copy, str, sizeof(copy));
105  char *xsaveptr = NULL;
106  char *key = strtok_r(copy, ",", &xsaveptr);
107  while (key != NULL) {
108  while (*key != '\0' && isblank(*key)) {
109  key++;
110  }
111  char *val = strchr(key, ' ');
112  if (val != NULL) {
113  *val++ = '\0';
114  while (*val != '\0' && isblank(*val)) {
115  val++;
116  SCLogDebug("cmd %s val %s", key, val);
117  }
118  } else {
119  SCLogDebug("cmd %s", key);
120  }
121 
122  if (strlen(key) == 0) {
123  goto next;
124  }
125 
126  if (!name_set) {
127  if (val) {
128  return -1;
129  }
130  strlcpy(name, key, name_len);
131  name_set = true;
132  } else if (!cmd_set) {
133  if (val) {
134  return -1;
135  }
136  strlcpy(cmd, key, cmd_len);
137  cmd_set = true;
138  } else if (!value_set) {
139  if (val) {
140  return -1;
141  }
142 
143  if (StringParseUint16(rep_value, 10, 0, key) < 0)
144  return -1;
145 
146  value_set = true;
147  } else {
148  if (val == NULL) {
149  return -1;
150  }
151 
152  if (strcmp(key, "type") == 0) {
153  SCLogDebug("type %s", val);
154 
155  if (strcmp(val, "md5") == 0) {
157  } else if (strcmp(val, "sha256") == 0) {
159  } else if (strcmp(val, "string") == 0) {
161  } else {
162  SCLogDebug("bad type %s", val);
163  return -1;
164  }
165 
166  } else if (strcmp(key, "load") == 0) {
167  SCLogDebug("load %s", val);
168  strlcpy(load, val, load_size);
169  }
170  if (strcmp(key, "memcap") == 0) {
171  if (ParseSizeStringU64(val, memcap) < 0) {
173  "invalid value for memcap: %s,"
174  " resetting to default",
175  val);
176  *memcap = 0;
177  }
178  }
179  if (strcmp(key, "hashsize") == 0) {
180  if (ParseSizeStringU32(val, hashsize) < 0) {
182  "invalid value for hashsize: %s,"
183  " resetting to default",
184  val);
185  *hashsize = 0;
186  }
187  }
188  }
189 
190  SCLogDebug("key: %s, value: %s", key, val);
191 
192  next:
193  key = strtok_r(NULL, ",", &xsaveptr);
194  }
195 
196  if (strlen(load) > 0 && *type == DATASET_TYPE_NOTSET) {
198  "if load is used type must be set as well");
199  return 0;
200  }
201 
202  if (!name_set || !cmd_set || !value_set) {
204  "missing values");
205  return 0;
206  }
207 
208  /* Trim trailing whitespace. */
209  while (strlen(name) > 0 && isblank(name[strlen(name) - 1])) {
210  name[strlen(name) - 1] = '\0';
211  }
212 
213  /* Validate name, spaces are not allowed. */
214  for (size_t i = 0; i < strlen(name); i++) {
215  if (isblank(name[i])) {
217  "spaces not allowed in dataset names");
218  return 0;
219  }
220  }
221 
222  return 1;
223 }
224 
225 /** \brief wrapper around dirname that does leave input untouched */
226 static void GetDirName(const char *in, char *out, size_t outs)
227 {
228  if (strlen(in) == 0) {
229  return;
230  }
231 
232  size_t size = strlen(in) + 1;
233  char tmp[size];
234  strlcpy(tmp, in, size);
235 
236  char *dir = dirname(tmp);
237  BUG_ON(dir == NULL);
238  strlcpy(out, dir, outs);
239  return;
240 }
241 
242 static int SetupLoadPath(const DetectEngineCtx *de_ctx,
243  char *load, size_t load_size)
244 {
245  SCLogDebug("load %s", load);
246 
247  if (PathIsAbsolute(load)) {
248  return 0;
249  }
250 
251  bool done = false;
252 #ifdef HAVE_LIBGEN_H
253  BUG_ON(de_ctx->rule_file == NULL);
254 
255  char dir[PATH_MAX] = "";
256  GetDirName(de_ctx->rule_file, dir, sizeof(dir));
257 
258  SCLogDebug("rule_file %s dir %s", de_ctx->rule_file, dir);
259  char path[PATH_MAX];
260  if (snprintf(path, sizeof(path), "%s/%s", dir, load) >= (int)sizeof(path)) // TODO windows path
261  return -1;
262 
263  if (SCPathExists(path)) {
264  done = true;
265  strlcpy(load, path, load_size);
266  SCLogDebug("using path '%s' (HAVE_LIBGEN_H)", load);
267  } else {
268  SCLogDebug("path '%s' does not exist (HAVE_LIBGEN_H)", path);
269  }
270 #endif
271  if (!done) {
272  char *loadp = DetectLoadCompleteSigPath(de_ctx, load);
273  if (loadp == NULL) {
274  return -1;
275  }
276  SCLogDebug("loadp %s", loadp);
277 
278  if (SCPathExists(loadp)) {
279  strlcpy(load, loadp, load_size);
280  SCLogDebug("using path '%s' (non-HAVE_LIBGEN_H)", load);
281  } else {
282  SCLogDebug("path '%s' does not exist (non-HAVE_LIBGEN_H)", loadp);
283  }
284  SCFree(loadp);
285 
286  // TODO try data-dir as well?
287  }
288  return 0;
289 }
290 
291 static int DetectDatarepSetup (DetectEngineCtx *de_ctx, Signature *s, const char *rawstr)
292 {
293  SigMatch *sm = NULL;
294  char cmd_str[16] = "", name[64] = "";
296  char load[PATH_MAX] = "";
297  uint16_t value = 0;
298  uint64_t memcap = 0;
299  uint32_t hashsize = 0;
300 
301  if (DetectBufferGetActiveList(de_ctx, s) == -1) {
303  "datarep is only supported for sticky buffers");
304  SCReturnInt(-1);
305  }
306 
307  int list = s->init_data->list;
308  if (list == DETECT_SM_LIST_NOTSET) {
310  "datarep is only supported for sticky buffers");
311  SCReturnInt(-1);
312  }
313 
314  if (!DetectDatarepParse(rawstr, cmd_str, sizeof(cmd_str), name, sizeof(name), &type, load,
315  sizeof(load), &value, &memcap, &hashsize)) {
316  return -1;
317  }
318 
319  if (strlen(load) != 0) {
320  if (SetupLoadPath(de_ctx, load, sizeof(load)) != 0)
321  return -1;
322  }
323 
324  enum DetectDatarepOp op;
325  if (strcmp(cmd_str,">") == 0) {
326  op = DATAREP_OP_GT;
327  } else if (strcmp(cmd_str,"<") == 0) {
328  op = DATAREP_OP_LT;
329  } else if (strcmp(cmd_str,"==") == 0) {
330  op = DATAREP_OP_EQ;
331  } else {
333  "datarep operation \"%s\" is not supported.", cmd_str);
334  return -1;
335  }
336 
337  Dataset *set = DatasetGet(name, type, /* no save */ NULL, load, memcap, hashsize);
338  if (set == NULL) {
340  "failed to set up datarep set '%s'.", name);
341  return -1;
342  }
343 
344  DetectDatarepData *cd = SCCalloc(1, sizeof(DetectDatarepData));
345  if (unlikely(cd == NULL))
346  goto error;
347 
348  cd->set = set;
349  cd->op = op;
350  cd->rep.value = value;
351 
352  SCLogDebug("cmd %s, name %s",
353  cmd_str, strlen(name) ? name : "(none)");
354 
355  /* Okay so far so good, lets get this into a SigMatch
356  * and put it in the Signature. */
357  sm = SigMatchAlloc();
358  if (sm == NULL)
359  goto error;
360 
361  sm->type = DETECT_DATAREP;
362  sm->ctx = (SigMatchCtx *)cd;
363  SigMatchAppendSMToList(s, sm, list);
364  return 0;
365 
366 error:
367  if (cd != NULL)
368  SCFree(cd);
369  if (sm != NULL)
370  SCFree(sm);
371  return -1;
372 }
373 
375 {
377 
378  if (fd == NULL)
379  return;
380 
381  SCFree(fd);
382 }
util-byte.h
SigTableElmt_::url
const char * url
Definition: detect.h:1204
detect-engine.h
StringParseUint16
int StringParseUint16(uint16_t *res, int base, uint16_t len, const char *str)
Definition: util-byte.c:336
DataRepResultType::rep
DataRepType rep
Definition: datasets-reputation.h:33
SigTableElmt_::desc
const char * desc
Definition: detect.h:1203
SC_ERR_INVALID_VALUE
@ SC_ERR_INVALID_VALUE
Definition: util-error.h:160
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1191
DetectParseRegex
Definition: detect-parse.h:42
SigTableElmt_::name
const char * name
Definition: detect.h:1201
DetectEngineCtx_::rule_file
char * rule_file
Definition: detect.h:863
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
DetectDatarepData_
Definition: detect-datarep.h:36
threads.h
DetectDatarepMatch
int DetectDatarepMatch(ThreadVars *, DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *)
DetectEngineCtx_
main detection engine ctx
Definition: detect.h:758
DETECT_DATAREP
@ DETECT_DATAREP
Definition: detect-engine-register.h:100
DataRepResultType::found
bool found
Definition: datasets-reputation.h:32
SC_ERR_INVALID_SIGNATURE
@ SC_ERR_INVALID_SIGNATURE
Definition: util-error.h:69
DATASET_TYPE_SHA256
@ DATASET_TYPE_SHA256
Definition: datasets.h:34
DetectDatarepRegister
void DetectDatarepRegister(void)
Definition: detect-datarep.c:51
DATAREP_OP_EQ
@ DATAREP_OP_EQ
Definition: detect-datarep.h:33
DetectBufferGetActiveList
int DetectBufferGetActiveList(DetectEngineCtx *de_ctx, Signature *s)
Definition: detect-engine.c:954
SigTableElmt_::Setup
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition: detect.h:1186
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
DataRepResultType
Definition: datasets-reputation.h:31
DatasetGet
Dataset * DatasetGet(const char *name, enum DatasetTypes type, const char *save, const char *load, uint64_t memcap, uint32_t hashsize)
Definition: datasets.c:423
datasets.h
decode.h
util-debug.h
type
uint8_t type
Definition: decode-icmpv4.h:0
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:17
DetectEngineThreadCtx_
Definition: detect.h:1003
SC_ERR_UNKNOWN_VALUE
@ SC_ERR_UNKNOWN_VALUE
Definition: util-error.h:159
DetectDatarepData_::rep
DataRepType rep
Definition: detect-datarep.h:40
DATASET_TYPE_NOTSET
#define DATASET_TYPE_NOTSET
Definition: datasets.h:31
DetectSetupParseRegexes
void DetectSetupParseRegexes(const char *parse_str, DetectParseRegex *detect_parse)
Definition: detect-parse.c:2558
SignatureInitData_::list
int list
Definition: detect.h:494
util-print.h
detect-engine-mpm.h
DetectDatarepOp
DetectDatarepOp
Definition: detect-datarep.h:30
detect.h
ThreadVars_
Per thread variable structure.
Definition: threadvars.h:58
SigMatch_::ctx
SigMatchCtx * ctx
Definition: detect.h:323
BUG_ON
#define BUG_ON(x)
Definition: suricata-common.h:281
Packet_
Definition: decode.h:414
DATAREP_OP_LT
@ DATAREP_OP_LT
Definition: detect-datarep.h:32
Signature_::init_data
SignatureInitData * init_data
Definition: detect.h:587
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
SigMatch_::type
uint8_t type
Definition: detect.h:321
SigMatchCtx_
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition: detect.h:315
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
DatasetTypes
DatasetTypes
Definition: datasets.h:30
DetectDatarepBufferMatch
int DetectDatarepBufferMatch(DetectEngineThreadCtx *det_ctx, const DetectDatarepData *sd, const uint8_t *data, const uint32_t data_len)
Definition: detect-datarep.c:67
suricata-common.h
DATAREP_OP_GT
@ DATAREP_OP_GT
Definition: detect-datarep.h:31
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
DetectDatarepData_::set
Dataset * set
Definition: detect-datarep.h:37
DataRepType::value
uint16_t value
Definition: datasets-reputation.h:28
ParseSizeStringU32
int ParseSizeStringU32(const char *size, uint32_t *res)
Definition: util-misc.c:183
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
detect-datarep.h
SCFree
#define SCFree(p)
Definition: util-mem.h:61
detect-parse.h
Signature_
Signature container.
Definition: detect.h:517
SigMatch_
a single match condition for a signature
Definition: detect.h:320
DATASET_TYPE_MD5
@ DATASET_TYPE_MD5
Definition: datasets.h:33
DATASET_TYPE_STRING
@ DATASET_TYPE_STRING
Definition: datasets.h:32
DetectDatarepFree
void DetectDatarepFree(DetectEngineCtx *, void *)
Definition: detect-datarep.c:374
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
Dataset
Definition: datasets.h:38
DetectDatarepData_::op
enum DetectDatarepOp op
Definition: detect-datarep.h:39
util-misc.h
PARSE_REGEX
#define PARSE_REGEX
Definition: detect-datarep.c:43
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
DatasetLookupwRep
DataRepResultType DatasetLookupwRep(Dataset *set, const uint8_t *data, const uint32_t data_len, const DataRepType *rep)
Definition: datasets.c:970