suricata
detect-id.c
Go to the documentation of this file.
1 /* Copyright (C) 2007-2016 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-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 pcre *parse_regex;
50 static pcre_extra *parse_regex_study;
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(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 = DOC_URL DOC_VERSION "/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, &parse_regex_study);
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  #define MAX_SUBSTRINGS 30
125  int ret = 0, res = 0;
126  int ov[MAX_SUBSTRINGS];
127 
128  ret = pcre_exec(parse_regex, parse_regex_study, idstr, strlen(idstr), 0, 0,
129  ov, MAX_SUBSTRINGS);
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  res = pcre_copy_substring((char *)idstr, ov, MAX_SUBSTRINGS, 1,
141  copy_str, sizeof(copy_str));
142  if (res < 0) {
143  SCLogError(SC_ERR_PCRE_GET_SUBSTRING, "pcre_copy_substring 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  temp = atoi((char *)tmp_str);
157 
158  if (temp > DETECT_IPID_MAX) {
159  SCLogError(SC_ERR_INVALID_VALUE, "invalid id option '%s'. The id option "
160  "value must be in the range %u - %u",
162  return NULL;
163  }
164 
165  /* We have a correct id option */
166  id_d = SCMalloc(sizeof(DetectIdData));
167  if (unlikely(id_d == NULL))
168  return NULL;
169 
170  id_d->id = temp;
171 
172  SCLogDebug("detect-id: will look for ip_id: %u\n", id_d->id);
173  return id_d;
174 }
175 
176 /**
177  * \brief this function is used to add the parsed "id" option
178  * \brief into the current signature
179  *
180  * \param de_ctx pointer to the Detection Engine Context
181  * \param s pointer to the Current Signature
182  * \param idstr pointer to the user provided "id" option
183  *
184  * \retval 0 on Success
185  * \retval -1 on Failure
186  */
187 int DetectIdSetup (DetectEngineCtx *de_ctx, Signature *s, const char *idstr)
188 {
189  DetectIdData *id_d = NULL;
190  SigMatch *sm = NULL;
191 
192  id_d = DetectIdParse(idstr);
193  if (id_d == NULL)
194  return -1;
195 
196  /* Okay so far so good, lets get this into a SigMatch
197  * and put it in the Signature. */
198  sm = SigMatchAlloc();
199  if (sm == NULL) {
200  DetectIdFree(id_d);
201  return -1;
202  }
203 
204  sm->type = DETECT_ID;
205  sm->ctx = (SigMatchCtx *)id_d;
206 
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  */
217 void DetectIdFree(void *ptr)
218 {
219  DetectIdData *id_d = (DetectIdData *)ptr;
220  SCFree(id_d);
221 }
222 
223 /* prefilter code */
224 
225 static void
226 PrefilterPacketIdMatch(DetectEngineThreadCtx *det_ctx, Packet *p, const void *pectx)
227 {
228  const PrefilterPacketHeaderCtx *ctx = pectx;
229 
230  if (!PKT_IS_IPV4(p) || PKT_IS_PSEUDOPKT(p)) {
231  return;
232  }
233 
234  if (PrefilterPacketHeaderExtraMatch(ctx, p) == FALSE)
235  return;
236 
237  if (IPV4_GET_IPID(p) == ctx->v1.u16[0])
238  {
239  SCLogDebug("packet matches IP id %u", ctx->v1.u16[0]);
240  PrefilterAddSids(&det_ctx->pmq, ctx->sigs_array, ctx->sigs_cnt);
241  }
242 }
243 
244 static void
245 PrefilterPacketIdSet(PrefilterPacketHeaderValue *v, void *smctx)
246 {
247  const DetectIdData *a = smctx;
248  v->u16[0] = a->id;
249 }
250 
251 static _Bool
252 PrefilterPacketIdCompare(PrefilterPacketHeaderValue v, void *smctx)
253 {
254  const DetectIdData *a = smctx;
255  if (v.u16[0] == a->id)
256  return TRUE;
257  return FALSE;
258 }
259 
260 static int PrefilterSetupId(DetectEngineCtx *de_ctx, SigGroupHead *sgh)
261 {
262  return PrefilterSetupPacketHeader(de_ctx, sgh, DETECT_ID,
263  PrefilterPacketIdSet,
264  PrefilterPacketIdCompare,
265  PrefilterPacketIdMatch);
266 }
267 
268 static _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  */
286 static int DetectIdTestParse01 (void)
287 {
288  DetectIdData *id_d = NULL;
289  id_d = DetectIdParse(" 35402 ");
290  if (id_d != NULL &&id_d->id==35402) {
291  DetectIdFree(id_d);
292  return 1;
293  }
294 
295  return 0;
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  */
303 static int DetectIdTestParse02 (void)
304 {
305  DetectIdData *id_d = NULL;
306  id_d = DetectIdParse("65537");
307  if (id_d == NULL) {
308  DetectIdFree(id_d);
309  return 1;
310  }
311 
312  return 0;
313 }
314 
315 /**
316  * \test DetectIdTestParse03 is a test to make sure that we parse the "id"
317  * option correctly when given an invalid id option
318  * it should return id_d = NULL
319  */
320 static int DetectIdTestParse03 (void)
321 {
322  DetectIdData *id_d = NULL;
323  id_d = DetectIdParse("12what?");
324  if (id_d == NULL) {
325  DetectIdFree(id_d);
326  return 1;
327  }
328 
329  return 0;
330 }
331 
332 /**
333  * \test DetectIdTestParse04 is a test to make sure that we parse the "id"
334  * option correctly when given valid id option but wrapped with "'s
335  */
336 static int DetectIdTestParse04 (void)
337 {
338  DetectIdData *id_d = NULL;
339  /* yep, look if we trim blank spaces correctly and ignore "'s */
340  id_d = DetectIdParse(" \"35402\" ");
341  if (id_d != NULL &&id_d->id==35402) {
342  DetectIdFree(id_d);
343  return 1;
344  }
345 
346  return 0;
347 }
348 
349 /**
350  * \test DetectIdTestSig01
351  * \brief Test to check "id" keyword with constructed packets
352  */
353 static int DetectIdTestMatch01(void)
354 {
355  int result = 0;
356  uint8_t *buf = (uint8_t *)"Hi all!";
357  uint16_t buflen = strlen((char *)buf);
358  Packet *p[3];
359  p[0] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_TCP);
360  p[1] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_UDP);
361  p[2] = UTHBuildPacket((uint8_t *)buf, buflen, IPPROTO_ICMP);
362 
363  if (p[0] == NULL || p[1] == NULL ||p[2] == NULL)
364  goto end;
365 
366  /* TCP IP id = 1234 */
367  p[0]->ip4h->ip_id = htons(1234);
368 
369  /* UDP IP id = 5678 */
370  p[1]->ip4h->ip_id = htons(5678);
371 
372  /* UDP IP id = 91011 */
373  p[2]->ip4h->ip_id = htons(5101);
374 
375  const char *sigs[3];
376  sigs[0]= "alert ip any any -> any any (msg:\"Testing id 1\"; id:1234; sid:1;)";
377  sigs[1]= "alert ip any any -> any any (msg:\"Testing id 2\"; id:5678; sid:2;)";
378  sigs[2]= "alert ip any any -> any any (msg:\"Testing id 3\"; id:5101; sid:3;)";
379 
380  uint32_t sid[3] = {1, 2, 3};
381 
382  uint32_t results[3][3] = {
383  /* packet 0 match sid 1 but should not match sid 2 */
384  {1, 0, 0},
385  /* packet 1 should not match */
386  {0, 1, 0},
387  /* packet 2 should not match */
388  {0, 0, 1} };
389 
390  result = UTHGenericTest(p, 3, sigs, sid, (uint32_t *) results, 3);
391 
392  UTHFreePackets(p, 3);
393 end:
394  return result;
395 }
396 #endif /* UNITTESTS */
397 
398 /**
399  * \brief this function registers unit tests for DetectId
400  */
402 {
403 #ifdef UNITTESTS /* UNITTESTS */
404  UtRegisterTest("DetectIdTestParse01", DetectIdTestParse01);
405  UtRegisterTest("DetectIdTestParse02", DetectIdTestParse02);
406  UtRegisterTest("DetectIdTestParse03", DetectIdTestParse03);
407  UtRegisterTest("DetectIdTestParse04", DetectIdTestParse04);
408  UtRegisterTest("DetectIdTestMatch01", DetectIdTestMatch01);
409 
410 #endif /* UNITTESTS */
411 }
SigTableElmt sigmatch_table[DETECT_TBLSIZE]
Definition: detect.h:1448
SignatureInitData * init_data
Definition: detect.h:591
int(* Setup)(DetectEngineCtx *, Signature *, const char *)
Definition: detect.h:1186
#define SCLogDebug(...)
Definition: util-debug.h:335
int(* SetupPrefilter)(DetectEngineCtx *de_ctx, struct SigGroupHead_ *sgh)
Definition: detect.h:1189
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))
uint32_t flags
Definition: detect.h:523
_Bool(* SupportsPrefilter)(const Signature *s)
Definition: detect.h:1188
#define FALSE
#define unlikely(expr)
Definition: util-optimize.h:35
Container for matching data for a signature group.
Definition: detect.h:1336
uint16_t ip_id
Definition: decode-ipv4.h:75
#define SIG_FLAG_REQUIRE_PACKET
Definition: detect.h:223
const char * name
Definition: detect.h:1200
Signature container.
Definition: detect.h:522
#define TRUE
Used to start a pointer to SigMatch context Should never be dereferenced without casting to something...
Definition: detect.h:313
#define PKT_IS_IPV4(p)
Definition: decode.h:252
struct SigMatch_ * next
Definition: detect.h:322
main detection engine ctx
Definition: detect.h:761
void DetectIdRegisterTests(void)
this function registers unit tests for DetectId
Definition: detect-id.c:401
void(* Free)(void *)
Definition: detect.h:1191
#define SCLogError(err_code,...)
Macro used to log ERROR messages.
Definition: util-debug.h:294
void UtRegisterTest(const char *name, int(*TestFn)(void))
Register unit test.
void DetectSetupParseRegexes(const char *parse_str, pcre **parse_regex, pcre_extra **parse_regex_study)
PrefilterRuleStore pmq
Definition: detect.h:1102
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.
#define MAX_SUBSTRINGS
int(* Match)(DetectEngineThreadCtx *, Packet *, const Signature *, const SigMatchCtx *)
Definition: detect.h:1170
uint8_t type
Definition: detect.h:319
const char * desc
Definition: detect.h:1202
void SigMatchAppendSMToList(Signature *s, SigMatch *new, int list)
Append a SigMatch to the list type.
Definition: detect-parse.c:346
struct SigMatch_ ** smlists
Definition: detect.h:516
IPV4Hdr * ip4h
Definition: decode.h:501
SigMatchCtx * ctx
Definition: detect.h:321
#define SCMalloc(a)
Definition: util-mem.h:222
uint16_t id
Definition: detect-id.h:32
#define SCFree(a)
Definition: util-mem.h:322
PoolThreadReserved res
#define PARSE_REGEX
Regex for parsing "id" option, matching number or "number".
Definition: detect-id.c:47
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...
const char * url
Definition: detect.h:1203
#define DOC_URL
Definition: suricata.h:86
#define PKT_IS_PSEUDOPKT(p)
return 1 if the packet is a pseudo packet
Definition: decode.h:1133
SigMatch * SigMatchAlloc(void)
Definition: detect-parse.c:232
#define DETECT_IPID_MIN
Definition: detect-id.h:28
#define DOC_VERSION
Definition: suricata.h:91
void UTHFreePackets(Packet **p, int numpkts)
UTHFreePackets: function to release the allocated data from UTHBuildPacket and the packet itself...
#define IPV4_GET_IPID(p)
Definition: decode-ipv4.h:129
void(* RegisterTests)(void)
Definition: detect.h:1192
a single match condition for a signature
Definition: detect.h:318
void DetectIdFree(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:64
#define DETECT_IPID_MAX
Definition: detect-id.h:29