suricata
detect-filename.c
Go to the documentation of this file.
1/* Copyright (C) 2007-2022 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 * \author Pablo Rincon <pablo.rincon.crespo@gmail.com>
23 *
24 */
25
26#include "suricata-common.h"
27#include "threads.h"
28#include "decode.h"
29
30#include "detect.h"
31
32#include "detect-engine.h"
34#include "detect-engine-mpm.h"
35#include "detect-engine-state.h"
36#include "detect-engine-file.h"
39
40#include "detect-parse.h"
41#include "detect-content.h"
42#include "detect-file-data.h"
43
44#include "flow.h"
45#include "flow-var.h"
46#include "flow-util.h"
47
48#include "util-debug.h"
49#include "util-spm-bm.h"
50#include "util-unittest.h"
52#include "util-profiling.h"
53
54#include "app-layer.h"
55#include "app-layer-htp.h"
56
57#include "stream-tcp.h"
58
59#include "detect-filename.h"
60#include "app-layer-parser.h"
61
62static int DetectFileextSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str);
63static int DetectFilenameSetup (DetectEngineCtx *, Signature *, const char *);
64static int DetectFilenameSetupSticky(DetectEngineCtx *de_ctx, Signature *s, const char *str);
65#ifdef UNITTESTS
66static void DetectFilenameRegisterTests(void);
67#endif
68static int g_file_match_list_id = 0;
69static int g_file_name_buffer_id = 0;
70
71static int PrefilterMpmFilenameRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx,
72 const DetectBufferMpmRegistry *mpm_reg, int list_id);
73static uint8_t DetectEngineInspectFilename(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
74 const DetectEngineAppInspectionEngine *engine, const Signature *s, Flow *f, uint8_t flags,
75 void *alstate, void *txv, uint64_t tx_id);
76
77/**
78 * \brief Registration function for keyword: filename
79 */
81{
83 sigmatch_table[DETECT_FILENAME].desc = "match on the file name";
84 sigmatch_table[DETECT_FILENAME].url = "/rules/file-keywords.html#filename";
85 sigmatch_table[DETECT_FILENAME].Setup = DetectFilenameSetup;
86#ifdef UNITTESTS
87 sigmatch_table[DETECT_FILENAME].RegisterTests = DetectFilenameRegisterTests;
88#endif
91
93 sigmatch_table[DETECT_FILEEXT].desc = "match on the extension of a file name";
94 sigmatch_table[DETECT_FILEEXT].url = "/rules/file-keywords.html#fileext";
95 sigmatch_table[DETECT_FILEEXT].Setup = DetectFileextSetup;
98
100 sigmatch_table[DETECT_FILE_NAME].desc = "sticky buffer to match on the file name";
101 sigmatch_table[DETECT_FILE_NAME].url = "/rules/file-keywords.html#filename";
102 sigmatch_table[DETECT_FILE_NAME].Setup = DetectFilenameSetupSticky;
105
106 DetectBufferTypeSetDescriptionByName("file.name", "file name");
107
108 g_file_match_list_id = DetectBufferTypeRegister("files");
109 g_file_name_buffer_id = DetectBufferTypeRegister("file.name");
110
111 SCLogDebug("registering filename rule option");
116
119 filehandler_table[DETECT_FILE_NAME].PrefilterFn = PrefilterMpmFilenameRegister;
120 filehandler_table[DETECT_FILE_NAME].Callback = DetectEngineInspectFilename;
121
123}
124
125static int DetectFileextSetup(DetectEngineCtx *de_ctx, Signature *s, const char *str)
126{
127 if (s->init_data->transforms.cnt) {
128 SCLogError("previous transforms not consumed before 'fileext'");
129 SCReturnInt(-1);
130 }
133
134 size_t dotstr_len = strlen(str) + 2;
135 char *dotstr = SCCalloc(1, dotstr_len);
136 if (dotstr == NULL)
137 return -1;
138 dotstr[0] = '.';
139 strlcat(dotstr, str, dotstr_len);
140
141 if (DetectContentSetup(de_ctx, s, dotstr) < 0) {
142 SCFree(dotstr);
143 return -1;
144 }
145 SCFree(dotstr);
146
148 if (sm == NULL)
149 return -1;
150
152 cd->flags |= DETECT_CONTENT_ENDS_WITH;
154 return -1;
156 de_ctx, s, NULL, DETECT_FILE_NAME, g_file_name_buffer_id, s->alproto) < 0)
157 return -1;
158
159 return 0;
160}
161/**
162 * \brief this function is used to parse filename options
163 * \brief into the current signature
164 *
165 * \param de_ctx pointer to the Detection Engine Context
166 * \param s pointer to the Current Signature
167 * \param str pointer to the user provided "filename" option
168 *
169 * \retval 0 on Success
170 * \retval -1 on Failure
171 */
172static int DetectFilenameSetup (DetectEngineCtx *de_ctx, Signature *s, const char *str)
173{
174 if (s->init_data->transforms.cnt) {
175 SCLogError("previous transforms not consumed before 'filename'");
176 SCReturnInt(-1);
177 }
180
181 if (DetectContentSetup(de_ctx, s, str) < 0) {
182 return -1;
183 }
184
186 if (sm == NULL)
187 return -1;
188
191 return -1;
193 de_ctx, s, NULL, DETECT_FILE_NAME, g_file_name_buffer_id, s->alproto) < 0)
194 return -1;
195
196 return 0;
197}
198
199/* file.name implementation */
200
201/**
202 * \brief this function setup the file.data keyword used in the rule
203 *
204 * \param de_ctx Pointer to the Detection Engine Context
205 * \param s Pointer to the Signature to which the current keyword belongs
206 * \param str Should hold an empty string always
207 *
208 * \retval 0 On success
209 */
210static int DetectFilenameSetupSticky(DetectEngineCtx *de_ctx, Signature *s, const char *str)
211{
212 if (SCDetectBufferSetActiveList(de_ctx, s, g_file_name_buffer_id) < 0)
213 return -1;
215 return 0;
216}
217
218static InspectionBuffer *FilenameGetDataCallback(DetectEngineThreadCtx *det_ctx,
219 const DetectEngineTransforms *transforms, Flow *f, uint8_t flow_flags, File *cur_file,
220 int list_id, int local_file_id)
221{
222 SCEnter();
223
224 InspectionBuffer *buffer = InspectionBufferMultipleForListGet(det_ctx, list_id, local_file_id);
225 if (buffer == NULL)
226 return NULL;
227 if (buffer->initialized)
228 return buffer;
229
230 const uint8_t *data = cur_file->name;
231 uint32_t data_len = cur_file->name_len;
232
233 InspectionBufferSetupMulti(det_ctx, buffer, transforms, data, data_len);
234
235 SCReturnPtr(buffer, "InspectionBuffer");
236}
237
238static uint8_t DetectEngineInspectFilename(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
239 const DetectEngineAppInspectionEngine *engine, const Signature *s, Flow *f, uint8_t flags,
240 void *alstate, void *txv, uint64_t tx_id)
241{
242 const DetectEngineTransforms *transforms = NULL;
243 if (!engine->mpm) {
244 transforms = engine->v2.transforms;
245 }
246
248 FileContainer *ffc = files.fc;
249 if (ffc == NULL || ffc->head == NULL) {
250 const bool eof = (AppLayerParserGetStateProgress(f->proto, f->alproto, txv, flags) >
251 engine->progress);
252 if (eof && engine->match_on_null) {
254 }
255 if (ffc != NULL) {
257 }
259 }
260
262 int local_file_id = 0;
263 for (File *file = ffc->head; file != NULL; file = file->next) {
264 InspectionBuffer *buffer = FilenameGetDataCallback(
265 det_ctx, transforms, f, flags, file, engine->sm_list, local_file_id);
266 if (buffer == NULL) {
267 local_file_id++;
268 continue;
269 }
270
271 const bool match = DetectEngineContentInspection(de_ctx, det_ctx, s, engine->smd, NULL, f,
272 buffer->inspect, buffer->inspect_len, buffer->inspect_offset,
274 if (match) {
276 } else {
278 }
279 local_file_id++;
280 }
281 return r;
282}
283
289
290/** \brief Filedata Filedata Mpm prefilter callback
291 *
292 * \param det_ctx detection engine thread ctx
293 * \param p packet to inspect
294 * \param f flow to inspect
295 * \param txv tx to inspect
296 * \param pectx inspection context
297 */
298static void PrefilterTxFilename(DetectEngineThreadCtx *det_ctx, const void *pectx, Packet *p,
299 Flow *f, void *txv, const uint64_t idx, const AppLayerTxData *txd, const uint8_t flags)
300{
301 SCEnter();
302
304 return;
305
306 const PrefilterMpmFilename *ctx = (const PrefilterMpmFilename *)pectx;
307 const MpmCtx *mpm_ctx = ctx->mpm_ctx;
308 const int list_id = ctx->list_id;
309
311 FileContainer *ffc = files.fc;
312 if (ffc != NULL) {
313 int local_file_id = 0;
314 for (File *file = ffc->head; file != NULL; file = file->next) {
315 InspectionBuffer *buffer = FilenameGetDataCallback(
316 det_ctx, ctx->transforms, f, flags, file, list_id, local_file_id);
317 if (buffer == NULL)
318 continue;
319
320 if (buffer->inspect_len >= mpm_ctx->minlen) {
321 (void)mpm_table[mpm_ctx->mpm_type].Search(mpm_ctx, &det_ctx->mtc, &det_ctx->pmq,
322 buffer->inspect, buffer->inspect_len);
324 }
325 local_file_id++;
326 }
327 }
328}
329
330static void PrefilterMpmFilenameFree(void *ptr)
331{
332 SCFree(ptr);
333}
334
335static int PrefilterMpmFilenameRegister(DetectEngineCtx *de_ctx, SigGroupHead *sgh, MpmCtx *mpm_ctx,
336 const DetectBufferMpmRegistry *mpm_reg, int list_id)
337{
338 PrefilterMpmFilename *pectx = SCCalloc(1, sizeof(*pectx));
339 if (pectx == NULL)
340 return -1;
341 pectx->list_id = list_id;
342 pectx->mpm_ctx = mpm_ctx;
343 pectx->transforms = &mpm_reg->transforms;
344
345 return PrefilterAppendTxEngine(de_ctx, sgh, PrefilterTxFilename,
346 mpm_reg->app_v2.alproto, mpm_reg->app_v2.tx_min_progress,
347 pectx, PrefilterMpmFilenameFree, mpm_reg->pname);
348}
349
350#ifdef UNITTESTS /* UNITTESTS */
351
352/**
353 * \test Test parser accepting valid rules and rejecting invalid rules
354 */
355static int DetectFilenameSignatureParseTest01(void)
356{
357 FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; sid:1;)", true));
358 FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; nocase; sid:1;)", true));
359 FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; endswith; sid:1;)", true));
360 FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; startswith; sid:1;)", true));
361 FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; startswith; endswith; sid:1;)", true));
362 FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; bsize:10; sid:1;)", true));
363
364 FAIL_IF_NOT(UTHParseSignature("alert http any any -> any any (flow:to_client; file.name; content:\"abc\"; rawbytes; sid:1;)", false));
365 FAIL_IF_NOT(UTHParseSignature("alert tcp any any -> any any (flow:to_client; file.name; sid:1;)", false));
366 //FAIL_IF_NOT(UTHParseSignature("alert tls any any -> any any (flow:to_client; file.name; content:\"abc\"; sid:1;)", false));
367 PASS;
368}
369/**
370 * \brief this function registers unit tests for DetectFilename
371 */
372void DetectFilenameRegisterTests(void)
373{
374 UtRegisterTest("DetectFilenameSignatureParseTest01", DetectFilenameSignatureParseTest01);
375}
376#endif /* UNITTESTS */
AppLayerGetFileState AppLayerParserGetTxFiles(const Flow *f, void *tx, const uint8_t direction)
int AppLayerParserGetStateProgress(uint8_t ipproto, AppProto alproto, void *alstate, uint8_t flags)
get the progress value for a tx/protocol
struct AppLayerGetFileState AppLayerGetFileState
struct AppLayerTxData AppLayerTxData
#define AppLayerParserHasFilesInDir(txd, direction)
check if tx (possibly) has files in this tx for the direction
uint8_t flags
Definition decode-gre.h:0
int DetectContentSetup(DetectEngineCtx *de_ctx, Signature *s, const char *contentstr)
Function to setup a content pattern.
int DetectContentConvertToNocase(DetectEngineCtx *de_ctx, DetectContentData *cd)
#define DETECT_CONTENT_ENDS_WITH
int SCDetectBufferSetActiveList(DetectEngineCtx *de_ctx, Signature *s, const int list)
bool DetectEngineContentInspection(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const Signature *s, const SigMatchData *smd, Packet *p, Flow *f, const uint8_t *buffer, const uint32_t buffer_len, const uint64_t stream_start_offset, const uint8_t flags, const enum DetectContentInspectionType inspection_mode)
wrapper around DetectEngineContentInspectionInternal to return true/false only
@ DETECT_ENGINE_CONTENT_INSPECTION_MODE_STATE
#define DETECT_CI_FLAGS_SINGLE
uint8_t DetectFileInspectGeneric(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx, const struct DetectEngineAppInspectionEngine_ *engine, const Signature *s, Flow *f, uint8_t flags, void *alstate, void *tx, uint64_t tx_id)
Inspect the file inspecting keywords against the state.
InspectionBuffer * InspectionBufferMultipleForListGet(DetectEngineThreadCtx *det_ctx, const int list_id, const uint32_t local_id)
for a InspectionBufferMultipleForList get a InspectionBuffer
void InspectionBufferSetupMulti(DetectEngineThreadCtx *det_ctx, InspectionBuffer *buffer, const DetectEngineTransforms *transforms, const uint8_t *data, const uint32_t data_len)
setup the buffer with our initial data
int PrefilterAppendTxEngine(DetectEngineCtx *de_ctx, SigGroupHead *sgh, PrefilterTxFn PrefilterTxFunc, AppProto alproto, int tx_min_progress, void *pectx, void(*FreeFunc)(void *pectx), const char *name)
Data structures and function prototypes for keeping state for the detection engine.
#define DETECT_ENGINE_INSPECT_SIG_MATCH
#define DETECT_ENGINE_INSPECT_SIG_CANT_MATCH_FILES
#define DETECT_ENGINE_INSPECT_SIG_NO_MATCH
int DetectBufferTypeRegister(const char *name)
void DetectBufferTypeSetDescriptionByName(const char *name, const char *desc)
void DetectBufferTypeSupportsMultiInstance(const char *name)
DetectFileHandlerTableElmt filehandler_table[DETECT_TBLSIZE_STATIC]
void DetectFilenameRegister(void)
Registration function for keyword: filename.
int DetectEngineContentModifierBufferSetup(DetectEngineCtx *de_ctx, Signature *s, const char *arg, int sm_type, int sm_list, AppProto alproto)
SigMatch * DetectGetLastSMFromLists(const Signature *s,...)
Returns the sm with the largest index (added latest) from the lists passed to us.
SigTableElmt * sigmatch_table
#define SIGMATCH_SUPPORT_DIR
Definition detect.h:1684
#define FILE_SIG_NEED_FILENAME
Definition detect.h:321
#define DETECT_SM_LIST_NOTSET
Definition detect.h:144
#define SIGMATCH_INFO_STICKY_BUFFER
Definition detect.h:1676
#define FILE_SIG_NEED_FILE
Definition detect.h:320
#define SIGMATCH_QUOTES_OPTIONAL
Definition detect.h:1664
#define SIGMATCH_OPTIONAL_OPT
Definition detect.h:1661
#define SIGMATCH_HANDLE_NEGATION
Definition detect.h:1672
DetectEngineCtx * de_ctx
void UtRegisterTest(const char *name, int(*TestFn)(void))
Register unit test.
#define FAIL_IF_NOT(expr)
Fail a test if expression evaluates to false.
#define PASS
Pass the test.
struct Thresholds ctx
one time registration of keywords at start up
Definition detect.h:762
DetectEngineTransforms transforms
Definition detect.h:775
struct DetectBufferMpmRegistry_::@98::@100 app_v2
const DetectEngineTransforms * transforms
Definition detect.h:436
struct DetectEngineAppInspectionEngine_::@90 v2
main detection engine ctx
Definition detect.h:932
MpmThreadCtx mtc
Definition detect.h:1345
PrefilterRuleStore pmq
Definition detect.h:1349
PrefilterRegisterFunc PrefilterFn
InspectEngineFuncPtr Callback
uint8_t * name
Definition util-file.h:88
uint16_t name_len
Definition util-file.h:81
Flow data structure.
Definition flow.h:356
uint8_t proto
Definition flow.h:378
AppProto alproto
application level protocol
Definition flow.h:450
uint8_t mpm_type
Definition util-mpm.h:95
uint16_t minlen
Definition util-mpm.h:104
uint32_t(* Search)(const struct MpmCtx_ *, struct MpmThreadCtx_ *, PrefilterRuleStore *, const uint8_t *, uint32_t)
Definition util-mpm.h:178
const DetectEngineTransforms * transforms
Container for matching data for a signature group.
Definition detect.h:1629
a single match condition for a signature
Definition detect.h:356
SigMatchCtx * ctx
Definition detect.h:359
const char * url
Definition detect.h:1462
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition detect.h:1441
uint16_t alternative
Definition detect.h:1457
uint16_t flags
Definition detect.h:1450
const char * desc
Definition detect.h:1461
void(* RegisterTests)(void)
Definition detect.h:1448
const char * name
Definition detect.h:1459
DetectEngineTransforms transforms
Definition detect.h:631
Signature container.
Definition detect.h:668
SignatureInitData * init_data
Definition detect.h:747
AppProto alproto
Definition detect.h:673
uint8_t file_flags
Definition detect.h:684
size_t strlcat(char *, const char *src, size_t siz)
#define str(s)
#define SCEnter(...)
Definition util-debug.h:277
#define SCLogDebug(...)
Definition util-debug.h:275
#define SCReturnInt(x)
Definition util-debug.h:281
#define SCReturnPtr(x, type)
Definition util-debug.h:293
#define SCLogError(...)
Macro used to log ERROR messages.
Definition util-debug.h:267
#define SCFree(p)
Definition util-mem.h:61
#define SCCalloc(nm, sz)
Definition util-mem.h:53
MpmTableElmt mpm_table[MPM_TABLE_SIZE]
Definition util-mpm.c:47
#define PREFILTER_PROFILING_ADD_BYTES(det_ctx, bytes)
int UTHParseSignature(const char *str, bool expect)
parser a sig and see if the expected result is correct