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