suricata
detect-id.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 Pablo Rincon Crespo <pablo.rincon.crespo@gmail.com>
22 *
23 * Implements the id keyword
24 */
25
26#include "suricata-common.h"
27#include "decode.h"
28#include "detect.h"
29
30#include "detect-parse.h"
31#include "detect-engine.h"
32#include "detect-engine-mpm.h"
34
35#include "detect-id.h"
36#include "flow.h"
37#include "flow-var.h"
38
39#include "util-debug.h"
40#include "util-byte.h"
41#include "util-unittest.h"
43
44/**
45 * \brief Regex for parsing "id" option, matching number or "number"
46 */
47#define PARSE_REGEX "^\\s*([0-9]{1,5}|\"[0-9]{1,5}\")\\s*$"
48
49static DetectParseRegex parse_regex;
50
51static int DetectIdMatch (DetectEngineThreadCtx *, Packet *,
52 const Signature *, const SigMatchCtx *);
53static int DetectIdSetup (DetectEngineCtx *, Signature *, const char *);
54#ifdef UNITTESTS
55static void DetectIdRegisterTests(void);
56#endif
57void DetectIdFree(DetectEngineCtx *, void *);
58
59static int PrefilterSetupId(DetectEngineCtx *de_ctx, SigGroupHead *sgh);
60static bool PrefilterIdIsPrefilterable(const Signature *s);
61
62/**
63 * \brief Registration function for keyword: id
64 */
66{
68 sigmatch_table[DETECT_ID].desc = "match on a specific IP ID value";
69 sigmatch_table[DETECT_ID].url = "/rules/header-keywords.html#id";
70 sigmatch_table[DETECT_ID].Match = DetectIdMatch;
71 sigmatch_table[DETECT_ID].Setup = DetectIdSetup;
73#ifdef UNITTESTS
74 sigmatch_table[DETECT_ID].RegisterTests = DetectIdRegisterTests;
75#endif
76 sigmatch_table[DETECT_ID].SupportsPrefilter = PrefilterIdIsPrefilterable;
77 sigmatch_table[DETECT_ID].SetupPrefilter = PrefilterSetupId;
78
80}
81
82/**
83 * \brief This function is used to match the specified id on a packet
84 *
85 * \param t pointer to thread vars
86 * \param det_ctx pointer to the pattern matcher thread
87 * \param p pointer to the current packet
88 * \param m pointer to the sigmatch that we will cast into DetectIdData
89 *
90 * \retval 0 no match
91 * \retval 1 match
92 */
93static int DetectIdMatch (DetectEngineThreadCtx *det_ctx, Packet *p,
94 const Signature *s, const SigMatchCtx *ctx)
95{
97 const DetectIdData *id_d = (const DetectIdData *)ctx;
98
99 /**
100 * To match a ipv4 packet with a "id" rule
101 */
102 if (!PacketIsIPv4(p)) {
103 return 0;
104 }
105
106 const IPV4Hdr *ip4h = PacketGetIPv4(p);
107 if (id_d->id == IPV4_GET_RAW_IPID(ip4h)) {
108 SCLogDebug("IPV4 Proto and matched with ip_id: %u.\n",
109 id_d->id);
110 return 1;
111 }
112
113 return 0;
114}
115
116/**
117 * \brief This function is used to parse IPV4 ip_id passed via keyword: "id"
118 *
119 * \param idstr Pointer to the user provided id option
120 *
121 * \retval id_d pointer to DetectIdData on success
122 * \retval NULL on failure
123 */
124static DetectIdData *DetectIdParse (const char *idstr)
125{
126 uint16_t temp;
127 DetectIdData *id_d = NULL;
128 int res = 0;
129 size_t pcre2len;
130 pcre2_match_data *match = NULL;
131
132 int ret = DetectParsePcreExec(&parse_regex, &match, idstr, 0, 0);
133
134 if (ret < 1 || ret > 3) {
135 SCLogError("invalid id option '%s'. The id option "
136 "value must be in the range %u - %u",
138 goto error;
139 }
140
141 char copy_str[128] = "";
142 char *tmp_str;
143 pcre2len = sizeof(copy_str);
144 res = pcre2_substring_copy_bynumber(match, 1, (PCRE2_UCHAR8 *)copy_str, &pcre2len);
145 if (res < 0) {
146 SCLogError("pcre2_substring_copy_bynumber failed");
147 goto error;
148 }
149 tmp_str = copy_str;
150
151 /* Let's see if we need to scape "'s */
152 if (tmp_str[0] == '"')
153 {
154 tmp_str[strlen(tmp_str) - 1] = '\0';
155 tmp_str += 1;
156 }
157
158 /* ok, fill the id data */
159 if (StringParseUint16(&temp, 10, 0, (const char *)tmp_str) < 0) {
160 SCLogError("invalid id option '%s'", tmp_str);
161 goto error;
162 }
163
164 /* We have a correct id option */
165 id_d = SCMalloc(sizeof(DetectIdData));
166 if (unlikely(id_d == NULL))
167 goto error;
168
169 id_d->id = temp;
170
171 SCLogDebug("detect-id: will look for ip_id: %u\n", id_d->id);
172 pcre2_match_data_free(match);
173 return id_d;
174
175error:
176 if (match) {
177 pcre2_match_data_free(match);
178 }
179 return NULL;
180}
181
182/**
183 * \brief this function is used to add the parsed "id" option
184 * \brief into the current signature
185 *
186 * \param de_ctx pointer to the Detection Engine Context
187 * \param s pointer to the Current Signature
188 * \param idstr pointer to the user provided "id" option
189 *
190 * \retval 0 on Success
191 * \retval -1 on Failure
192 */
193int DetectIdSetup (DetectEngineCtx *de_ctx, Signature *s, const char *idstr)
194{
195 DetectIdData *id_d = NULL;
196
197 id_d = DetectIdParse(idstr);
198 if (id_d == NULL)
199 return -1;
200
201 /* Okay so far so good, lets get this into a SigMatch
202 * and put it in the Signature. */
204 NULL) {
205 DetectIdFree(de_ctx, id_d);
206 return -1;
207 }
209 return 0;
210}
211
212/**
213 * \brief this function will free memory associated with DetectIdData
214 *
215 * \param id_d pointer to DetectIdData
216 */
218{
219 DetectIdData *id_d = (DetectIdData *)ptr;
220 SCFree(id_d);
221}
222
223/* prefilter code */
224
225static void
226PrefilterPacketIdMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx)
227{
229
230 const PrefilterPacketHeaderCtx *ctx = pectx;
231
232 if (!PacketIsIPv4(p)) {
233 return;
234 }
235
236 if (!PrefilterPacketHeaderExtraMatch(ctx, p))
237 return;
238
239 const IPV4Hdr *ip4h = PacketGetIPv4(p);
240 if (ctx->v1.u16[0] == IPV4_GET_RAW_IPID(ip4h)) {
241 SCLogDebug("packet matches IP id %u", ctx->v1.u16[0]);
242 PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt);
243 }
244}
245
246static void
247PrefilterPacketIdSet(PrefilterPacketHeaderValue *v, void *smctx)
248{
249 const DetectIdData *a = smctx;
250 v->u16[0] = a->id;
251}
252
253static bool
254PrefilterPacketIdCompare(PrefilterPacketHeaderValue v, void *smctx)
255{
256 const DetectIdData *a = smctx;
257 if (v.u16[0] == a->id)
258 return true;
259 return false;
260}
261
262static int PrefilterSetupId(DetectEngineCtx *de_ctx, SigGroupHead *sgh)
263{
265 PrefilterPacketIdSet, PrefilterPacketIdCompare, PrefilterPacketIdMatch);
266}
267
268static bool PrefilterIdIsPrefilterable(const Signature *s)
269{
270 const SigMatch *sm;
271 for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) {
272 switch (sm->type) {
273 case DETECT_ID:
274 return true;
275 }
276 }
277 return false;
278}
279
280#ifdef UNITTESTS /* UNITTESTS */
281
282/**
283 * \test DetectIdTestParse01 is a test to make sure that we parse the "id"
284 * option correctly when given valid id option
285 */
286static int DetectIdTestParse01 (void)
287{
288 DetectIdData *id_d = DetectIdParse(" 35402 ");
289
290 FAIL_IF_NULL(id_d);
291 FAIL_IF_NOT(id_d->id == 35402);
292
293 DetectIdFree(NULL, id_d);
294
295 PASS;
296}
297
298/**
299 * \test DetectIdTestParse02 is a test to make sure that we parse the "id"
300 * option correctly when given an invalid id option
301 * it should return id_d = NULL
302 */
303static int DetectIdTestParse02 (void)
304{
305 DetectIdData *id_d = DetectIdParse("65537");
306
307 FAIL_IF_NOT_NULL(id_d);
308
309 PASS;
310}
311
312/**
313 * \test DetectIdTestParse03 is a test to make sure that we parse the "id"
314 * option correctly when given an invalid id option
315 * it should return id_d = NULL
316 */
317static int DetectIdTestParse03 (void)
318{
319 DetectIdData *id_d = DetectIdParse("12what?");
320
321 FAIL_IF_NOT_NULL(id_d);
322
323 PASS;
324}
325
326/**
327 * \test DetectIdTestParse04 is a test to make sure that we parse the "id"
328 * option correctly when given valid id option but wrapped with "'s
329 */
330static int DetectIdTestParse04 (void)
331{
332 /* yep, look if we trim blank spaces correctly and ignore "'s */
333 DetectIdData *id_d = DetectIdParse(" \"35402\" ");
334
335 FAIL_IF_NULL(id_d);
336 FAIL_IF_NOT(id_d->id == 35402);
337
338 DetectIdFree(NULL, id_d);
339
340 PASS;
341}
342
343/**
344 * \test DetectIdTestSig01
345 * \brief Test to check "id" keyword with constructed packets
346 */
347static int DetectIdTestMatch01(void)
348{
349 uint8_t *buf = (uint8_t *)"Hi all!";
350 uint16_t buflen = strlen((char *)buf);
351 Packet *p[3];
352 p[0] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP);
353 p[1] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_UDP);
354 p[2] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_ICMP);
355
356 FAIL_IF_NULL(p[0]);
357 FAIL_IF_NULL(p[1]);
358 FAIL_IF_NULL(p[2]);
359
360 /* TCP IP id = 1234 */
361 p[0]->l3.hdrs.ip4h->ip_id = htons(1234);
362
363 /* UDP IP id = 5678 */
364 p[1]->l3.hdrs.ip4h->ip_id = htons(5678);
365
366 /* UDP IP id = 91011 */
367 p[2]->l3.hdrs.ip4h->ip_id = htons(5101);
368
369 const char *sigs[3];
370 sigs[0]= "alert ip any any -> any any (msg:\"Testing id 1\"; id:1234; sid:1;)";
371 sigs[1]= "alert ip any any -> any any (msg:\"Testing id 2\"; id:5678; sid:2;)";
372 sigs[2]= "alert ip any any -> any any (msg:\"Testing id 3\"; id:5101; sid:3;)";
373
374 uint32_t sid[3] = {1, 2, 3};
375
376 uint32_t results[3][3] = {
377 /* packet 0 match sid 1 but should not match sid 2 */
378 {1, 0, 0},
379 /* packet 1 should not match */
380 {0, 1, 0},
381 /* packet 2 should not match */
382 {0, 0, 1} };
383
384 FAIL_IF_NOT(UTHGenericTest(p, 3, sigs, sid, (uint32_t *)results, 3));
385
386 UTHFreePackets(p, 3);
387
388 PASS;
389}
390
391/**
392 * \brief this function registers unit tests for DetectId
393 */
394void DetectIdRegisterTests(void)
395{
396 UtRegisterTest("DetectIdTestParse01", DetectIdTestParse01);
397 UtRegisterTest("DetectIdTestParse02", DetectIdTestParse02);
398 UtRegisterTest("DetectIdTestParse03", DetectIdTestParse03);
399 UtRegisterTest("DetectIdTestParse04", DetectIdTestParse04);
400 UtRegisterTest("DetectIdTestMatch01", DetectIdTestMatch01);
401
402}
403#endif /* UNITTESTS */
#define IPV4_GET_RAW_IPID(ip4h)
Definition decode-ipv4.h:99
#define PKT_IS_PSEUDOPKT(p)
return 1 if the packet is a pseudo packet
Definition decode.h:1321
int PrefilterSetupPacketHeader(DetectEngineCtx *de_ctx, SigGroupHead *sgh, int sm_type, SignatureMask mask, void(*Set)(PrefilterPacketHeaderValue *v, void *), bool(*Compare)(PrefilterPacketHeaderValue v, void *), void(*Match)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx))
#define PARSE_REGEX
Regex for parsing "id" option, matching number or "number".
Definition detect-id.c:47
void DetectIdFree(DetectEngineCtx *, void *)
this function will free memory associated with DetectIdData
Definition detect-id.c:217
void DetectIdRegister(void)
Registration function for keyword: id.
Definition detect-id.c:65
#define DETECT_IPID_MAX
Definition detect-id.h:28
#define DETECT_IPID_MIN
Definition detect-id.h:27
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)
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_REQUIRE_PACKET
Definition detect.h:254
#define SIG_MASK_REQUIRE_REAL_PKT
Definition detect.h:316
@ DETECT_SM_LIST_MATCH
Definition detect.h:117
DetectEngineCtx * de_ctx
#define FAIL_IF_NULL(expr)
Fail a test if expression evaluates to NULL.
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.
#define FAIL_IF_NOT_NULL(expr)
Fail a test if expression evaluates to non-NULL.
struct Thresholds ctx
main detection engine ctx
Definition detect.h:932
PrefilterRuleStore pmq
Definition detect.h:1349
uint16_t id
Definition detect-id.h:31
uint16_t ip_id
Definition decode-ipv4.h:76
union PacketL3::Hdrs hdrs
struct PacketL3 l3
Definition decode.h:600
Container for matching data for a signature group.
Definition detect.h:1629
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition detect.h:351
a single match condition for a signature
Definition detect.h:356
uint16_t type
Definition detect.h:357
struct SigMatch_ * next
Definition detect.h:360
const char * url
Definition detect.h:1462
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition detect.h:1441
int(* SetupPrefilter)(DetectEngineCtx *de_ctx, struct SigGroupHead_ *sgh)
Definition detect.h:1444
void(* Free)(DetectEngineCtx *, void *)
Definition detect.h:1446
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
bool(* SupportsPrefilter)(const Signature *s)
Definition detect.h:1443
struct SigMatch_ * smlists[DETECT_SM_LIST_MAX]
Definition detect.h:642
Signature container.
Definition detect.h:668
uint32_t flags
Definition detect.h:669
SignatureInitData * init_data
Definition detect.h:747
IPV4Hdr * ip4h
Definition decode.h:439
int StringParseUint16(uint16_t *res, int base, size_t len, const char *str)
Definition util-byte.c:337
#define SCLogDebug(...)
Definition util-debug.h:275
#define SCLogError(...)
Macro used to log ERROR messages.
Definition util-debug.h:267
#define SCMalloc(sz)
Definition util-mem.h:47
#define SCFree(p)
Definition util-mem.h:61
#define unlikely(expr)
void UTHFreePackets(Packet **p, int numpkts)
UTHFreePackets: function to release the allocated data from UTHBuildPacket and the packet itself.
Packet * UTHBuildPacket(uint8_t *payload, uint16_t payload_len, uint8_t ipproto)
UTHBuildPacket is a wrapper that build packets with default ip and port fields.
int UTHGenericTest(Packet **pkt, int numpkts, const char *sigs[], uint32_t sids[], uint32_t *results, int numsigs)
UTHGenericTest: function that perform a generic check taking care of as maximum common unittest eleme...
#define DEBUG_VALIDATE_BUG_ON(exp)