suricata
detect-filestore.c
Go to the documentation of this file.
1/* Copyright (C) 2007-2021 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 filestore keyword
24 */
25
26#include "suricata-common.h"
27#include "threads.h"
28#include "decode.h"
29
30#include "detect.h"
31#include "detect-parse.h"
32
33#include "detect-engine.h"
34#include "detect-engine-mpm.h"
35#include "detect-engine-state.h"
36
37#include "feature.h"
38
39#include "flow.h"
40#include "flow-var.h"
41#include "flow-util.h"
42
43#include "util-debug.h"
44#include "util-spm-bm.h"
45#include "util-unittest.h"
47
48#include "app-layer.h"
49#include "app-layer-parser.h"
50#include "app-layer-htp.h"
51
52#include "stream-tcp.h"
53
54#include "detect-filestore.h"
55
56#include "util-validate.h"
57
58/**
59 * \brief Regex for parsing our flow options
60 */
61#define PARSE_REGEX "^\\s*([A-z_]+)\\s*(?:,\\s*([A-z_]+))?\\s*(?:,\\s*([A-z_]+))?\\s*$"
62
63static DetectParseRegex parse_regex;
64
65static int DetectFilestoreMatch (DetectEngineThreadCtx *,
66 Flow *, uint8_t, File *, const Signature *, const SigMatchCtx *);
67static int DetectFilestorePostMatch(DetectEngineThreadCtx *det_ctx,
68 Packet *p, const Signature *s, const SigMatchCtx *ctx);
69static int DetectFilestoreSetup (DetectEngineCtx *, Signature *, const char *);
70static void DetectFilestoreFree(DetectEngineCtx *, void *);
71#ifdef UNITTESTS
72static void DetectFilestoreRegisterTests(void);
73#endif
74static int g_file_match_list_id = 0;
75
76/**
77 * \brief Registration function for keyword: filestore
78 */
80{
82 sigmatch_table[DETECT_FILESTORE].desc = "stores files to disk if the rule matched";
83 sigmatch_table[DETECT_FILESTORE].url = "/rules/file-keywords.html#filestore";
84 sigmatch_table[DETECT_FILESTORE].FileMatch = DetectFilestoreMatch;
85 sigmatch_table[DETECT_FILESTORE].Setup = DetectFilestoreSetup;
86 sigmatch_table[DETECT_FILESTORE].Free = DetectFilestoreFree;
87#ifdef UNITTESTS
88 sigmatch_table[DETECT_FILESTORE].RegisterTests = DetectFilestoreRegisterTests;
89#endif
91
92 sigmatch_table[DETECT_FILESTORE_POSTMATCH].name = "__filestore__postmatch__";
93 sigmatch_table[DETECT_FILESTORE_POSTMATCH].Match = DetectFilestorePostMatch;
94 sigmatch_table[DETECT_FILESTORE_POSTMATCH].Free = DetectFilestoreFree;
95
97
98 g_file_match_list_id = DetectBufferTypeRegister("files");
99}
100
101/**
102 * \brief apply the post match filestore with options
103 */
104static int FilestorePostMatchWithOptions(Packet *p, Flow *f, const DetectFilestoreData *filestore,
105 FileContainer *fc, uint32_t file_id, uint64_t tx_id)
106{
107 if (filestore == NULL) {
108 SCReturnInt(0);
109 }
110
111 int this_file = 0;
112 int this_tx = 0;
113 int this_flow = 0;
114 int rule_dir = 0;
115 int toserver_dir = 0;
116 int toclient_dir = 0;
117
118 switch (filestore->direction) {
120 rule_dir = 1;
121 // will use both sides if scope is not default
122 // fallthrough
124 toserver_dir = 1;
125 toclient_dir = 1;
126 break;
128 toserver_dir = 1;
129 break;
131 toclient_dir = 1;
132 break;
133 }
134
135 switch (filestore->scope) {
137 if (rule_dir) {
138 this_file = 1;
139 } else if ((p->flowflags & FLOW_PKT_TOCLIENT) && toclient_dir) {
140 this_file = 1;
141 } else if ((p->flowflags & FLOW_PKT_TOSERVER) && toserver_dir) {
142 this_file = 1;
143 }
144 break;
146 this_tx = 1;
147 break;
149 this_flow = 1;
150 break;
151 }
152
153 if (this_file) {
154 FileStoreFileById(fc, file_id);
155 } else if (this_tx) {
156 /* set in AppLayerTxData. Parsers and logger will propagate it to the
157 * individual files, both new and current. */
158 void *txv = AppLayerParserGetTx(f->proto, f->alproto, f->alstate, tx_id);
159 DEBUG_VALIDATE_BUG_ON(txv == NULL);
160 if (txv != NULL) {
162 if (toclient_dir) {
163 txd->file_flags |= FLOWFILE_STORE_TC;
164 }
165 if (toserver_dir) {
166 txd->file_flags |= FLOWFILE_STORE_TS;
167 }
168 }
169 } else if (this_flow) {
170 /* set in flow and AppLayerStateData */
172 if (toclient_dir) {
174 if (sd != NULL) {
175 sd->file_flags |= FLOWFILE_STORE_TC;
176 }
177 }
178 if (toserver_dir) {
180 if (sd != NULL) {
181 sd->file_flags |= FLOWFILE_STORE_TS;
182 }
183 }
184 } else {
185 FileStoreFileById(fc, file_id);
186 }
187
188 SCReturnInt(0);
189}
190
191/**
192 * \brief post-match function for filestore
193 *
194 * \param t thread local vars
195 * \param det_ctx pattern matcher thread local data
196 * \param p packet
197 *
198 * The match function for filestore records store candidates in the det_ctx.
199 * When we are sure all parts of the signature matched, we run this function
200 * to finalize the filestore.
201 */
202static int DetectFilestorePostMatch(DetectEngineThreadCtx *det_ctx,
203 Packet *p, const Signature *s, const SigMatchCtx *ctx)
204{
205 SCEnter();
206
207 if (det_ctx->filestore_cnt == 0) {
208 SCReturnInt(0);
209 }
210
211 if ((s->filestore_ctx == NULL && !(s->flags & SIG_FLAG_FILESTORE)) || p->flow == NULL) {
212#ifndef DEBUG
213 SCReturnInt(0);
214#else
215 BUG_ON(1);
216#endif
217 }
218
219 if (p->flow->proto == IPPROTO_TCP && p->flow->protoctx != NULL) {
220 /* set filestore depth for stream reassembling */
221 TcpSession *ssn = (TcpSession *)p->flow->protoctx;
223 }
224
225 SCLogDebug("s->filestore_ctx %p", s->filestore_ctx);
226
227 const uint8_t flags = STREAM_FLAGS_FOR_PACKET(p);
228 for (uint16_t u = 0; u < det_ctx->filestore_cnt; u++) {
229 void *alstate = FlowGetAppState(p->flow);
231 p->flow->proto, p->flow->alproto, alstate, det_ctx->filestore[u].tx_id, flags);
232
233 void *txv = AppLayerParserGetTx(
234 p->flow->proto, p->flow->alproto, alstate, det_ctx->filestore[u].tx_id);
235 DEBUG_VALIDATE_BUG_ON(txv == NULL);
236 if (txv) {
238 FileContainer *ffc_tx = files.fc;
239 DEBUG_VALIDATE_BUG_ON(ffc_tx == NULL);
240 if (ffc_tx) {
241 SCLogDebug("u %u txv %p ffc_tx %p file_id %u", u, txv, ffc_tx,
242 det_ctx->filestore[u].file_id);
243
244 /* filestore for single files only */
245 if (s->filestore_ctx == NULL) {
246 FileStoreFileById(ffc_tx, det_ctx->filestore[u].file_id);
247 } else {
248 FilestorePostMatchWithOptions(p, p->flow, s->filestore_ctx, ffc_tx,
249 det_ctx->filestore[u].file_id, det_ctx->filestore[u].tx_id);
250 }
251 }
252 }
253 }
254 SCReturnInt(0);
255}
256
257/**
258 * \brief match the specified filestore
259 *
260 * \param t thread local vars
261 * \param det_ctx pattern matcher thread local data
262 * \param f *LOCKED* flow
263 * \param flags direction flags
264 * \param file file being inspected
265 * \param s signature being inspected
266 * \param m sigmatch that we will cast into DetectFilestoreData
267 *
268 * \retval 0 no match
269 * \retval 1 match
270 *
271 * \todo when we start supporting more protocols, the logic in this function
272 * needs to be put behind a api.
273 */
274static int DetectFilestoreMatch (DetectEngineThreadCtx *det_ctx, Flow *f,
275 uint8_t flags, File *file, const Signature *s, const SigMatchCtx *m)
276{
277 uint32_t file_id = 0;
278
279 SCEnter();
280
281 if (!RunmodeIsUnittests()) {
282 extern bool g_filedata_logger_enabled;
284 SCLogDebug("not storing file match: no filedata logger enabled");
285 SCReturnInt(1);
286 }
287 }
288 if (det_ctx->filestore_cnt >= DETECT_FILESTORE_MAX) {
289 SCReturnInt(1);
290 }
291
292 /* file can be NULL when a rule with filestore scope > file
293 * matches. */
294 if (file != NULL) {
295 file_id = file->file_track_id;
296 if (file->sid != NULL && s->id > 0) {
297 if (file->sid_cnt >= file->sid_max) {
298 void *p = SCRealloc(file->sid, sizeof(uint32_t) * (file->sid_max + 8));
299 if (p == NULL) {
300 SCFree(file->sid);
301 file->sid = NULL;
302 file->sid_cnt = 0;
303 file->sid_max = 0;
304 goto continue_after_realloc_fail;
305 } else {
306 file->sid = p;
307 file->sid_max += 8;
308 }
309 }
310 file->sid[file->sid_cnt] = s->id;
311 file->sid_cnt++;
312 }
313 }
314
315continue_after_realloc_fail:
316
317 det_ctx->filestore[det_ctx->filestore_cnt].file_id = file_id;
318 det_ctx->filestore[det_ctx->filestore_cnt].tx_id = det_ctx->tx_id;
319
320 SCLogDebug("%u, file %u, tx %"PRIu64, det_ctx->filestore_cnt,
321 det_ctx->filestore[det_ctx->filestore_cnt].file_id,
322 det_ctx->filestore[det_ctx->filestore_cnt].tx_id);
323
324 det_ctx->filestore_cnt++;
325 SCReturnInt(1);
326}
327
328/**
329 * \brief this function is used to parse filestore options
330 * \brief into the current signature
331 *
332 * \param de_ctx pointer to the Detection Engine Context
333 * \param s pointer to the Current Signature
334 * \param str pointer to the user provided "filestore" option
335 *
336 * \retval 0 on Success
337 * \retval -1 on Failure
338 */
339static int DetectFilestoreSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str)
340{
341 SCEnter();
342
343 static bool warn_not_configured = false;
344 static uint32_t de_version = 0;
345
346 if (de_ctx->filestore_cnt == UINT16_MAX) {
347 SCLogError("Cannot have more than 65535 filestore signatures");
348 return -1;
349 }
350
351 /* Check on first-time loads (includes following a reload) */
352 if (!warn_not_configured || (de_ctx->version != de_version)) {
353 if (de_version != de_ctx->version) {
354 SCLogDebug("reload-detected; re-checking feature presence; DE version now %"PRIu32,
355 de_ctx->version);
356 }
358 SCLogWarning("One or more rule(s) depends on the "
359 "file-store output log which is not enabled. "
360 "Enable the output \"file-store\".");
361 }
362 warn_not_configured = true;
363 de_version = de_ctx->version;
364 }
365
366 DetectFilestoreData *fd = NULL;
367 char *args[3] = {NULL,NULL,NULL};
368 int res = 0;
369 size_t pcre2len;
370 pcre2_match_data *match = NULL;
371
372 /* filestore and bypass keywords can't work together */
373 if (s->flags & SIG_FLAG_BYPASS) {
374 SCLogError("filestore can't work with bypass keyword");
375 return -1;
376 }
377
378 if (str != NULL && strlen(str) > 0) {
379 char str_0[32];
380 char str_1[32];
381 char str_2[32];
382 SCLogDebug("str %s", str);
383
384 int ret = DetectParsePcreExec(&parse_regex, &match, str, 0, 0);
385 if (ret < 1 || ret > 4) {
386 SCLogError("parse error, ret %" PRId32 ", string %s", ret, str);
387 goto error;
388 }
389
390 if (ret > 1) {
391 pcre2len = sizeof(str_0);
392 res = pcre2_substring_copy_bynumber(match, 1, (PCRE2_UCHAR8 *)str_0, &pcre2len);
393 if (res < 0) {
394 SCLogError("pcre2_substring_copy_bynumber failed");
395 goto error;
396 }
397 args[0] = (char *)str_0;
398
399 if (ret > 2) {
400 pcre2len = sizeof(str_1);
401 res = pcre2_substring_copy_bynumber(match, 2, (PCRE2_UCHAR8 *)str_1, &pcre2len);
402 if (res < 0) {
403 SCLogError("pcre2_substring_copy_bynumber failed");
404 goto error;
405 }
406 args[1] = (char *)str_1;
407 }
408 if (ret > 3) {
409 pcre2len = sizeof(str_2);
410 res = pcre2_substring_copy_bynumber(match, 3, (PCRE2_UCHAR8 *)str_2, &pcre2len);
411 if (res < 0) {
412 SCLogError("pcre2_substring_copy_bynumber failed");
413 goto error;
414 }
415 args[2] = (char *)str_2;
416 }
417 }
418
419 fd = SCCalloc(1, sizeof(DetectFilestoreData));
420 if (unlikely(fd == NULL))
421 goto error;
422
423 if (args[0] != NULL) {
424 SCLogDebug("first arg %s", args[0]);
425
426 if (strcasecmp(args[0], "request") == 0 ||
427 strcasecmp(args[0], "to_server") == 0)
428 {
431 }
432 else if (strcasecmp(args[0], "response") == 0 ||
433 strcasecmp(args[0], "to_client") == 0)
434 {
437 }
438 else if (strcasecmp(args[0], "both") == 0)
439 {
442 }
443 } else {
445 }
446
447 if (args[1] != NULL) {
448 SCLogDebug("second arg %s", args[1]);
449
450 if (strcasecmp(args[1], "file") == 0)
451 {
453 } else if (strcasecmp(args[1], "tx") == 0)
454 {
456 } else if (strcasecmp(args[1], "ssn") == 0 ||
457 strcasecmp(args[1], "flow") == 0)
458 {
460 }
461 } else {
462 if (fd->scope == 0)
464 }
465 }
466
467 if (s->alproto == ALPROTO_HTTP1 || s->alproto == ALPROTO_HTTP) {
469 }
470
472 de_ctx, s, DETECT_FILESTORE, (SigMatchCtx *)fd, g_file_match_list_id) == NULL) {
473 DetectFilestoreFree(de_ctx, fd);
474 goto error;
475 }
476 s->filestore_ctx = fd;
477
480 goto error;
481 }
482
485
486 if (match)
487 pcre2_match_data_free(match);
488
489 return 0;
490
491error:
492 if (match) {
493 pcre2_match_data_free(match);
494 }
495 return -1;
496}
497
498static void DetectFilestoreFree(DetectEngineCtx *de_ctx, void *ptr)
499{
500 if (ptr != NULL) {
501 SCFree(ptr);
502 }
503}
504
505#ifdef UNITTESTS
506/*
507 * The purpose of this test is to confirm that
508 * filestore and bypass keywords can't
509 * can't work together
510 */
511static int DetectFilestoreTest01(void)
512{
513 DetectEngineCtx *de_ctx = NULL;
514 int result = 1;
515
517 FAIL_IF(de_ctx == NULL);
518
520
521 de_ctx->sig_list = SigInit(de_ctx,"alert http any any -> any any "
522 "(bypass; filestore; "
523 "content:\"message\"; http_host; "
524 "sid:1;)");
526
528
529 return result;
530}
531
532void DetectFilestoreRegisterTests(void)
533{
534 UtRegisterTest("DetectFilestoreTest01", DetectFilestoreTest01);
535}
536#endif /* UNITTESTS */
AppLayerTxData * AppLayerParserGetTxData(uint8_t ipproto, AppProto alproto, void *tx)
AppLayerGetFileState AppLayerParserGetTxFiles(const Flow *f, void *tx, const uint8_t direction)
AppLayerStateData * AppLayerParserGetStateData(uint8_t ipproto, AppProto alproto, void *state)
void AppLayerParserSetStreamDepthFlag(uint8_t ipproto, AppProto alproto, void *state, uint64_t tx_id, uint8_t flags)
bool g_filedata_logger_enabled
void * AppLayerParserGetTx(uint8_t ipproto, AppProto alproto, void *alstate, uint64_t tx_id)
struct AppLayerGetFileState AppLayerGetFileState
struct AppLayerTxData AppLayerTxData
struct AppLayerStateData AppLayerStateData
@ ALPROTO_HTTP
@ ALPROTO_HTTP1
uint8_t flags
Definition decode-gre.h:0
@ DETECT_FILESTORE_POSTMATCH
DetectEngineCtx * DetectEngineCtxInit(void)
void DetectEngineCtxFree(DetectEngineCtx *)
Free a DetectEngineCtx::
Data structures and function prototypes for keeping state for the detection engine.
int DetectBufferTypeRegister(const char *name)
void DetectFilestoreRegister(void)
Registration function for keyword: filestore.
#define PARSE_REGEX
Regex for parsing our flow options.
#define FILESTORE_DIR_TOSERVER
#define FILESTORE_SCOPE_TX
#define FILESTORE_DIR_DEFAULT
#define FILESTORE_DIR_TOCLIENT
#define FILESTORE_DIR_BOTH
#define FILESTORE_SCOPE_SSN
#define FILESTORE_SCOPE_DEFAULT
void DetectSetupParseRegexes(const char *parse_str, DetectParseRegex *detect_parse)
int DetectParsePcreExec(DetectParseRegex *parse_regex, pcre2_match_data **match, const char *str, int start_offset, int options)
Signature * SigInit(DetectEngineCtx *de_ctx, const char *sigstr)
Parses a signature and adds it to the Detection Engine Context.
SigMatch * SCSigMatchAppendSMToList(DetectEngineCtx *de_ctx, Signature *s, uint16_t type, SigMatchCtx *ctx, const int list)
Append a SigMatch to the list type.
SigTableElmt * sigmatch_table
#define SIG_FLAG_FILESTORE
Definition detect.h:269
#define DE_QUIET
Definition detect.h:330
#define DETECT_FILESTORE_MAX
Definition detect.h:1189
#define SIGMATCH_OPTIONAL_OPT
Definition detect.h:1661
@ DETECT_SM_LIST_POSTMATCH
Definition detect.h:127
#define SIG_FLAG_BYPASS
Definition detect.h:276
bool RequiresFeature(const char *feature_name)
Definition feature.c:126
#define FEATURE_OUTPUT_FILESTORE
Definition feature.h:28
SCMutex m
Definition flow-hash.h:6
#define FLOW_PKT_TOSERVER
Definition flow.h:233
#define FLOWFILE_STORE_TS
Definition flow.h:153
#define FLOWFILE_STORE_TC
Definition flow.h:154
#define FLOW_PKT_TOCLIENT
Definition flow.h:234
DetectEngineCtx * de_ctx
void UtRegisterTest(const char *name, int(*TestFn)(void))
Register unit test.
#define FAIL_IF(expr)
Fail a test if expression evaluates to true.
#define FAIL_IF_NOT_NULL(expr)
Fail a test if expression evaluates to non-NULL.
void AppLayerHtpNeedFileInspection(void)
Sets a flag that informs the HTP app layer that some module in the engine needs the http request file...
struct Thresholds ctx
void TcpSessionSetReassemblyDepth(TcpSession *ssn, uint32_t size)
#define STREAM_FLAGS_FOR_PACKET(p)
Definition stream.h:30
main detection engine ctx
Definition detect.h:932
uint16_t filestore_cnt
Definition detect.h:1138
uint8_t flags
Definition detect.h:934
Signature * sig_list
Definition detect.h:941
uint32_t version
Definition detect.h:1013
struct DetectEngineThreadCtx_::@111 filestore[DETECT_FILESTORE_MAX]
uint32_t sid_max
Definition util-file.h:110
uint32_t sid_cnt
Definition util-file.h:109
uint32_t * sid
Definition util-file.h:108
uint32_t file_track_id
Definition util-file.h:84
Flow data structure.
Definition flow.h:356
uint8_t proto
Definition flow.h:378
uint16_t file_flags
Definition flow.h:423
AppProto alproto
application level protocol
Definition flow.h:450
void * alstate
Definition flow.h:479
void * protoctx
Definition flow.h:441
uint8_t flowflags
Definition decode.h:532
struct Flow_ * flow
Definition decode.h:546
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition detect.h:351
const char * url
Definition detect.h:1462
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition detect.h:1441
void(* Free)(DetectEngineCtx *, void *)
Definition detect.h:1446
uint16_t flags
Definition detect.h:1450
const char * desc
Definition detect.h:1461
void(* RegisterTests)(void)
Definition detect.h:1448
int(* Match)(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *)
Definition detect.h:1421
const char * name
Definition detect.h:1459
int(* FileMatch)(DetectEngineThreadCtx *, Flow *, uint8_t flags, File *, const Signature *, const SigMatchCtx *)
Definition detect.h:1429
Signature container.
Definition detect.h:668
uint32_t flags
Definition detect.h:669
AppProto alproto
Definition detect.h:673
const struct DetectFilestoreData_ * filestore_ctx
Definition detect.h:734
uint32_t id
Definition detect.h:713
#define BUG_ON(x)
#define str(s)
int RunmodeIsUnittests(void)
Definition suricata.c:270
#define SCEnter(...)
Definition util-debug.h:277
#define SCLogDebug(...)
Definition util-debug.h:275
#define SCReturnInt(x)
Definition util-debug.h:281
#define SCLogWarning(...)
Macro used to log WARNING messages.
Definition util-debug.h:255
#define SCLogError(...)
Macro used to log ERROR messages.
Definition util-debug.h:267
uint32_t FileReassemblyDepth(void)
Definition util-file.c:133
void FileStoreFileById(FileContainer *fc, uint32_t file_id)
flag a file with id "file_id" to be stored.
Definition util-file.c:1157
#define SCFree(p)
Definition util-mem.h:61
#define SCRealloc(ptr, sz)
Definition util-mem.h:50
#define SCCalloc(nm, sz)
Definition util-mem.h:53
#define unlikely(expr)
#define DEBUG_VALIDATE_BUG_ON(exp)