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"
42 #include "util-unittest-helper.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 
49 static DetectParseRegex parse_regex;
50 
51 static int DetectIdMatch (DetectEngineThreadCtx *, Packet *,
52  const Signature *, const SigMatchCtx *);
53 static int DetectIdSetup (DetectEngineCtx *, Signature *, const char *);
54 #ifdef UNITTESTS
55 static void DetectIdRegisterTests(void);
56 #endif
57 void DetectIdFree(DetectEngineCtx *, void *);
58 
59 static int PrefilterSetupId(DetectEngineCtx *de_ctx, SigGroupHead *sgh);
60 static bool PrefilterIdIsPrefilterable(const Signature *s);
61 
62 /**
63  * \brief Registration function for keyword: id
64  */
65 void DetectIdRegister (void)
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 
79  DetectSetupParseRegexes(PARSE_REGEX, &parse_regex);
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  */
93 static int DetectIdMatch (DetectEngineThreadCtx *det_ctx, Packet *p,
94  const Signature *s, const SigMatchCtx *ctx)
95 {
96  const DetectIdData *id_d = (const DetectIdData *)ctx;
97 
98  /**
99  * To match a ipv4 packet with a "id" rule
100  */
101  if (!PKT_IS_IPV4(p) || PKT_IS_PSEUDOPKT(p)) {
102  return 0;
103  }
104 
105  if (id_d->id == IPV4_GET_IPID(p)) {
106  SCLogDebug("IPV4 Proto and matched with ip_id: %u.\n",
107  id_d->id);
108  return 1;
109  }
110 
111  return 0;
112 }
113 
114 /**
115  * \brief This function is used to parse IPV4 ip_id passed via keyword: "id"
116  *
117  * \param idstr Pointer to the user provided id option
118  *
119  * \retval id_d pointer to DetectIdData on success
120  * \retval NULL on failure
121  */
122 static DetectIdData *DetectIdParse (const char *idstr)
123 {
124  uint16_t temp;
125  DetectIdData *id_d = NULL;
126  int ret = 0, res = 0;
127  size_t pcre2len;
128 
129  ret = DetectParsePcreExec(&parse_regex, idstr, 0, 0);
130 
131  if (ret < 1 || ret > 3) {
132  SCLogError(SC_ERR_INVALID_VALUE, "invalid id option '%s'. The id option "
133  "value must be in the range %u - %u",
135  return NULL;
136  }
137 
138  char copy_str[128] = "";
139  char *tmp_str;
140  pcre2len = sizeof(copy_str);
141  res = pcre2_substring_copy_bynumber(parse_regex.match, 1, (PCRE2_UCHAR8 *)copy_str, &pcre2len);
142  if (res < 0) {
143  SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre2_substring_copy_bynumber failed");
144  return NULL;
145  }
146  tmp_str = copy_str;
147 
148  /* Let's see if we need to scape "'s */
149  if (tmp_str[0] == '"')
150  {
151  tmp_str[strlen(tmp_str) - 1] = '\0';
152  tmp_str += 1;
153  }
154 
155  /* ok, fill the id data */
156  if (StringParseUint16(&temp, 10, 0, (const char *)tmp_str) < 0) {
157  SCLogError(SC_ERR_INVALID_VALUE, "invalid id option '%s'", tmp_str);
158  return NULL;
159  }
160 
161  /* We have a correct id option */
162  id_d = SCMalloc(sizeof(DetectIdData));
163  if (unlikely(id_d == NULL))
164  return NULL;
165 
166  id_d->id = temp;
167 
168  SCLogDebug("detect-id: will look for ip_id: %u\n", id_d->id);
169  return id_d;
170 }
171 
172 /**
173  * \brief this function is used to add the parsed "id" option
174  * \brief into the current signature
175  *
176  * \param de_ctx pointer to the Detection Engine Context
177  * \param s pointer to the Current Signature
178  * \param idstr pointer to the user provided "id" option
179  *
180  * \retval 0 on Success
181  * \retval -1 on Failure
182  */
183 int DetectIdSetup (DetectEngineCtx *de_ctx, Signature *s, const char *idstr)
184 {
185  DetectIdData *id_d = NULL;
186  SigMatch *sm = NULL;
187 
188  id_d = DetectIdParse(idstr);
189  if (id_d == NULL)
190  return -1;
191 
192  /* Okay so far so good, lets get this into a SigMatch
193  * and put it in the Signature. */
194  sm = SigMatchAlloc();
195  if (sm == NULL) {
196  DetectIdFree(de_ctx, id_d);
197  return -1;
198  }
199 
200  sm->type = DETECT_ID;
201  sm->ctx = (SigMatchCtx *)id_d;
202 
205  return 0;
206 }
207 
208 /**
209  * \brief this function will free memory associated with DetectIdData
210  *
211  * \param id_d pointer to DetectIdData
212  */
214 {
215  DetectIdData *id_d = (DetectIdData *)ptr;
216  SCFree(id_d);
217 }
218 
219 /* prefilter code */
220 
221 static void
222 PrefilterPacketIdMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx)
223 {
224  const PrefilterPacketHeaderCtx *ctx = pectx;
225 
226  if (!PKT_IS_IPV4(p) || PKT_IS_PSEUDOPKT(p)) {
227  return;
228  }
229 
230  if (!PrefilterPacketHeaderExtraMatch(ctx, p))
231  return;
232 
233  if (IPV4_GET_IPID(p) == ctx->v1.u16[0])
234  {
235  SCLogDebug("packet matches IP id %u", ctx->v1.u16[0]);
236  PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt);
237  }
238 }
239 
240 static void
241 PrefilterPacketIdSet(PrefilterPacketHeaderValue *v, void *smctx)
242 {
243  const DetectIdData *a = smctx;
244  v->u16[0] = a->id;
245 }
246 
247 static bool
248 PrefilterPacketIdCompare(PrefilterPacketHeaderValue v, void *smctx)
249 {
250  const DetectIdData *a = smctx;
251  if (v.u16[0] == a->id)
252  return true;
253  return false;
254 }
255 
256 static int PrefilterSetupId(DetectEngineCtx *de_ctx, SigGroupHead *sgh)
257 {
259  PrefilterPacketIdSet,
260  PrefilterPacketIdCompare,
261  PrefilterPacketIdMatch);
262 }
263 
264 static bool PrefilterIdIsPrefilterable(const Signature *s)
265 {
266  const SigMatch *sm;
267  for (sm = s->init_data->smlists[DETECT_SM_LIST_MATCH] ; sm != NULL; sm = sm->next) {
268  switch (sm->type) {
269  case DETECT_ID:
270  return true;
271  }
272  }
273  return false;
274 }
275 
276 #ifdef UNITTESTS /* UNITTESTS */
277 
278 /**
279  * \test DetectIdTestParse01 is a test to make sure that we parse the "id"
280  * option correctly when given valid id option
281  */
282 static int DetectIdTestParse01 (void)
283 {
284  DetectIdData *id_d = DetectIdParse(" 35402 ");
285 
286  FAIL_IF_NULL(id_d);
287  FAIL_IF_NOT(id_d->id == 35402);
288 
289  DetectIdFree(NULL, id_d);
290 
291  PASS;
292 }
293 
294 /**
295  * \test DetectIdTestParse02 is a test to make sure that we parse the "id"
296  * option correctly when given an invalid id option
297  * it should return id_d = NULL
298  */
299 static int DetectIdTestParse02 (void)
300 {
301  DetectIdData *id_d = DetectIdParse("65537");
302 
303  FAIL_IF_NOT_NULL(id_d);
304 
305  PASS;
306 }
307 
308 /**
309  * \test DetectIdTestParse03 is a test to make sure that we parse the "id"
310  * option correctly when given an invalid id option
311  * it should return id_d = NULL
312  */
313 static int DetectIdTestParse03 (void)
314 {
315  DetectIdData *id_d = DetectIdParse("12what?");
316 
317  FAIL_IF_NOT_NULL(id_d);
318 
319  PASS;
320 }
321 
322 /**
323  * \test DetectIdTestParse04 is a test to make sure that we parse the "id"
324  * option correctly when given valid id option but wrapped with "'s
325  */
326 static int DetectIdTestParse04 (void)
327 {
328  /* yep, look if we trim blank spaces correctly and ignore "'s */
329  DetectIdData *id_d = DetectIdParse(" \"35402\" ");
330 
331  FAIL_IF_NULL(id_d);
332  FAIL_IF_NOT(id_d->id == 35402);
333 
334  DetectIdFree(NULL, id_d);
335 
336  PASS;
337 }
338 
339 /**
340  * \test DetectIdTestSig01
341  * \brief Test to check "id" keyword with constructed packets
342  */
343 static int DetectIdTestMatch01(void)
344 {
345  uint8_t *buf = (uint8_t *)"Hi all!";
346  uint16_t buflen = strlen((char *)buf);
347  Packet *p[3];
348  p[0] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP);
349  p[1] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_UDP);
350  p[2] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_ICMP);
351 
352  FAIL_IF_NULL(p[0]);
353  FAIL_IF_NULL(p[1]);
354  FAIL_IF_NULL(p[2]);
355 
356  /* TCP IP id = 1234 */
357  p[0]->ip4h->ip_id = htons(1234);
358 
359  /* UDP IP id = 5678 */
360  p[1]->ip4h->ip_id = htons(5678);
361 
362  /* UDP IP id = 91011 */
363  p[2]->ip4h->ip_id = htons(5101);
364 
365  const char *sigs[3];
366  sigs[0]= "alert ip any any -> any any (msg:\"Testing id 1\"; id:1234; sid:1;)";
367  sigs[1]= "alert ip any any -> any any (msg:\"Testing id 2\"; id:5678; sid:2;)";
368  sigs[2]= "alert ip any any -> any any (msg:\"Testing id 3\"; id:5101; sid:3;)";
369 
370  uint32_t sid[3] = {1, 2, 3};
371 
372  uint32_t results[3][3] = {
373  /* packet 0 match sid 1 but should not match sid 2 */
374  {1, 0, 0},
375  /* packet 1 should not match */
376  {0, 1, 0},
377  /* packet 2 should not match */
378  {0, 0, 1} };
379 
380  FAIL_IF_NOT(UTHGenericTest(p, 3, sigs, sid, (uint32_t *)results, 3));
381 
382  UTHFreePackets(p, 3);
383 
384  PASS;
385 }
386 
387 /**
388  * \brief this function registers unit tests for DetectId
389  */
390 void DetectIdRegisterTests(void)
391 {
392  UtRegisterTest("DetectIdTestParse01", DetectIdTestParse01);
393  UtRegisterTest("DetectIdTestParse02", DetectIdTestParse02);
394  UtRegisterTest("DetectIdTestParse03", DetectIdTestParse03);
395  UtRegisterTest("DetectIdTestParse04", DetectIdTestParse04);
396  UtRegisterTest("DetectIdTestMatch01", DetectIdTestMatch01);
397 
398 }
399 #endif /* UNITTESTS */
util-byte.h
DetectParseRegex::match
pcre2_match_data * match
Definition: detect-parse.h:45
SigTableElmt_::url
const char * url
Definition: detect.h:1248
detect-engine.h
FAIL_IF_NULL
#define FAIL_IF_NULL(expr)
Fail a test if expression evaluates to NULL.
Definition: util-unittest.h:89
SigTableElmt_::desc
const char * desc
Definition: detect.h:1247
DetectParsePcreExec
int DetectParsePcreExec(DetectParseRegex *parse_regex, const char *str, int start_offset, int options)
Definition: detect-parse.c:2475
SC_ERR_INVALID_VALUE
@ SC_ERR_INVALID_VALUE
Definition: util-error.h:160
SigTableElmt_::Free
void(* Free)(DetectEngineCtx *, void *)
Definition: detect.h:1235
DetectParseRegex
Definition: detect-parse.h:42
SigTableElmt_::name
const char * name
Definition: detect.h:1245
PKT_IS_PSEUDOPKT
#define PKT_IS_PSEUDOPKT(p)
return 1 if the packet is a pseudo packet
Definition: decode.h:1222
SigGroupHead_
Container for matching data for a signature group.
Definition: detect.h:1403
unlikely
#define unlikely(expr)
Definition: util-optimize.h:35
UtRegisterTest
void UtRegisterTest(const char *name, int(*TestFn)(void))
Register unit test.
Definition: util-unittest.c:103
SCLogDebug
#define SCLogDebug(...)
Definition: util-debug.h:296
DETECT_ID
@ DETECT_ID
Definition: detect-engine-register.h:81
results
struct DetectRfbSecresult_ results[]
DetectEngineThreadCtx_::pmq
PrefilterRuleStore pmq
Definition: detect.h:1141
DetectEngineCtx_
main detection engine ctx
Definition: detect.h:785
DetectIdData_::id
uint16_t id
Definition: detect-id.h:32
StringParseUint16
int StringParseUint16(uint16_t *res, int base, size_t len, const char *str)
Definition: util-byte.c:336
PrefilterPacketHeaderCtx_::sigs_array
SigIntId * sigs_array
Definition: detect-engine-prefilter-common.h:43
PARSE_REGEX
#define PARSE_REGEX
Regex for parsing "id" option, matching number or "number".
Definition: detect-id.c:47
IPV4Hdr_::ip_id
uint16_t ip_id
Definition: decode-ipv4.h:75
UTHBuildPacket
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.
Definition: util-unittest-helper.c:338
PrefilterPacketHeaderCtx_::sigs_cnt
uint32_t sigs_cnt
Definition: detect-engine-prefilter-common.h:42
SC_ERR_PCRE_GET_SUBSTRING
@ SC_ERR_PCRE_GET_SUBSTRING
Definition: util-error.h:34
SigTableElmt_::Setup
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition: detect.h:1230
PrefilterPacketHeaderValue::u16
uint16_t u16[8]
Definition: detect-engine-prefilter-common.h:25
util-unittest.h
util-unittest-helper.h
FAIL_IF_NOT
#define FAIL_IF_NOT(expr)
Fail a test if expression evaluates to false.
Definition: util-unittest.h:82
SigTableElmt_::SetupPrefilter
int(* SetupPrefilter)(DetectEngineCtx *de_ctx, struct SigGroupHead_ *sgh)
Definition: detect.h:1233
PrefilterPacketHeaderCtx_
Definition: detect-engine-prefilter-common.h:35
decode.h
FAIL_IF_NOT_NULL
#define FAIL_IF_NOT_NULL(expr)
Fail a test if expression evaluates to non-NULL.
Definition: util-unittest.h:96
util-debug.h
PASS
#define PASS
Pass the test.
Definition: util-unittest.h:105
de_ctx
DetectEngineCtx * de_ctx
Definition: fuzz_siginit.c:17
DetectEngineThreadCtx_
Definition: detect.h:1034
res
PoolThreadReserved res
Definition: stream-tcp-private.h:0
DetectSetupParseRegexes
void DetectSetupParseRegexes(const char *parse_str, DetectParseRegex *detect_parse)
Definition: detect-parse.c:2598
detect-engine-mpm.h
detect.h
SigMatch_::next
struct SigMatch_ * next
Definition: detect.h:318
DetectIdRegister
void DetectIdRegister(void)
Registration function for keyword: id.
Definition: detect-id.c:65
DETECT_SM_LIST_MATCH
@ DETECT_SM_LIST_MATCH
Definition: detect.h:80
IPV4_GET_IPID
#define IPV4_GET_IPID(p)
Definition: decode-ipv4.h:128
SigMatch_::ctx
SigMatchCtx * ctx
Definition: detect.h:317
Signature_::flags
uint32_t flags
Definition: detect.h:541
Packet_
Definition: decode.h:434
detect-id.h
Packet_::ip4h
IPV4Hdr * ip4h
Definition: decode.h:532
Signature_::init_data
SignatureInitData * init_data
Definition: detect.h:611
SigTableElmt_::Match
int(* Match)(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *)
Definition: detect.h:1213
SignatureInitData_::smlists
struct SigMatch_ ** smlists
Definition: detect.h:534
SigMatchAlloc
SigMatch * SigMatchAlloc(void)
Definition: detect-parse.c:235
PrefilterPacketHeaderCtx_::v1
PrefilterPacketHeaderValue v1
Definition: detect-engine-prefilter-common.h:36
SigMatchCtx_
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition: detect.h:309
DetectIdData_
Definition: detect-id.h:31
suricata-common.h
SigMatch_::type
uint16_t type
Definition: detect.h:315
sigmatch_table
SigTableElmt sigmatch_table[DETECT_TBLSIZE]
Definition: detect-parse.c:73
SCLogError
#define SCLogError(err_code,...)
Macro used to log ERROR messages.
Definition: util-debug.h:255
UTHGenericTest
int UTHGenericTest(Packet **pkt, int numpkts, const char *sigs[], uint32_t sids[], uint32_t *results, int numsigs)
UTHGenericTest: function that perfom a generic check taking care of as maximum common unittest elemen...
Definition: util-unittest-helper.c:605
PrefilterSetupPacketHeader
int PrefilterSetupPacketHeader(DetectEngineCtx *de_ctx, SigGroupHead *sgh, int sm_type, void(*Set)(PrefilterPacketHeaderValue *v, void *), bool(*Compare)(PrefilterPacketHeaderValue v, void *), void(*Match)(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx))
Definition: detect-engine-prefilter-common.c:417
SCMalloc
#define SCMalloc(sz)
Definition: util-mem.h:47
DETECT_IPID_MAX
#define DETECT_IPID_MAX
Definition: detect-id.h:29
SCFree
#define SCFree(p)
Definition: util-mem.h:61
SigTableElmt_::SupportsPrefilter
bool(* SupportsPrefilter)(const Signature *s)
Definition: detect.h:1232
detect-parse.h
Signature_
Signature container.
Definition: detect.h:540
SigMatch_
a single match condition for a signature
Definition: detect.h:314
DETECT_IPID_MIN
#define DETECT_IPID_MIN
Definition: detect-id.h:28
DetectIdFree
void DetectIdFree(DetectEngineCtx *, void *)
this function will free memory associated with DetectIdData
Definition: detect-id.c:213
PrefilterPacketHeaderValue
Definition: detect-engine-prefilter-common.h:23
detect-engine-prefilter-common.h
flow.h
flow-var.h
PKT_IS_IPV4
#define PKT_IS_IPV4(p)
Definition: decode.h:253
SigMatchAppendSMToList
void SigMatchAppendSMToList(Signature *s, SigMatch *new, int list)
Append a SigMatch to the list type.
Definition: detect-parse.c:349
SigTableElmt_::RegisterTests
void(* RegisterTests)(void)
Definition: detect.h:1237
SIG_FLAG_REQUIRE_PACKET
#define SIG_FLAG_REQUIRE_PACKET
Definition: detect.h:217
UTHFreePackets
void UTHFreePackets(Packet **p, int numpkts)
UTHFreePackets: function to release the allocated data from UTHBuildPacket and the packet itself.
Definition: util-unittest-helper.c:469