• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

jasonish / suricata / 22598483541

01 Mar 2026 06:45AM UTC coverage: 73.677% (+30.4%) from 43.31%
22598483541

push

github

victorjulien
detect/transforms: update gunzip / zlib_deflate syntax

Use standard space separated syntax.

38322 of 77530 branches covered (49.43%)

Branch coverage included in aggregate %.

6 of 6 new or added lines in 1 file covered. (100.0%)

501 existing lines in 30 files now uncovered.

265690 of 335097 relevant lines covered (79.29%)

4921680.05 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

70.5
/src/detect-engine.c
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
 */
23

24
#include "suricata-common.h"
25
#include "suricata.h"
26
#include "detect.h"
27
#include "flow.h"
28
#include "flow-private.h"
29
#include "flow-util.h"
30
#include "flow-worker.h"
31
#include "conf.h"
32
#include "conf-yaml-loader.h"
33
#include "datasets.h"
34

35
#include "app-layer-parser.h"
36
#include "app-layer-events.h"
37
#include "app-layer-htp.h"
38

39
#include "detect-parse.h"
40
#include "detect-engine-sigorder.h"
41

42
#include "detect-engine-build.h"
43
#include "detect-engine-siggroup.h"
44
#include "detect-engine-address.h"
45
#include "detect-engine-port.h"
46
#include "detect-engine-prefilter.h"
47
#include "detect-engine-mpm.h"
48
#include "detect-engine-iponly.h"
49
#include "detect-engine-tag.h"
50
#include "detect-engine-frame.h"
51

52
#include "detect-engine-file.h"
53

54
#include "detect-engine.h"
55
#include "detect-engine-state.h"
56
#include "detect-engine-payload.h"
57
#include "detect-fast-pattern.h"
58
#include "detect-byte-extract.h"
59
#include "detect-content.h"
60
#include "detect-uricontent.h"
61
#include "detect-tcphdr.h"
62
#include "detect-engine-threshold.h"
63
#include "detect-engine-content-inspection.h"
64

65
#include "detect-engine-loader.h"
66

67
#include "detect-engine-alert.h"
68

69
#include "util-classification-config.h"
70
#include "util-reference-config.h"
71
#include "util-threshold-config.h"
72
#include "util-error.h"
73
#include "util-hash.h"
74
#include "util-byte.h"
75
#include "util-debug.h"
76
#include "util-unittest.h"
77
#include "util-action.h"
78
#include "util-magic.h"
79
#include "util-signal.h"
80
#include "util-spm.h"
81
#include "util-device-private.h"
82
#include "util-var-name.h"
83
#include "util-path.h"
84
#include "util-profiling.h"
85
#include "util-validate.h"
86
#include "util-hash-string.h"
87
#include "util-enum.h"
88
#include "util-conf.h"
89

90
#include "tm-threads.h"
91
#include "runmodes.h"
92

93
#include "reputation.h"
94

95
#define DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT 3000
38,898✔
96

97
static int DetectEngineCtxLoadConf(DetectEngineCtx *);
98

99
static DetectEngineMasterCtx g_master_de_ctx = { SCMUTEX_INITIALIZER,
100
    0, 99, NULL, NULL, TENANT_SELECTOR_UNKNOWN, NULL, NULL, 0};
101

102
static uint32_t TenantIdHash(HashTable *h, void *data, uint16_t data_len);
103
static char TenantIdCompare(void *d1, uint16_t d1_len, void *d2, uint16_t d2_len);
104
static void TenantIdFree(void *d);
105
static uint32_t DetectEngineTenantGetIdFromLivedev(const void *ctx, const Packet *p);
106
static uint32_t DetectEngineTenantGetIdFromVlanId(const void *ctx, const Packet *p);
107
static uint32_t DetectEngineTenantGetIdFromPcap(const void *ctx, const Packet *p);
108

109
static bool DetectEngineMultiTenantEnabledWithLock(void);
110
static DetectEngineAppInspectionEngine *g_app_inspect_engines = NULL;
111
static DetectEnginePktInspectionEngine *g_pkt_inspect_engines = NULL;
112
static DetectEngineFrameInspectionEngine *g_frame_inspect_engines = NULL;
113

114
// clang-format off
115
// rule types documentation tag start: SignatureProperties
116
const struct SignatureProperties signature_properties[SIG_TYPE_MAX] = {
117
    /* SIG_TYPE_NOT_SET */      { SIG_PROP_FLOW_ACTION_PACKET, },
118
    /* SIG_TYPE_IPONLY */       { SIG_PROP_FLOW_ACTION_FLOW, },
119
    /* SIG_TYPE_LIKE_IPONLY */  { SIG_PROP_FLOW_ACTION_FLOW, },
120
    /* SIG_TYPE_PDONLY */       { SIG_PROP_FLOW_ACTION_FLOW, },
121
    /* SIG_TYPE_DEONLY */       { SIG_PROP_FLOW_ACTION_PACKET, },
122
    /* SIG_TYPE_PKT */          { SIG_PROP_FLOW_ACTION_PACKET, },
123
    /* SIG_TYPE_PKT_STREAM */   { SIG_PROP_FLOW_ACTION_FLOW_IF_STATEFUL, },
124
    /* SIG_TYPE_STREAM */       { SIG_PROP_FLOW_ACTION_FLOW_IF_STATEFUL, },
125
    /* SIG_TYPE_APPLAYER */     { SIG_PROP_FLOW_ACTION_FLOW, },
126
    /* SIG_TYPE_APP_TX */       { SIG_PROP_FLOW_ACTION_FLOW, },
127
};
128
// rule types documentation tag end: SignatureProperties
129
// clang-format on
130

131
const char *DetectTableToString(enum DetectTable table)
132
{
×
133
    switch (table) {
×
134
        case DETECT_TABLE_NOT_SET:
×
135
            return "not_set";
×
136
        case DETECT_TABLE_PACKET_PRE_FLOW:
×
137
            return "pre_flow";
×
138
        case DETECT_TABLE_PACKET_PRE_STREAM:
×
139
            return "pre_stream";
×
140
        case DETECT_TABLE_PACKET_FILTER:
×
141
            return "packet_filter";
×
142
        case DETECT_TABLE_PACKET_TD:
×
143
            return "packet_td";
×
144
        case DETECT_TABLE_APP_FILTER:
×
145
            return "app_filter";
×
146
        case DETECT_TABLE_APP_TD:
×
147
            return "app_td";
×
148
        default:
×
149
            return "unknown";
×
150
    }
×
151
}
×
152

153
/** \brief register inspect engine at start up time
154
 *
155
 *  \note errors are fatal */
156
void DetectPktInspectEngineRegister(const char *name,
157
        InspectionBufferGetPktDataPtr GetPktData,
158
        InspectionBufferPktInspectFunc Callback)
159
{
19,737✔
160
    DetectBufferTypeRegister(name);
19,737✔
161
    const int sm_list = DetectBufferTypeGetByName(name);
19,737✔
162
    if (sm_list == -1) {
19,737!
163
        FatalError("failed to register inspect engine %s", name);
×
164
    }
×
165

166
    if ((sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) ||
19,737!
167
        (Callback == NULL))
19,737!
168
    {
×
169
        SCLogError("Invalid arguments");
×
170
        BUG_ON(1);
×
171
    }
×
172

173
    DetectEnginePktInspectionEngine *new_engine = SCCalloc(1, sizeof(*new_engine));
19,737✔
174
    if (unlikely(new_engine == NULL)) {
19,737!
175
        FatalError("failed to register inspect engine %s: %s", name, strerror(errno));
×
176
    }
×
177
    new_engine->sm_list = (uint16_t)sm_list;
19,737✔
178
    new_engine->sm_list_base = (uint16_t)sm_list;
19,737✔
179
    new_engine->v1.Callback = Callback;
19,737✔
180
    new_engine->v1.GetData = GetPktData;
19,737✔
181

182
    if (g_pkt_inspect_engines == NULL) {
19,737✔
183
        g_pkt_inspect_engines = new_engine;
2,193✔
184
    } else {
17,544✔
185
        DetectEnginePktInspectionEngine *t = g_pkt_inspect_engines;
17,544✔
186
        while (t->next != NULL) {
78,948✔
187
            t = t->next;
61,404✔
188
        }
61,404✔
189

190
        t->next = new_engine;
17,544✔
191
    }
17,544✔
192
}
19,737✔
193

194
/** \brief register inspect engine at start up time
195
 *
196
 *  \note errors are fatal */
197
static void AppLayerInspectEngineRegisterInternal(const char *name, AppProto alproto, uint32_t dir,
198
        int progress, InspectEngineFuncPtr Callback, InspectionBufferGetDataPtr GetData,
199
        InspectionSingleBufferGetDataPtr GetDataSingle,
200
        InspectionMultiBufferGetDataPtr GetMultiData)
201
{
1,504,358✔
202
    BUG_ON(progress >= 48);
1,504,358!
203

204
    DetectBufferTypeRegister(name);
1,504,358✔
205
    const int sm_list = DetectBufferTypeGetByName(name);
1,504,358✔
206
    if (sm_list == -1) {
1,504,358!
207
        FatalError("failed to register inspect engine %s", name);
×
208
    }
×
209
    SCLogDebug("name %s id %d", name, sm_list);
1,504,358!
210

211
    if ((alproto == ALPROTO_FAILED) || (!(dir == SIG_FLAG_TOSERVER || dir == SIG_FLAG_TOCLIENT)) ||
1,504,358!
212
            (sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) ||
1,504,358!
213
            (progress < 0 || progress >= SHRT_MAX) || (Callback == NULL)) {
1,504,358!
214
        SCLogError("Invalid arguments");
×
215
        BUG_ON(1);
×
216
    } else if (Callback == DetectEngineInspectBufferGeneric && GetData == NULL) {
1,504,358!
217
        SCLogError("Invalid arguments: must register "
×
218
                   "GetData with DetectEngineInspectBufferGeneric");
×
219
        BUG_ON(1);
×
220
    } else if (Callback == DetectEngineInspectBufferSingle && GetDataSingle == NULL) {
1,504,358!
221
        SCLogError("Invalid arguments: must register "
×
222
                   "GetData with DetectEngineInspectBufferGeneric");
×
223
        BUG_ON(1);
×
224
    } else if (Callback == DetectEngineInspectMultiBufferGeneric && GetMultiData == NULL) {
1,504,358!
225
        SCLogError("Invalid arguments: must register "
×
226
                   "GetData with DetectEngineInspectMultiBufferGeneric");
×
227
        BUG_ON(1);
×
228
    }
×
229

230
    uint8_t direction;
1,504,358✔
231
    if (dir == SIG_FLAG_TOSERVER) {
1,504,358✔
232
        direction = 0;
811,374✔
233
    } else {
811,374✔
234
        direction = 1;
692,984✔
235
    }
692,984✔
236
    // every DNS or HTTP2 can be accessed from DOH2
237
    if (alproto == ALPROTO_HTTP2 || alproto == ALPROTO_DNS) {
1,504,358✔
238
        AppLayerInspectEngineRegisterInternal(
168,861✔
239
                name, ALPROTO_DOH2, dir, progress, Callback, GetData, GetDataSingle, GetMultiData);
168,861✔
240
    }
168,861✔
241

242
    DetectEngineAppInspectionEngine *new_engine =
1,504,358✔
243
            SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
1,504,358✔
244
    if (unlikely(new_engine == NULL)) {
1,504,358!
245
        exit(EXIT_FAILURE);
×
246
    }
×
247
    new_engine->alproto = alproto;
1,504,358✔
248
    new_engine->dir = direction;
1,504,358✔
249
    new_engine->sm_list = (uint16_t)sm_list;
1,504,358✔
250
    new_engine->sm_list_base = (uint16_t)sm_list;
1,504,358✔
251
    new_engine->progress = (int16_t)progress;
1,504,358✔
252
    new_engine->v2.Callback = Callback;
1,504,358✔
253
    if (Callback == DetectEngineInspectBufferGeneric) {
1,504,358✔
254
        new_engine->v2.GetData = GetData;
289,476✔
255
    } else if (Callback == DetectEngineInspectBufferSingle) {
1,214,882✔
256
        new_engine->v2.GetDataSingle = GetDataSingle;
175,408✔
257
    } else if (Callback == DetectEngineInspectMultiBufferGeneric) {
1,039,474✔
258
        new_engine->v2.GetMultiData = GetMultiData;
203,949✔
259
    }
203,949✔
260

261
    if (g_app_inspect_engines == NULL) {
1,504,358✔
262
        g_app_inspect_engines = new_engine;
2,193✔
263
    } else {
1,502,165✔
264
        DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
1,502,165✔
265
        while (t->next != NULL) {
515,228,987✔
266
            t = t->next;
513,726,822✔
267
        }
513,726,822✔
268

269
        t->next = new_engine;
1,502,165✔
270
    }
1,502,165✔
271
}
1,504,358✔
272

273
void DetectAppLayerInspectEngineRegister(const char *name, AppProto alproto, uint32_t dir,
274
        int progress, InspectEngineFuncPtr Callback, InspectionBufferGetDataPtr GetData)
275
{
993,421✔
276
    /* before adding, check that we don't add a duplicate entry, which will
277
     * propagate all the way into the packet runtime if allowed. */
278
    DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
993,421✔
279
    while (t != NULL) {
279,740,808✔
280
        const uint32_t t_direction = t->dir == 0 ? SIG_FLAG_TOSERVER : SIG_FLAG_TOCLIENT;
278,747,387✔
281
        const int sm_list = DetectBufferTypeGetByName(name);
278,747,387✔
282

283
        if (t->sm_list == sm_list && t->alproto == alproto && t_direction == dir &&
278,747,387!
284
                t->progress == progress && t->v2.Callback == Callback && t->v2.GetData == GetData) {
278,747,387!
285
            DEBUG_VALIDATE_BUG_ON(1);
×
286
            return;
×
287
        }
×
288
        t = t->next;
278,747,387✔
289
    }
278,747,387✔
290

291
    AppLayerInspectEngineRegisterInternal(
993,421✔
292
            name, alproto, dir, progress, Callback, GetData, NULL, NULL);
993,421✔
293
}
993,421✔
294

295
void DetectAppLayerInspectEngineRegisterSingle(const char *name, AppProto alproto, uint32_t dir,
296
        int progress, InspectEngineFuncPtr Callback, InspectionSingleBufferGetDataPtr GetData)
297
{
175,408✔
298
    /* before adding, check that we don't add a duplicate entry, which will
299
     * propagate all the way into the packet runtime if allowed. */
300
    DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
175,408✔
301
    while (t != NULL) {
102,813,791✔
302
        const uint32_t t_direction = t->dir == 0 ? SIG_FLAG_TOSERVER : SIG_FLAG_TOCLIENT;
102,638,383✔
303
        const int sm_list = DetectBufferTypeGetByName(name);
102,638,383✔
304

305
        if (t->sm_list == sm_list && t->alproto == alproto && t_direction == dir &&
102,638,383!
306
                t->progress == progress && t->v2.Callback == Callback &&
102,638,383!
307
                t->v2.GetDataSingle == GetData) {
102,638,383!
308
            DEBUG_VALIDATE_BUG_ON(1);
×
309
            return;
×
310
        }
×
311
        t = t->next;
102,638,383✔
312
    }
102,638,383✔
313

314
    AppLayerInspectEngineRegisterInternal(
175,408✔
315
            name, alproto, dir, progress, Callback, NULL, GetData, NULL);
175,408✔
316
}
175,408✔
317

318
/* copy an inspect engine with transforms to a new list id. */
319
static void DetectAppLayerInspectEngineCopy(
320
        DetectEngineCtx *de_ctx,
321
        int sm_list, int new_list,
322
        const DetectEngineTransforms *transforms)
323
{
63,713✔
324
    const DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
63,713✔
325
    while (t) {
43,894,889✔
326
        if (t->sm_list == sm_list) {
43,831,176✔
327
            DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
532,767✔
328
            if (unlikely(new_engine == NULL)) {
532,767!
329
                exit(EXIT_FAILURE);
×
330
            }
×
331
            new_engine->alproto = t->alproto;
532,767✔
332
            new_engine->dir = t->dir;
532,767✔
333
            DEBUG_VALIDATE_BUG_ON(new_list < 0 || new_list > UINT16_MAX);
532,767✔
334
            new_engine->sm_list = (uint16_t)new_list; /* use new list id */
532,767✔
335
            DEBUG_VALIDATE_BUG_ON(sm_list < 0 || sm_list > UINT16_MAX);
532,767✔
336
            new_engine->sm_list_base = (uint16_t)sm_list;
532,767✔
337
            new_engine->progress = t->progress;
532,767✔
338
            new_engine->v2 = t->v2;
532,767✔
339
            new_engine->v2.transforms = transforms; /* assign transforms */
532,767✔
340

341
            if (de_ctx->app_inspect_engines == NULL) {
532,767!
342
                de_ctx->app_inspect_engines = new_engine;
×
343
            } else {
532,767✔
344
                DetectEngineAppInspectionEngine *list = de_ctx->app_inspect_engines;
532,767✔
345
                while (list->next != NULL) {
1,047,651,598✔
346
                    list = list->next;
1,047,118,831✔
347
                }
1,047,118,831✔
348

349
                list->next = new_engine;
532,767✔
350
            }
532,767✔
351
        }
532,767✔
352
        t = t->next;
43,831,176✔
353
    }
43,831,176✔
354
}
63,713✔
355

356
/* copy inspect engines from global registrations to de_ctx list */
357
static void DetectAppLayerInspectEngineCopyListToDetectCtx(DetectEngineCtx *de_ctx)
358
{
38,898✔
359
    const DetectEngineAppInspectionEngine *t = g_app_inspect_engines;
38,898✔
360
    DetectEngineAppInspectionEngine *list = de_ctx->app_inspect_engines;
38,898✔
361
    while (t) {
26,793,955✔
362
        DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
26,755,057✔
363
        if (unlikely(new_engine == NULL)) {
26,755,057!
364
            exit(EXIT_FAILURE);
×
365
        }
×
366
        new_engine->alproto = t->alproto;
26,755,057✔
367
        new_engine->dir = t->dir;
26,755,057✔
368
        new_engine->sm_list = t->sm_list;
26,755,057✔
369
        new_engine->sm_list_base = t->sm_list;
26,755,057✔
370
        new_engine->progress = t->progress;
26,755,057✔
371
        new_engine->v2 = t->v2;
26,755,057✔
372

373
        if (list == NULL) {
26,755,057✔
374
            de_ctx->app_inspect_engines = new_engine;
38,898✔
375
        } else {
26,716,159✔
376
            list->next = new_engine;
26,716,159✔
377
        }
26,716,159✔
378
        list = new_engine;
26,755,057✔
379

380
        t = t->next;
26,755,057✔
381
    }
26,755,057✔
382
}
38,898✔
383

384
/* copy an inspect engine with transforms to a new list id. */
385
static void DetectPktInspectEngineCopy(
386
        DetectEngineCtx *de_ctx,
387
        int sm_list, int new_list,
388
        const DetectEngineTransforms *transforms)
389
{
1,520✔
390
    const DetectEnginePktInspectionEngine *t = g_pkt_inspect_engines;
1,520✔
391
    while (t) {
15,200✔
392
        if (t->sm_list == sm_list) {
13,680✔
393
            DetectEnginePktInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEnginePktInspectionEngine));
1,520✔
394
            if (unlikely(new_engine == NULL)) {
1,520!
395
                exit(EXIT_FAILURE);
×
396
            }
×
397
            DEBUG_VALIDATE_BUG_ON(new_list < 0 || new_list > UINT16_MAX);
1,520✔
398
            new_engine->sm_list = (uint16_t)new_list; /* use new list id */
1,520✔
399
            DEBUG_VALIDATE_BUG_ON(sm_list < 0 || sm_list > UINT16_MAX);
1,520✔
400
            new_engine->sm_list_base = (uint16_t)sm_list;
1,520✔
401
            new_engine->v1 = t->v1;
1,520✔
402
            new_engine->v1.transforms = transforms; /* assign transforms */
1,520✔
403

404
            if (de_ctx->pkt_inspect_engines == NULL) {
1,520!
405
                de_ctx->pkt_inspect_engines = new_engine;
×
406
            } else {
1,520✔
407
                DetectEnginePktInspectionEngine *list = de_ctx->pkt_inspect_engines;
1,520✔
408
                while (list->next != NULL) {
84,152✔
409
                    list = list->next;
82,632✔
410
                }
82,632✔
411

412
                list->next = new_engine;
1,520✔
413
            }
1,520✔
414
        }
1,520✔
415
        t = t->next;
13,680✔
416
    }
13,680✔
417
}
1,520✔
418

419
/* copy inspect engines from global registrations to de_ctx list */
420
static void DetectPktInspectEngineCopyListToDetectCtx(DetectEngineCtx *de_ctx)
421
{
38,898✔
422
    const DetectEnginePktInspectionEngine *t = g_pkt_inspect_engines;
38,898✔
423
    while (t) {
388,980✔
424
        SCLogDebug("engine %p", t);
350,082!
425
        DetectEnginePktInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEnginePktInspectionEngine));
350,082✔
426
        if (unlikely(new_engine == NULL)) {
350,082!
427
            exit(EXIT_FAILURE);
×
428
        }
×
429
        new_engine->sm_list = t->sm_list;
350,082✔
430
        new_engine->sm_list_base = t->sm_list;
350,082✔
431
        new_engine->v1 = t->v1;
350,082✔
432

433
        if (de_ctx->pkt_inspect_engines == NULL) {
350,082✔
434
            de_ctx->pkt_inspect_engines = new_engine;
38,898✔
435
        } else {
311,184✔
436
            DetectEnginePktInspectionEngine *list = de_ctx->pkt_inspect_engines;
311,184✔
437
            while (list->next != NULL) {
1,400,328✔
438
                list = list->next;
1,089,144✔
439
            }
1,089,144✔
440

441
            list->next = new_engine;
311,184✔
442
        }
311,184✔
443

444
        t = t->next;
350,082✔
445
    }
350,082✔
446
}
38,898✔
447

448
/** \brief register inspect engine at start up time
449
 *
450
 *  \note errors are fatal */
451
void DetectEngineFrameInspectEngineRegister(DetectEngineCtx *de_ctx, const char *name, int dir,
452
        InspectionBufferFrameInspectFunc Callback, AppProto alproto, uint8_t type)
453
{
7,108✔
454
    const int sm_list = DetectEngineBufferTypeRegister(de_ctx, name);
7,108✔
455
    if (sm_list < 0) {
7,108!
456
        FatalError("failed to register inspect engine %s", name);
×
457
    }
×
458

459
    if ((sm_list < DETECT_SM_LIST_MATCH) || (sm_list >= SHRT_MAX) || (Callback == NULL)) {
7,108!
460
        SCLogError("Invalid arguments");
×
461
        BUG_ON(1);
×
462
    }
×
463

464
    uint8_t direction;
7,108✔
465
    if (dir == SIG_FLAG_TOSERVER) {
7,108✔
466
        direction = 0;
3,554✔
467
    } else {
3,554✔
468
        direction = 1;
3,554✔
469
    }
3,554✔
470

471
    DetectEngineFrameInspectionEngine *new_engine = SCCalloc(1, sizeof(*new_engine));
7,108✔
472
    if (unlikely(new_engine == NULL)) {
7,108!
473
        FatalError("failed to register inspect engine %s: %s", name, strerror(errno));
×
474
    }
×
475
    new_engine->sm_list = (uint16_t)sm_list;
7,108✔
476
    new_engine->sm_list_base = (uint16_t)sm_list;
7,108✔
477
    new_engine->dir = direction;
7,108✔
478
    new_engine->v1.Callback = Callback;
7,108✔
479
    new_engine->alproto = alproto;
7,108✔
480
    new_engine->type = type;
7,108✔
481

482
    if (de_ctx->frame_inspect_engines == NULL) {
7,108✔
483
        de_ctx->frame_inspect_engines = new_engine;
1,753✔
484
    } else {
5,355✔
485
        DetectEngineFrameInspectionEngine *list = de_ctx->frame_inspect_engines;
5,355✔
486
        while (list->next != NULL) {
16,906✔
487
            list = list->next;
11,551✔
488
        }
11,551✔
489

490
        list->next = new_engine;
5,355✔
491
    }
5,355✔
492
}
7,108✔
493

494
/* copy an inspect engine with transforms to a new list id. */
495
static void DetectFrameInspectEngineCopy(DetectEngineCtx *de_ctx, int sm_list, int new_list,
496
        const DetectEngineTransforms *transforms)
497
{
387✔
498
    /* take the list from the detect engine as the buffers can be registered
499
     * dynamically. */
500
    DetectEngineFrameInspectionEngine *t = de_ctx->frame_inspect_engines;
387✔
501
    while (t) {
7,167✔
502
        if (t->sm_list == sm_list) {
6,780✔
503
            DetectEngineFrameInspectionEngine *new_engine =
774✔
504
                    SCCalloc(1, sizeof(DetectEngineFrameInspectionEngine));
774✔
505
            if (unlikely(new_engine == NULL)) {
774!
506
                exit(EXIT_FAILURE);
×
507
            }
×
508
            DEBUG_VALIDATE_BUG_ON(new_list < 0 || new_list > UINT16_MAX);
774✔
509
            new_engine->sm_list = (uint16_t)new_list; /* use new list id */
774✔
510
            DEBUG_VALIDATE_BUG_ON(sm_list < 0 || sm_list > UINT16_MAX);
774✔
511
            new_engine->sm_list_base = (uint16_t)sm_list;
774✔
512
            new_engine->dir = t->dir;
774✔
513
            new_engine->alproto = t->alproto;
774✔
514
            new_engine->type = t->type;
774✔
515
            new_engine->v1 = t->v1;
774✔
516
            new_engine->v1.transforms = transforms; /* assign transforms */
774✔
517

518
            /* append to the list */
519
            DetectEngineFrameInspectionEngine *list = t;
774✔
520
            while (list->next != NULL) {
9,612✔
521
                list = list->next;
8,838✔
522
            }
8,838✔
523

524
            list->next = new_engine;
774✔
525
        }
774✔
526
        t = t->next;
6,780✔
527
    }
6,780✔
528
}
387✔
529

530
/* copy inspect engines from global registrations to de_ctx list */
531
static void DetectFrameInspectEngineCopyListToDetectCtx(DetectEngineCtx *de_ctx)
532
{
38,898✔
533
    const DetectEngineFrameInspectionEngine *t = g_frame_inspect_engines;
38,898✔
534
    while (t) {
38,898!
535
        SCLogDebug("engine %p", t);
×
536
        DetectEngineFrameInspectionEngine *new_engine =
×
537
                SCCalloc(1, sizeof(DetectEngineFrameInspectionEngine));
×
538
        if (unlikely(new_engine == NULL)) {
×
539
            exit(EXIT_FAILURE);
×
540
        }
×
541
        new_engine->sm_list = t->sm_list;
×
542
        new_engine->sm_list_base = t->sm_list;
×
543
        new_engine->dir = t->dir;
×
544
        new_engine->alproto = t->alproto;
×
545
        new_engine->type = t->type;
×
546
        new_engine->v1 = t->v1;
×
547

548
        if (de_ctx->frame_inspect_engines == NULL) {
×
549
            de_ctx->frame_inspect_engines = new_engine;
×
550
        } else {
×
551
            DetectEngineFrameInspectionEngine *list = de_ctx->frame_inspect_engines;
×
552
            while (list->next != NULL) {
×
553
                list = list->next;
×
554
            }
×
555

556
            list->next = new_engine;
×
557
        }
×
558

559
        t = t->next;
×
560
    }
×
561
}
38,898✔
562

563
/** \internal
564
 *  \brief append the stream inspection
565
 *
566
 *  If stream inspection is MPM, then prepend it.
567
 */
568
static void AppendStreamInspectEngine(
569
        Signature *s, SigMatchData *stream, uint8_t direction, uint8_t id)
570
{
5,324✔
571
    bool prepend = false;
5,324✔
572

573
    DetectEngineAppInspectionEngine *new_engine = SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
5,324✔
574
    if (unlikely(new_engine == NULL)) {
5,324!
575
        exit(EXIT_FAILURE);
×
576
    }
×
577
    if (s->init_data->mpm_sm_list == DETECT_SM_LIST_PMATCH) {
5,324✔
578
        SCLogDebug("stream is mpm");
1,356!
579
        prepend = true;
1,356✔
580
        new_engine->mpm = true;
1,356✔
581
    }
1,356✔
582
    new_engine->alproto = ALPROTO_UNKNOWN; /* all */
5,324✔
583
    new_engine->dir = direction;
5,324✔
584
    new_engine->stream = true;
5,324✔
585
    new_engine->sm_list = DETECT_SM_LIST_PMATCH;
5,324✔
586
    new_engine->sm_list_base = DETECT_SM_LIST_PMATCH;
5,324✔
587
    new_engine->smd = stream;
5,324✔
588
    new_engine->v2.Callback = DetectEngineInspectStream;
5,324✔
589
    new_engine->progress = 0;
5,324✔
590

591
    /* append */
592
    if (s->app_inspect == NULL) {
5,324✔
593
        s->app_inspect = new_engine;
41✔
594
        new_engine->id = DE_STATE_FLAG_BASE; /* id is used as flag in stateful detect */
41✔
595
    } else if (prepend) {
5,283✔
596
        new_engine->next = s->app_inspect;
1,315✔
597
        s->app_inspect = new_engine;
1,315✔
598
        new_engine->id = id;
1,315✔
599

600
    } else {
3,968✔
601
        DetectEngineAppInspectionEngine *a = s->app_inspect;
3,968✔
602
        while (a->next != NULL) {
74,214✔
603
            a = a->next;
70,246✔
604
        }
70,246✔
605

606
        a->next = new_engine;
3,968✔
607
        new_engine->id = id;
3,968✔
608
    }
3,968✔
609
    SCLogDebug("sid %u: engine %p/%u added", s->id, new_engine, new_engine->id);
5,324!
610
}
5,324✔
611

612
static void AppendFrameInspectEngine(DetectEngineCtx *de_ctx,
613
        const DetectEngineFrameInspectionEngine *u, Signature *s, SigMatchData *smd,
614
        const int mpm_list)
615
{
6,726✔
616
    bool prepend = false;
6,726✔
617

618
    if (u->alproto == ALPROTO_UNKNOWN) {
6,726!
619
        /* special case, inspect engine applies to all protocols */
620
    } else if (s->alproto != ALPROTO_UNKNOWN && !AppProtoEquals(s->alproto, u->alproto))
6,726!
621
        return;
×
622

623
    if (s->flags & SIG_FLAG_TOSERVER && !(s->flags & SIG_FLAG_TOCLIENT)) {
6,726✔
624
        if (u->dir == 1)
2,720✔
625
            return;
1,360✔
626
    } else if (s->flags & SIG_FLAG_TOCLIENT && !(s->flags & SIG_FLAG_TOSERVER)) {
4,006!
627
        if (u->dir == 0)
1,548✔
628
            return;
774✔
629
    }
1,548✔
630

631
    DetectEngineFrameInspectionEngine *new_engine =
4,592✔
632
            SCCalloc(1, sizeof(DetectEngineFrameInspectionEngine));
4,592✔
633
    if (unlikely(new_engine == NULL)) {
4,592!
634
        exit(EXIT_FAILURE);
×
635
    }
×
636
    if (mpm_list == u->sm_list) {
4,592✔
637
        SCLogDebug("%s is mpm", DetectEngineBufferTypeGetNameById(de_ctx, u->sm_list));
4,475!
638
        prepend = true;
4,475✔
639
        new_engine->mpm = true;
4,475✔
640
    }
4,475✔
641

642
    new_engine->type = u->type;
4,592✔
643
    new_engine->sm_list = u->sm_list;
4,592✔
644
    new_engine->sm_list_base = u->sm_list_base;
4,592✔
645
    new_engine->smd = smd;
4,592✔
646
    new_engine->v1 = u->v1;
4,592✔
647
    SCLogDebug("sm_list %d new_engine->v1 %p/%p", new_engine->sm_list, new_engine->v1.Callback,
4,592!
648
            new_engine->v1.transforms);
4,592✔
649

650
    if (s->frame_inspect == NULL) {
4,592✔
651
        s->frame_inspect = new_engine;
3,363✔
652
    } else if (prepend) {
3,363✔
653
        new_engine->next = s->frame_inspect;
1,172✔
654
        s->frame_inspect = new_engine;
1,172✔
655
    } else {
1,172✔
656
        DetectEngineFrameInspectionEngine *a = s->frame_inspect;
57✔
657
        while (a->next != NULL) {
57!
658
            a = a->next;
×
659
        }
×
660
        new_engine->next = a->next;
57✔
661
        a->next = new_engine;
57✔
662
    }
57✔
663
}
4,592✔
664

665
static void AppendPacketInspectEngine(DetectEngineCtx *de_ctx,
666
        const DetectEnginePktInspectionEngine *e, Signature *s, SigMatchData *smd,
667
        const int mpm_list)
668
{
963✔
669
    bool prepend = false;
963✔
670

671
    DetectEnginePktInspectionEngine *new_engine =
963✔
672
            SCCalloc(1, sizeof(DetectEnginePktInspectionEngine));
963✔
673
    if (unlikely(new_engine == NULL)) {
963!
674
        exit(EXIT_FAILURE);
×
675
    }
×
676
    if (mpm_list == e->sm_list) {
963✔
677
        SCLogDebug("%s is mpm", DetectEngineBufferTypeGetNameById(de_ctx, e->sm_list));
393!
678
        prepend = true;
393✔
679
        new_engine->mpm = true;
393✔
680
    }
393✔
681

682
    new_engine->sm_list = e->sm_list;
963✔
683
    new_engine->sm_list_base = e->sm_list_base;
963✔
684
    new_engine->smd = smd;
963✔
685
    new_engine->v1 = e->v1;
963✔
686
    SCLogDebug("sm_list %d new_engine->v1 %p/%p/%p", new_engine->sm_list, new_engine->v1.Callback,
963!
687
            new_engine->v1.GetData, new_engine->v1.transforms);
963✔
688

689
    if (s->pkt_inspect == NULL) {
963✔
690
        s->pkt_inspect = new_engine;
881✔
691
    } else if (prepend) {
881!
692
        new_engine->next = s->pkt_inspect;
13✔
693
        s->pkt_inspect = new_engine;
13✔
694
    } else {
69✔
695
        DetectEnginePktInspectionEngine *a = s->pkt_inspect;
69✔
696
        while (a->next != NULL) {
333!
697
            a = a->next;
264✔
698
        }
264✔
699
        new_engine->next = a->next;
69✔
700
        a->next = new_engine;
69✔
701
    }
69✔
702
}
963✔
703

704
static void AppendAppInspectEngine(DetectEngineCtx *de_ctx,
705
        const DetectEngineAppInspectionEngine *t, Signature *s, SigMatchData *smd,
706
        const int mpm_list, const int files_id, uint8_t *last_id, bool *head_is_mpm)
707
{
651,394✔
708
    if (t->alproto == ALPROTO_UNKNOWN) {
651,394✔
709
        /* special case, inspect engine applies to all protocols */
710
    } else if (s->alproto != ALPROTO_UNKNOWN && !AppProtoEquals(s->alproto, t->alproto))
611,364✔
711
        return;
232,649✔
712

713
    if (s->flags & SIG_FLAG_TOSERVER && !(s->flags & SIG_FLAG_TOCLIENT)) {
418,745✔
714
        if (t->dir == 1)
240,437✔
715
            return;
29,989✔
716
    } else if (s->flags & SIG_FLAG_TOCLIENT && !(s->flags & SIG_FLAG_TOSERVER)) {
319,421!
717
        if (t->dir == 0)
55,543✔
718
            return;
22,574✔
719
    }
55,543✔
720
    SCLogDebug("app engine: t %p t->id %u => alproto:%s files:%s", t, t->id,
366,182!
721
            AppProtoToString(t->alproto), BOOL2STR(t->sm_list == files_id));
366,182✔
722

723
    DetectEngineAppInspectionEngine *new_engine =
366,182✔
724
            SCCalloc(1, sizeof(DetectEngineAppInspectionEngine));
366,182✔
725
    if (unlikely(new_engine == NULL)) {
366,182!
726
        exit(EXIT_FAILURE);
×
727
    }
×
728
    bool prepend = false;
366,182✔
729
    if (mpm_list == t->sm_list) {
366,182✔
730
        SCLogDebug("%s is mpm", DetectEngineBufferTypeGetNameById(de_ctx, t->sm_list));
202,905!
731
        prepend = true;
202,905✔
732
        *head_is_mpm = true;
202,905✔
733
        new_engine->mpm = true;
202,905✔
734
    }
202,905✔
735

736
    new_engine->alproto = t->alproto;
366,182✔
737
    new_engine->dir = t->dir;
366,182✔
738
    new_engine->sm_list = t->sm_list;
366,182✔
739
    new_engine->sm_list_base = t->sm_list_base;
366,182✔
740
    new_engine->smd = smd;
366,182✔
741
    new_engine->match_on_null = smd ? DetectContentInspectionMatchOnAbsentBuffer(smd) : false;
366,182✔
742
    new_engine->progress = t->progress;
366,182✔
743
    new_engine->v2 = t->v2;
366,182✔
744
    SCLogDebug("sm_list %d new_engine->v2 %p/%p/%p", new_engine->sm_list, new_engine->v2.Callback,
366,182!
745
            new_engine->v2.GetData, new_engine->v2.transforms);
366,182✔
746

747
    if (s->app_inspect == NULL) {
366,182✔
748
        s->app_inspect = new_engine;
127,778✔
749
        if (new_engine->sm_list == files_id) {
127,778✔
750
            new_engine->id = DE_STATE_ID_FILE_INSPECT;
670✔
751
            SCLogDebug("sid %u: engine %p/%u is FILE ENGINE", s->id, new_engine, new_engine->id);
670!
752
        } else {
127,108✔
753
            new_engine->id = DE_STATE_FLAG_BASE; /* id is used as flag in stateful detect */
127,108✔
754
            SCLogDebug("sid %u: engine %p/%u %s", s->id, new_engine, new_engine->id,
127,108!
755
                    DetectEngineBufferTypeGetNameById(de_ctx, new_engine->sm_list));
127,108✔
756
        }
127,108✔
757

758
        /* prepend engine if forced or if our engine has a lower progress. */
759
    } else if (prepend || (!(*head_is_mpm) && s->app_inspect->progress > new_engine->progress)) {
238,450✔
760
        new_engine->next = s->app_inspect;
135,927✔
761
        s->app_inspect = new_engine;
135,927✔
762
        if (new_engine->sm_list == files_id) {
135,927!
763
            new_engine->id = DE_STATE_ID_FILE_INSPECT;
2✔
764
            SCLogDebug("sid %u: engine %p/%u is FILE ENGINE", s->id, new_engine, new_engine->id);
2!
765
        } else {
135,925✔
766
            new_engine->id = ++(*last_id);
135,925✔
767
            SCLogDebug("sid %u: engine %p/%u %s", s->id, new_engine, new_engine->id,
135,925!
768
                    DetectEngineBufferTypeGetNameById(de_ctx, new_engine->sm_list));
135,925✔
769
        }
135,925✔
770

771
    } else {
135,927✔
772
        DetectEngineAppInspectionEngine *a = s->app_inspect;
102,477✔
773
        while (a->next != NULL) {
406,264✔
774
            if (a->next && a->next->progress > new_engine->progress) {
335,825!
775
                break;
32,038✔
776
            }
32,038✔
777
            a = a->next;
303,787✔
778
        }
303,787✔
779

780
        new_engine->next = a->next;
102,477✔
781
        a->next = new_engine;
102,477✔
782
        if (new_engine->sm_list == files_id) {
102,477✔
783
            new_engine->id = DE_STATE_ID_FILE_INSPECT;
24,643✔
784
            SCLogDebug("sid %u: engine %p/%u is FILE ENGINE", s->id, new_engine, new_engine->id);
24,643!
785
        } else {
81,437✔
786
            new_engine->id = ++(*last_id);
77,834✔
787
            SCLogDebug("sid %u: engine %p/%u %s", s->id, new_engine, new_engine->id,
77,834!
788
                    DetectEngineBufferTypeGetNameById(de_ctx, new_engine->sm_list));
77,834✔
789
        }
77,834✔
790
    }
102,477✔
791

792
    SCLogDebug("sid %u: engine %p/%u added", s->id, new_engine, new_engine->id);
366,182!
793

794
    s->init_data->init_flags |= SIG_FLAG_INIT_STATE_MATCH;
366,182✔
795
}
366,182✔
796

797
/**
798
 *  \note for the file inspect engine, the id DE_STATE_ID_FILE_INSPECT
799
 *        is assigned.
800
 */
801
int DetectEngineAppInspectionEngine2Signature(DetectEngineCtx *de_ctx, Signature *s)
802
{
266,105✔
803
    const int mpm_list = s->init_data->mpm_sm ? s->init_data->mpm_sm_list : -1;
266,105✔
804
    const int files_id = DetectBufferTypeGetByName("files");
266,105✔
805
    bool head_is_mpm = false;
266,105✔
806
    uint8_t last_id = DE_STATE_FLAG_BASE;
266,105✔
807
    SCLogDebug("%u: setup app inspect engines. %u buffers", s->id, s->init_data->buffer_index);
266,105!
808

809
    for (uint32_t x = 0; x < s->init_data->buffer_index; x++) {
440,268✔
810
        SigMatchData *smd = SigMatchList2DataArray(s->init_data->buffers[x].head);
174,163✔
811
        SCLogDebug("smd %p, id %u", smd, s->init_data->buffers[x].id);
174,163!
812

813
        const DetectBufferType *b =
174,163✔
814
                DetectEngineBufferTypeGetById(de_ctx, s->init_data->buffers[x].id);
174,163✔
815
        if (b == NULL)
174,163!
816
            FatalError("unknown buffer");
×
817

818
        if (b->frame) {
174,163✔
819
            for (const DetectEngineFrameInspectionEngine *u = de_ctx->frame_inspect_engines;
3,363✔
820
                    u != NULL; u = u->next) {
25,765✔
821
                if (u->sm_list == s->init_data->buffers[x].id) {
22,402✔
822
                    AppendFrameInspectEngine(de_ctx, u, s, smd, mpm_list);
6,726✔
823
                }
6,726✔
824
            }
22,402✔
825
        } else if (b->packet) {
170,800✔
826
            /* set up pkt inspect engines */
827
            for (const DetectEnginePktInspectionEngine *e = de_ctx->pkt_inspect_engines; e != NULL;
9,935✔
828
                    e = e->next) {
8,972✔
829
                SCLogDebug("e %p sm_list %u", e, e->sm_list);
8,972!
830
                if (e->sm_list == s->init_data->buffers[x].id) {
8,972✔
831
                    AppendPacketInspectEngine(de_ctx, e, s, smd, mpm_list);
963✔
832
                }
963✔
833
            }
8,972✔
834
        } else {
169,867✔
835
            SCLogDebug("app %s id %u parent %u rule %u xforms %u", b->name, b->id, b->parent_id,
169,837!
836
                    s->init_data->buffers[x].id, b->transforms.cnt);
169,837✔
837
            for (const DetectEngineAppInspectionEngine *t = de_ctx->app_inspect_engines; t != NULL;
121,409,197✔
838
                    t = t->next) {
121,239,360✔
839
                if (t->sm_list == s->init_data->buffers[x].id) {
121,239,360✔
840
                    if (s->flags & SIG_FLAG_TXBOTHDIR) {
651,754✔
841
                        // ambiguous keywords have app engines in both directions
842
                        // so we skip the wrong direction for this buffer
843
                        if (s->init_data->buffers[x].only_tc && t->dir == 0) {
1,907✔
844
                            continue;
391✔
845
                        } else if (s->init_data->buffers[x].only_ts && t->dir == 1) {
1,516✔
846
                            continue;
102✔
847
                        }
102✔
848
                    }
1,907✔
849
                    AppendAppInspectEngine(
651,261✔
850
                            de_ctx, t, s, smd, mpm_list, files_id, &last_id, &head_is_mpm);
651,261✔
851
                }
651,261✔
852
            }
121,239,360✔
853
        }
169,837✔
854
    }
174,163✔
855

856
    /* handle rules that have an app-layer hook w/o bringing their own app inspect engine,
857
     * e.g. `alert dns:request_complete ... (sid:1;)`
858
     *
859
     * Here we use a minimal stub inspect engine in which we set:
860
     * - alproto
861
     * - progress
862
     * - sm_list/sm_list_base to get the mapping to the hook name
863
     * - dir based on sig direction
864
     *
865
     * The inspect engine has no callback and is thus considered a straight match.
866
     */
867
    if (s->init_data->buffer_index == 0 && s->init_data->hook.type == SIGNATURE_HOOK_TYPE_APP) {
266,105✔
868
        uint8_t dir = 0;
133✔
869
        BUG_ON((s->flags & (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT)) ==
133!
870
                (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT));
133✔
871
        BUG_ON((s->flags & (SIG_FLAG_TOSERVER | SIG_FLAG_TOCLIENT)) == 0);
133!
872
        if (s->flags & SIG_FLAG_TOSERVER)
133✔
873
            dir = 0;
72✔
874
        else if (s->flags & SIG_FLAG_TOCLIENT)
61!
875
            dir = 1;
61✔
876

877
        DetectEngineAppInspectionEngine t = {
133✔
878
            .alproto = s->init_data->hook.t.app.alproto,
133✔
879
            .progress = (uint16_t)s->init_data->hook.t.app.app_progress,
133✔
880
            .sm_list = (uint16_t)s->init_data->hook.sm_list,
133✔
881
            .sm_list_base = (uint16_t)s->init_data->hook.sm_list,
133✔
882
            .dir = dir,
133✔
883
        };
133✔
884
        AppendAppInspectEngine(de_ctx, &t, s, NULL, mpm_list, files_id, &last_id, &head_is_mpm);
133✔
885
    }
133✔
886

887
    if ((s->init_data->init_flags & SIG_FLAG_INIT_STATE_MATCH) &&
266,105✔
888
            s->init_data->smlists[DETECT_SM_LIST_PMATCH] != NULL)
266,105✔
889
    {
3,552✔
890
        /* if engine is added multiple times, we pass it the same list */
891
        SigMatchData *stream = SigMatchList2DataArray(s->init_data->smlists[DETECT_SM_LIST_PMATCH]);
3,552✔
892
        BUG_ON(stream == NULL);
3,552!
893
        if (s->flags & SIG_FLAG_TOSERVER && !(s->flags & SIG_FLAG_TOCLIENT)) {
3,552✔
894
            AppendStreamInspectEngine(s, stream, 0, last_id + 1);
1,684✔
895
        } else if (s->flags & SIG_FLAG_TOCLIENT && !(s->flags & SIG_FLAG_TOSERVER)) {
2,629!
896
            AppendStreamInspectEngine(s, stream, 1, last_id + 1);
96✔
897
        } else {
1,834✔
898
            AppendStreamInspectEngine(s, stream, 0, last_id + 1);
1,772✔
899
            AppendStreamInspectEngine(s, stream, 1, last_id + 1);
1,772✔
900
        }
1,772✔
901

902
        if (s->init_data->init_flags & SIG_FLAG_INIT_NEED_FLUSH) {
3,552✔
903
            SCLogDebug("set SIG_FLAG_FLUSH on %u", s->id);
468!
904
            s->flags |= SIG_FLAG_FLUSH;
468✔
905
        }
468✔
906
    }
3,552✔
907

908
#ifdef DEBUG
909
    const DetectEngineAppInspectionEngine *iter = s->app_inspect;
910
    while (iter) {
911
        SCLogDebug("%u: engine %s id %u progress %d %s", s->id,
912
                DetectEngineBufferTypeGetNameById(de_ctx, iter->sm_list), iter->id, iter->progress,
913
                iter->sm_list == mpm_list ? "MPM" : "");
914
        iter = iter->next;
915
    }
916
#endif
917
    return 0;
266,105✔
918
}
266,105✔
919

920
/** \brief free app inspect engines for a signature
921
 *
922
 *  For lists that are registered multiple times, like http_header and
923
 *  http_cookie, making the engines owner of the lists is complicated.
924
 *  Multiple engines in a sig may be pointing to the same list. To
925
 *  address this the 'free' code needs to be extra careful about not
926
 *  double freeing, so it takes an approach to first fill an array
927
 *  of the to-free pointers before freeing them.
928
 */
929
void DetectEngineAppInspectionEngineSignatureFree(DetectEngineCtx *de_ctx, Signature *s)
930
{
5,314,632✔
931
    int engines = 0;
5,314,632✔
932

933
    DetectEngineAppInspectionEngine *ie = s->app_inspect;
5,314,632✔
934
    while (ie) {
5,686,134✔
935
        ie = ie->next;
371,502✔
936
        engines++;
371,502✔
937
    }
371,502✔
938
    DetectEnginePktInspectionEngine *e = s->pkt_inspect;
5,314,632✔
939
    while (e) {
5,445,425✔
940
        e = e->next;
130,793✔
941
        engines++;
130,793✔
942
    }
130,793✔
943
    DetectEngineFrameInspectionEngine *u = s->frame_inspect;
5,314,632✔
944
    while (u) {
5,319,224✔
945
        u = u->next;
4,592✔
946
        engines++;
4,592✔
947
    }
4,592✔
948
    if (engines == 0) {
5,314,632✔
949
        BUG_ON(s->pkt_inspect);
5,126,261!
950
        BUG_ON(s->frame_inspect);
5,126,261!
951
        return;
5,126,261✔
952
    }
5,126,261✔
953

954
    SigMatchData *bufs[engines];
188,371✔
955
    memset(&bufs, 0, (engines * sizeof(SigMatchData *)));
188,371✔
956
    int arrays = 0;
188,371✔
957

958
    /* free engines and put smd in the array */
959
    ie = s->app_inspect;
188,371✔
960
    while (ie) {
559,873✔
961
        DetectEngineAppInspectionEngine *next = ie->next;
371,502✔
962

963
        bool skip = false;
371,502✔
964
        for (int i = 0; i < arrays; i++) {
542,227✔
965
            if (bufs[i] == ie->smd) {
368,707✔
966
                skip = true;
197,982✔
967
                break;
197,982✔
968
            }
197,982✔
969
        }
368,707✔
970
        if (!skip) {
371,502✔
971
            bufs[arrays++] = ie->smd;
173,520✔
972
        }
173,520✔
973
        SCFree(ie);
371,502✔
974
        ie = next;
371,502✔
975
    }
371,502✔
976
    e = s->pkt_inspect;
188,371✔
977
    while (e) {
319,164✔
978
        DetectEnginePktInspectionEngine *next = e->next;
130,793✔
979

980
        bool skip = false;
130,793✔
981
        for (int i = 0; i < arrays; i++) {
231,304✔
982
            if (bufs[i] == e->smd) {
112,159✔
983
                skip = true;
11,648✔
984
                break;
11,648✔
985
            }
11,648✔
986
        }
112,159✔
987
        if (!skip) {
130,793✔
988
            bufs[arrays++] = e->smd;
119,145✔
989
        }
119,145✔
990
        SCFree(e);
130,793✔
991
        e = next;
130,793✔
992
    }
130,793✔
993
    u = s->frame_inspect;
188,371✔
994
    while (u) {
192,963✔
995
        DetectEngineFrameInspectionEngine *next = u->next;
4,592✔
996

997
        bool skip = false;
4,592✔
998
        for (int i = 0; i < arrays; i++) {
4,746✔
999
            if (bufs[i] == u->smd) {
1,383✔
1000
                skip = true;
1,229✔
1001
                break;
1,229✔
1002
            }
1,229✔
1003
        }
1,383✔
1004
        if (!skip) {
4,592✔
1005
            bufs[arrays++] = u->smd;
3,363✔
1006
        }
3,363✔
1007
        SCFree(u);
4,592✔
1008
        u = next;
4,592✔
1009
    }
4,592✔
1010

1011
    for (int i = 0; i < engines; i++) {
695,258✔
1012
        if (bufs[i] == NULL)
506,887✔
1013
            continue;
329,174✔
1014
        SigMatchData *smd = bufs[i];
177,713✔
1015
        while (1) {
272,719!
1016
            if (sigmatch_table[smd->type].Free != NULL) {
272,719✔
1017
                sigmatch_table[smd->type].Free(de_ctx, smd->ctx);
272,713✔
1018
            }
272,713✔
1019
            if (smd->is_last)
272,719✔
1020
                break;
177,713✔
1021
            smd++;
95,006✔
1022
        }
95,006✔
1023
        SCFree(bufs[i]);
177,713✔
1024
    }
177,713✔
1025
}
188,371✔
1026

1027
/* code for registering buffers */
1028

1029
#include "util-hash-lookup3.h"
1030

1031
static HashListTable *g_buffer_type_hash = NULL;
1032
static int g_buffer_type_id = DETECT_SM_LIST_DYNAMIC_START;
1033
static int g_buffer_type_reg_closed = 0;
1034

1035
int DetectBufferTypeMaxId(void)
1036
{
×
1037
    return g_buffer_type_id;
×
1038
}
×
1039

1040
static void DetectBufferAddTransformData(DetectBufferType *map)
1041
{
103,528✔
1042
    for (int i = 0; i < map->transforms.cnt; i++) {
237,865✔
1043
        const TransformData *t = &map->transforms.transforms[i];
134,337✔
1044
        if (sigmatch_table[t->transform].TransformId) {
134,337✔
1045
            sigmatch_table[t->transform].TransformId(
62,892✔
1046
                    &map->xform_id[i].id_data, &map->xform_id[i].id_data_len, t->options);
62,892✔
1047
            SCLogDebug("transform identity data: [%p] \"%s\" [%d]", map->xform_id[i].id_data,
62,892!
1048
                    (char *)map->xform_id[i].id_data, map->xform_id[i].id_data_len);
62,892✔
1049
        }
62,892✔
1050
    }
134,337✔
1051
}
103,528✔
1052

1053
static uint32_t DetectBufferTypeHashNameFunc(HashListTable *ht, void *data, uint16_t datalen)
1054
{
407,778,682✔
1055
    const DetectBufferType *map = (DetectBufferType *)data;
407,778,682✔
1056
    uint32_t hash = hashlittle_safe(map->name, strlen(map->name), 0);
407,778,682✔
1057

1058
    // Add the transform data
1059
    // - Collect transform id and position
1060
    // - Collect identity data, if any
1061
    hash += hashlittle_safe((uint8_t *)&map->transforms.cnt, sizeof(map->transforms.cnt), 0);
407,778,682✔
1062
    for (int i = 0; i < map->transforms.cnt; i++) {
408,008,343✔
1063
        const TransformData *t = &map->transforms.transforms[i];
229,661✔
1064
        int tval = t->transform;
229,661✔
1065
        hash += hashlittle_safe((uint8_t *)&tval, sizeof(tval), 0);
229,661✔
1066
        if (map->xform_id[i].id_data) {
229,661✔
1067
            hash += hashlittle_safe(
62,892✔
1068
                    &map->xform_id[i].id_data_len, sizeof(map->xform_id[i].id_data_len), 0);
62,892✔
1069
            hash += hashlittle_safe(map->xform_id[i].id_data, map->xform_id[i].id_data_len, 0);
62,892✔
1070
        }
62,892✔
1071
    }
229,661✔
1072
    hash %= ht->array_size;
407,778,682✔
1073
    SCLogDebug("map->name %s, hash %d", map->name, hash);
407,778,682!
1074
    return hash;
407,778,682✔
1075
}
407,778,682✔
1076

1077
static uint32_t DetectBufferTypeHashIdFunc(HashListTable *ht, void *data, uint16_t datalen)
1078
{
23,167,582✔
1079
    const DetectBufferType *map = (DetectBufferType *)data;
23,167,582✔
1080
    uint32_t hash = map->id;
23,167,582✔
1081
    hash %= ht->array_size;
23,167,582✔
1082
    return hash;
23,167,582✔
1083
}
23,167,582✔
1084

1085
static char DetectBufferTypeCompareNameFunc(void *data1, uint16_t len1, void *data2, uint16_t len2)
1086
{
418,704,707✔
1087
    DetectBufferType *map1 = (DetectBufferType *)data1;
418,704,707✔
1088
    DetectBufferType *map2 = (DetectBufferType *)data2;
418,704,707✔
1089

1090
    char r = (strcmp(map1->name, map2->name) == 0);
418,704,707✔
1091

1092
    // Compare the transforms
1093
    // the transform supports identity, that data will also be added.
1094
    r &= map1->transforms.cnt == map2->transforms.cnt;
418,704,707✔
1095
    if (r && map1->transforms.cnt) {
418,704,707✔
1096
        for (int i = 0; i < map1->transforms.cnt; i++) {
77,081✔
1097
            if (map1->transforms.transforms[i].transform !=
39,173!
1098
                    map2->transforms.transforms[i].transform) {
39,173✔
1099
                r = 0;
×
1100
                break;
×
1101
            }
×
1102

1103
            SCLogDebug("%s: transform ids match; checking specialized data", map1->name);
39,173!
1104
            // Checks
1105
            // - Both NULL: --> ok, continue
1106
            // - One NULL: --> no match, break?
1107
            // - identity data lengths match: --> ok, continue
1108
            // - identity data matches: ok
1109

1110
            // Stop if only one is NULL
1111
            if ((map1->xform_id[i].id_data == NULL) ^ (map2->xform_id[i].id_data == NULL)) {
39,173!
1112
                SCLogDebug("identity data: only one is null");
103!
1113
                r = 0;
103✔
1114
                break;
103✔
1115
            } else if (map1->xform_id[i].id_data == NULL) { /* continue when both are null */
39,070!
1116
                SCLogDebug("identity data: both null");
39,070!
1117
                r = 1;
39,070✔
1118
                continue;
39,070✔
1119
            } else if (map1->xform_id[i].id_data_len != map2->xform_id[i].id_data_len) {
39,070!
1120
                // Stop when id data lengths aren't equal
1121
                SCLogDebug("id data: unequal lengths");
×
1122
                r = 0;
×
1123
                break;
×
1124
            }
×
1125

1126
            // stop if the identity data is different
1127
            r &= memcmp(map1->xform_id[i].id_data, map2->xform_id[i].id_data,
×
1128
                         map1->xform_id[i].id_data_len) == 0;
×
1129
            if (r == 0)
×
1130
                break;
×
1131
            SCLogDebug("identity data: data matches");
×
1132
        }
×
1133
    }
38,011✔
1134
    return r;
418,704,707✔
1135
}
418,704,707✔
1136

1137
static char DetectBufferTypeCompareIdFunc(void *data1, uint16_t len1, void *data2, uint16_t len2)
1138
{
7,508,401✔
1139
    DetectBufferType *map1 = (DetectBufferType *)data1;
7,508,401✔
1140
    DetectBufferType *map2 = (DetectBufferType *)data2;
7,508,401✔
1141
    return map1->id == map2->id;
7,508,401✔
1142
}
7,508,401✔
1143

1144
static void DetectBufferTypeFreeFunc(void *data)
1145
{
16,028,637✔
1146
    DetectBufferType *map = (DetectBufferType *)data;
16,028,637✔
1147

1148
    if (map == NULL) {
16,028,637!
1149
        return;
×
1150
    }
×
1151

1152
    /* Release transformation option memory, if any */
1153
    for (int i = 0; i < map->transforms.cnt; i++) {
16,123,916✔
1154
        if (map->transforms.transforms[i].options == NULL)
95,279✔
1155
            continue;
32,408✔
1156

1157
        if (sigmatch_table[map->transforms.transforms[i].transform].Free == NULL) {
62,871!
1158
            SCLogError("%s allocates transform option memory but has no free routine",
×
1159
                    sigmatch_table[map->transforms.transforms[i].transform].name);
×
1160
            continue;
×
1161
        }
×
1162
        sigmatch_table[map->transforms.transforms[i].transform].Free(NULL, map->transforms.transforms[i].options);
62,871✔
1163
    }
62,871✔
1164

1165
    SCFree(map);
16,028,637✔
1166
}
16,028,637✔
1167

1168
static int DetectBufferTypeInit(void)
1169
{
2,193✔
1170
    BUG_ON(g_buffer_type_hash);
2,193!
1171
    g_buffer_type_hash = HashListTableInit(256, DetectBufferTypeHashNameFunc,
2,193✔
1172
            DetectBufferTypeCompareNameFunc, DetectBufferTypeFreeFunc);
2,193✔
1173
    if (g_buffer_type_hash == NULL)
2,193!
1174
        return -1;
×
1175

1176
    return 0;
2,193✔
1177
}
2,193✔
1178
#if 0
1179
static void DetectBufferTypeFree(void)
1180
{
1181
    if (g_buffer_type_hash == NULL)
1182
        return;
1183

1184
    HashListTableFree(g_buffer_type_hash);
1185
    g_buffer_type_hash = NULL;
1186
}
1187
#endif
1188
static int DetectBufferTypeAdd(const char *string)
1189
{
899,092✔
1190
    BUG_ON(string == NULL || strlen(string) >= 64);
899,092!
1191

1192
    DetectBufferType *map = SCCalloc(1, sizeof(*map));
899,092✔
1193
    if (map == NULL)
899,092!
1194
        return -1;
×
1195

1196
    strlcpy(map->name, string, sizeof(map->name));
899,092✔
1197
    map->id = g_buffer_type_id++;
899,092✔
1198

1199
    BUG_ON(HashListTableAdd(g_buffer_type_hash, (void *)map, 0) != 0);
899,092!
1200
    SCLogDebug("buffer %s registered with id %d", map->name, map->id);
899,092!
1201
    return map->id;
899,092✔
1202
}
899,092✔
1203

1204
static DetectBufferType *DetectBufferTypeLookupByName(const char *string)
1205
{
390,651,051✔
1206
    DetectBufferType map;
390,651,051✔
1207
    memset(&map, 0, sizeof(map));
390,651,051✔
1208
    strlcpy(map.name, string, sizeof(map.name));
390,651,051✔
1209

1210
    DetectBufferType *res = HashListTableLookup(g_buffer_type_hash, &map, 0);
390,651,051✔
1211
    return res;
390,651,051✔
1212
}
390,651,051✔
1213

1214
int DetectBufferTypeRegister(const char *name)
1215
{
3,565,680✔
1216
    BUG_ON(g_buffer_type_reg_closed);
3,565,680!
1217
    if (g_buffer_type_hash == NULL)
3,565,680✔
1218
        DetectBufferTypeInit();
2,193✔
1219

1220
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
3,565,680✔
1221
    if (!exists) {
3,565,680✔
1222
        return DetectBufferTypeAdd(name);
899,092✔
1223
    } else {
2,666,588✔
1224
        return exists->id;
2,666,588✔
1225
    }
2,666,588✔
1226
}
3,565,680✔
1227

1228
void DetectBufferTypeSupportsMultiInstance(const char *name)
1229
{
109,650✔
1230
    BUG_ON(g_buffer_type_reg_closed);
109,650!
1231
    DetectBufferTypeRegister(name);
109,650✔
1232
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
109,650✔
1233
    BUG_ON(!exists);
109,650!
1234
    exists->multi_instance = true;
109,650✔
1235
    SCLogDebug("%p %s -- %d supports multi instance", exists, name, exists->id);
109,650!
1236
}
109,650✔
1237

1238
void DetectBufferTypeSupportsFrames(const char *name)
1239
{
×
1240
    BUG_ON(g_buffer_type_reg_closed);
×
1241
    DetectBufferTypeRegister(name);
×
1242
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
×
1243
    BUG_ON(!exists);
×
1244
    exists->frame = true;
×
1245
    SCLogDebug("%p %s -- %d supports frame inspection", exists, name, exists->id);
×
1246
}
×
1247

1248
void DetectBufferTypeSupportsPacket(const char *name)
1249
{
19,737✔
1250
    BUG_ON(g_buffer_type_reg_closed);
19,737!
1251
    DetectBufferTypeRegister(name);
19,737✔
1252
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
19,737✔
1253
    BUG_ON(!exists);
19,737!
1254
    exists->packet = true;
19,737✔
1255
    SCLogDebug("%p %s -- %d supports packet inspection", exists, name, exists->id);
19,737!
1256
}
19,737✔
1257

1258
void DetectBufferTypeSupportsMpm(const char *name)
1259
{
833,308✔
1260
    BUG_ON(g_buffer_type_reg_closed);
833,308!
1261
    DetectBufferTypeRegister(name);
833,308✔
1262
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
833,308✔
1263
    BUG_ON(!exists);
833,308!
1264
    exists->mpm = true;
833,308✔
1265
    SCLogDebug("%p %s -- %d supports mpm", exists, name, exists->id);
833,308!
1266
}
833,308✔
1267

1268
void DetectBufferTypeSupportsTransformations(const char *name)
1269
{
833,308✔
1270
    BUG_ON(g_buffer_type_reg_closed);
833,308!
1271
    DetectBufferTypeRegister(name);
833,308✔
1272
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
833,308✔
1273
    BUG_ON(!exists);
833,308!
1274
    exists->supports_transforms = true;
833,308✔
1275
    SCLogDebug("%p %s -- %d supports transformations", exists, name, exists->id);
833,308!
1276
}
833,308✔
1277

1278
int DetectBufferTypeGetByName(const char *name)
1279
{
384,885,920✔
1280
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
384,885,920✔
1281
    if (!exists) {
384,885,920✔
1282
        return -1;
201,484,876✔
1283
    }
201,484,876✔
1284
    return exists->id;
183,401,044✔
1285
}
384,885,920✔
1286

1287
static DetectBufferType *DetectEngineBufferTypeLookupByName(
1288
        const DetectEngineCtx *de_ctx, const char *string)
1289
{
72,199✔
1290
    DetectBufferType map;
72,199✔
1291
    memset(&map, 0, sizeof(map));
72,199✔
1292
    strlcpy(map.name, string, sizeof(map.name));
72,199✔
1293

1294
    DetectBufferType *res = HashListTableLookup(de_ctx->buffer_type_hash_name, &map, 0);
72,199✔
1295
    return res;
72,199✔
1296
}
72,199✔
1297

1298
const DetectBufferType *DetectEngineBufferTypeGetById(const DetectEngineCtx *de_ctx, const int id)
1299
{
7,114,754✔
1300
    DetectBufferType lookup;
7,114,754✔
1301
    memset(&lookup, 0, sizeof(lookup));
7,114,754✔
1302
    lookup.id = id;
7,114,754✔
1303
    const DetectBufferType *res =
7,114,754✔
1304
            HashListTableLookup(de_ctx->buffer_type_hash_id, (void *)&lookup, 0);
7,114,754✔
1305
    return res;
7,114,754✔
1306
}
7,114,754✔
1307

1308
const char *DetectEngineBufferTypeGetNameById(const DetectEngineCtx *de_ctx, const int id)
1309
{
31,089✔
1310
    const DetectBufferType *res = DetectEngineBufferTypeGetById(de_ctx, id);
31,089✔
1311
    return res ? res->name : NULL;
31,089✔
1312
}
31,089✔
1313

1314
static int DetectEngineBufferTypeAdd(DetectEngineCtx *de_ctx, const char *string)
1315
{
3,554✔
1316
    BUG_ON(string == NULL || strlen(string) >= 32);
3,554!
1317

1318
    DetectBufferType *map = SCCalloc(1, sizeof(*map));
3,554✔
1319
    if (map == NULL)
3,554!
1320
        return -1;
×
1321

1322
    strlcpy(map->name, string, sizeof(map->name));
3,554✔
1323
    map->id = de_ctx->buffer_type_id++;
3,554✔
1324

1325
    BUG_ON(HashListTableAdd(de_ctx->buffer_type_hash_name, (void *)map, 0) != 0);
3,554!
1326
    BUG_ON(HashListTableAdd(de_ctx->buffer_type_hash_id, (void *)map, 0) != 0);
3,554!
1327
    SCLogDebug("buffer %s registered with id %d", map->name, map->id);
3,554!
1328
    return map->id;
3,554✔
1329
}
3,554✔
1330

1331
int DetectEngineBufferTypeRegisterWithFrameEngines(DetectEngineCtx *de_ctx, const char *name,
1332
        const int direction, const AppProto alproto, const uint8_t frame_type)
1333
{
36,659✔
1334
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
36,659✔
1335
    if (exists) {
36,659✔
1336
        return exists->id;
33,105✔
1337
    }
33,105✔
1338

1339
    const int buffer_id = DetectEngineBufferTypeAdd(de_ctx, name);
3,554✔
1340
    if (buffer_id < 0) {
3,554!
1341
        return -1;
×
1342
    }
×
1343

1344
    /* TODO hack we need the map to get the name. Should we return the map at reg? */
1345
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, buffer_id);
3,554✔
1346
    BUG_ON(!map);
3,554!
1347

1348
    /* register MPM/inspect engines */
1349
    if (direction & SIG_FLAG_TOSERVER) {
3,554!
1350
        DetectEngineFrameMpmRegister(de_ctx, map->name, SIG_FLAG_TOSERVER, 2,
3,554✔
1351
                PrefilterGenericMpmFrameRegister, alproto, frame_type);
3,554✔
1352
        DetectEngineFrameInspectEngineRegister(de_ctx, map->name, SIG_FLAG_TOSERVER,
3,554✔
1353
                DetectEngineInspectFrameBufferGeneric, alproto, frame_type);
3,554✔
1354
    }
3,554✔
1355
    if (direction & SIG_FLAG_TOCLIENT) {
3,554!
1356
        DetectEngineFrameMpmRegister(de_ctx, map->name, SIG_FLAG_TOCLIENT, 2,
3,554✔
1357
                PrefilterGenericMpmFrameRegister, alproto, frame_type);
3,554✔
1358
        DetectEngineFrameInspectEngineRegister(de_ctx, map->name, SIG_FLAG_TOCLIENT,
3,554✔
1359
                DetectEngineInspectFrameBufferGeneric, alproto, frame_type);
3,554✔
1360
    }
3,554✔
1361

1362
    return buffer_id;
3,554✔
1363
}
3,554✔
1364

1365
int DetectEngineBufferTypeRegister(DetectEngineCtx *de_ctx, const char *name)
1366
{
14,216✔
1367
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
14,216✔
1368
    if (!exists) {
14,216!
1369
        return DetectEngineBufferTypeAdd(de_ctx, name);
×
1370
    } else {
14,216✔
1371
        return exists->id;
14,216✔
1372
    }
14,216✔
1373
}
14,216✔
1374

1375
void DetectBufferTypeSetDescriptionByName(const char *name, const char *desc)
1376
{
342,076✔
1377
    BUG_ON(desc == NULL || strlen(desc) >= 128);
342,076!
1378

1379
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
342,076✔
1380
    if (!exists) {
342,076✔
1381
        return;
4,386✔
1382
    }
4,386✔
1383
    strlcpy(exists->description, desc, sizeof(exists->description));
337,690✔
1384
}
337,690✔
1385

1386
const char *DetectEngineBufferTypeGetDescriptionById(const DetectEngineCtx *de_ctx, const int id)
1387
{
986✔
1388
    const DetectBufferType *exists = DetectEngineBufferTypeGetById(de_ctx, id);
986✔
1389
    if (!exists) {
986!
1390
        return NULL;
×
1391
    }
×
1392
    return exists->description;
986✔
1393
}
986✔
1394

1395
void DetectEngineBufferTypeSupportsFrames(DetectEngineCtx *de_ctx, const char *name)
1396
{
7,108✔
1397
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
7,108✔
1398
    BUG_ON(!exists);
7,108!
1399
    exists->frame = true;
7,108✔
1400
    SCLogDebug("%p %s -- %d supports frame inspection", exists, name, exists->id);
7,108!
1401
}
7,108✔
1402

1403
void DetectEngineBufferTypeSupportsPacket(DetectEngineCtx *de_ctx, const char *name)
1404
{
×
1405
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
×
1406
    BUG_ON(!exists);
×
1407
    exists->packet = true;
×
1408
    SCLogDebug("%p %s -- %d supports packet inspection", exists, name, exists->id);
×
1409
}
×
1410

1411
void DetectEngineBufferTypeSupportsMpm(DetectEngineCtx *de_ctx, const char *name)
1412
{
7,108✔
1413
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
7,108✔
1414
    BUG_ON(!exists);
7,108!
1415
    exists->mpm = true;
7,108✔
1416
    SCLogDebug("%p %s -- %d supports mpm", exists, name, exists->id);
7,108!
1417
}
7,108✔
1418

1419
void DetectEngineBufferTypeSupportsTransformations(DetectEngineCtx *de_ctx, const char *name)
1420
{
7,108✔
1421
    DetectBufferType *exists = DetectEngineBufferTypeLookupByName(de_ctx, name);
7,108✔
1422
    BUG_ON(!exists);
7,108!
1423
    exists->supports_transforms = true;
7,108✔
1424
    SCLogDebug("%p %s -- %d supports transformations", exists, name, exists->id);
7,108!
1425
}
7,108✔
1426

1427
bool DetectEngineBufferTypeSupportsMultiInstanceGetById(const DetectEngineCtx *de_ctx, const int id)
1428
{
654,901✔
1429
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
654,901✔
1430
    if (map == NULL)
654,901!
1431
        return false;
×
1432
    SCLogDebug("map %p id %d multi_instance? %s", map, id, BOOL2STR(map->multi_instance));
654,901!
1433
    return map->multi_instance;
654,901✔
1434
}
654,901✔
1435

1436
bool DetectEngineBufferTypeSupportsPacketGetById(const DetectEngineCtx *de_ctx, const int id)
1437
{
683,602✔
1438
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
683,602✔
1439
    if (map == NULL)
683,602!
1440
        return false;
×
1441
    SCLogDebug("map %p id %d packet? %d", map, id, map->packet);
683,602!
1442
    return map->packet;
683,602✔
1443
}
683,602✔
1444

1445
bool DetectEngineBufferTypeSupportsMpmGetById(const DetectEngineCtx *de_ctx, const int id)
1446
{
1,249,721✔
1447
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
1,249,721✔
1448
    if (map == NULL)
1,249,721✔
1449
        return false;
460,474✔
1450
    SCLogDebug("map %p id %d mpm? %d", map, id, map->mpm);
789,247!
1451
    return map->mpm;
789,247✔
1452
}
1,249,721✔
1453

1454
bool DetectEngineBufferTypeSupportsFramesGetById(const DetectEngineCtx *de_ctx, const int id)
1455
{
673,549✔
1456
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
673,549✔
1457
    if (map == NULL)
673,549!
1458
        return false;
×
1459
    SCLogDebug("map %p id %d frame? %d", map, id, map->frame);
673,549!
1460
    return map->frame;
673,549✔
1461
}
673,549✔
1462

1463
void DetectBufferTypeRegisterSetupCallback(const char *name,
1464
        void (*SetupCallback)(const DetectEngineCtx *, Signature *, const DetectBufferType *))
1465
{
26,316✔
1466
    BUG_ON(g_buffer_type_reg_closed);
26,316!
1467
    DetectBufferTypeRegister(name);
26,316✔
1468
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
26,316✔
1469
    BUG_ON(!exists);
26,316!
1470
    exists->SetupCallback = SetupCallback;
26,316✔
1471
}
26,316✔
1472

1473
void DetectEngineBufferRunSetupCallback(const DetectEngineCtx *de_ctx, const int id, Signature *s)
1474
{
1,565,723✔
1475
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
1,565,723✔
1476
    if (map && map->SetupCallback) {
1,565,723✔
1477
        map->SetupCallback(de_ctx, s, map);
194,290✔
1478
    }
194,290✔
1479
}
1,565,723✔
1480

1481
void DetectBufferTypeRegisterValidateCallback(
1482
        const char *name, bool (*ValidateCallback)(const Signature *, const char **sigerror,
1483
                                  const DetectBufferType *))
1484
{
35,056✔
1485
    BUG_ON(g_buffer_type_reg_closed);
35,056!
1486
    DetectBufferTypeRegister(name);
35,056✔
1487
    DetectBufferType *exists = DetectBufferTypeLookupByName(name);
35,056✔
1488
    BUG_ON(!exists);
35,056!
1489
    exists->ValidateCallback = ValidateCallback;
35,056✔
1490
}
35,056✔
1491

1492
bool DetectEngineBufferRunValidateCallback(
1493
        const DetectEngineCtx *de_ctx, const int id, const Signature *s, const char **sigerror)
1494
{
709,155✔
1495
    const DetectBufferType *map = DetectEngineBufferTypeGetById(de_ctx, id);
709,155✔
1496
    // only run validation if the buffer is not transformed
1497
    if (map && map->ValidateCallback && map->transforms.cnt == 0) {
709,155!
1498
        return map->ValidateCallback(s, sigerror, map);
213,622✔
1499
    }
213,622✔
1500
    return true;
495,533✔
1501
}
709,155✔
1502

1503
bool DetectBufferIsPresent(const Signature *s, const uint32_t buf_id)
1504
{
3✔
1505
    for (uint32_t i = 0; i < s->init_data->buffer_index; i++) {
3!
1506
        if (buf_id == s->init_data->buffers[i].id) {
×
1507
            return true;
×
1508
        }
×
1509
    }
×
1510
    return false;
3✔
1511
}
3✔
1512

1513
/** \brief Check content byte array compatibility with transforms
1514
 *
1515
 *  The "content" array is presented to the transforms so that each
1516
 *  transform may validate that it's compatible with the transform.
1517
 *
1518
 *  When a transform indicates the byte array is incompatible, none of the
1519
 *  subsequent transforms, if any, are invoked. This means the first validation
1520
 *  failure terminates the loop.
1521
 *
1522
 *  \param de_ctx Detection engine context.
1523
 *  \param sm_list The SM list id.
1524
 *  \param content The byte array being validated
1525
 *  \param namestr returns the name of the transform that is incompatible with
1526
 *  content.
1527
 *
1528
 *  \retval true (false) If any of the transforms indicate the byte array is
1529
 *  (is not) compatible.
1530
 **/
1531
bool DetectEngineBufferTypeValidateTransform(DetectEngineCtx *de_ctx, int sm_list,
1532
        const uint8_t *content, uint16_t content_len, const char **namestr)
1533
{
453,190✔
1534
    const DetectBufferType *dbt = DetectEngineBufferTypeGetById(de_ctx, sm_list);
453,190✔
1535
    BUG_ON(dbt == NULL);
453,190!
1536

1537
    for (int i = 0; i < dbt->transforms.cnt; i++) {
580,858✔
1538
        const TransformData *t = &dbt->transforms.transforms[i];
133,168✔
1539
        if (!sigmatch_table[t->transform].TransformValidate)
133,168✔
1540
            continue;
95,282✔
1541

1542
        if (sigmatch_table[t->transform].TransformValidate(content, content_len, t->options)) {
37,886✔
1543
            continue;
32,386✔
1544
        }
32,386✔
1545

1546
        if (namestr) {
5,500!
1547
            *namestr = sigmatch_table[t->transform].name;
5,500✔
1548
        }
5,500✔
1549

1550
        return false;
5,500✔
1551
    }
37,886✔
1552

1553
    return true;
447,690✔
1554
}
453,190✔
1555

1556
static void DetectBufferTypeSetupDetectEngine(DetectEngineCtx *de_ctx)
1557
{
38,898✔
1558
    const int size = g_buffer_type_id;
38,898✔
1559
    BUG_ON(!(size > 0));
38,898!
1560

1561
    de_ctx->buffer_type_hash_name = HashListTableInit(256, DetectBufferTypeHashNameFunc,
38,898✔
1562
            DetectBufferTypeCompareNameFunc, DetectBufferTypeFreeFunc);
38,898✔
1563
    BUG_ON(de_ctx->buffer_type_hash_name == NULL);
38,898!
1564
    de_ctx->buffer_type_hash_id =
38,898✔
1565
            HashListTableInit(256, DetectBufferTypeHashIdFunc, DetectBufferTypeCompareIdFunc,
38,898✔
1566
                    NULL); // entries owned by buffer_type_hash_name
38,898✔
1567
    BUG_ON(de_ctx->buffer_type_hash_id == NULL);
38,898!
1568
    de_ctx->buffer_type_id = g_buffer_type_id;
38,898✔
1569

1570
    SCLogDebug("DETECT_SM_LIST_DYNAMIC_START %u", DETECT_SM_LIST_DYNAMIC_START);
38,898!
1571
    HashListTableBucket *b = HashListTableGetListHead(g_buffer_type_hash);
38,898✔
1572
    while (b) {
16,022,561✔
1573
        DetectBufferType *map = HashListTableGetListData(b);
15,983,660✔
1574

1575
        DetectBufferType *copy = SCCalloc(1, sizeof(*copy));
15,983,660✔
1576
        BUG_ON(!copy);
15,983,660✔
1577
        memcpy(copy, map, sizeof(*copy));
15,983,668✔
1578
        int r = HashListTableAdd(de_ctx->buffer_type_hash_name, (void *)copy, 0);
15,983,668✔
1579
        BUG_ON(r != 0);
15,983,668✔
1580
        r = HashListTableAdd(de_ctx->buffer_type_hash_id, (void *)copy, 0);
15,983,664✔
1581
        BUG_ON(r != 0);
15,983,664!
1582

1583
        SCLogDebug("name %s id %d mpm %s packet %s -- %s. "
15,983,663!
1584
                   "Callbacks: Setup %p Validate %p",
15,983,663✔
1585
                map->name, map->id, map->mpm ? "true" : "false", map->packet ? "true" : "false",
15,983,663✔
1586
                map->description, map->SetupCallback, map->ValidateCallback);
15,983,663✔
1587
        b = HashListTableGetListNext(b);
15,983,663✔
1588
    }
15,983,663✔
1589

1590
    PrefilterInit(de_ctx);
38,901✔
1591
    DetectMpmInitializeAppMpms(de_ctx);
38,901✔
1592
    DetectAppLayerInspectEngineCopyListToDetectCtx(de_ctx);
38,901✔
1593
    DetectMpmInitializeFrameMpms(de_ctx);
38,901✔
1594
    DetectFrameInspectEngineCopyListToDetectCtx(de_ctx);
38,901✔
1595
    DetectMpmInitializePktMpms(de_ctx);
38,901✔
1596
    DetectPktInspectEngineCopyListToDetectCtx(de_ctx);
38,901✔
1597
}
38,901✔
1598

1599
static void DetectBufferTypeFreeDetectEngine(DetectEngineCtx *de_ctx)
1600
{
38,842✔
1601
    if (de_ctx) {
38,842!
1602
        if (de_ctx->buffer_type_hash_name)
38,842✔
1603
            HashListTableFree(de_ctx->buffer_type_hash_name);
38,839✔
1604
        if (de_ctx->buffer_type_hash_id)
38,842✔
1605
            HashListTableFree(de_ctx->buffer_type_hash_id);
38,839✔
1606

1607
        DetectEngineAppInspectionEngine *ilist = de_ctx->app_inspect_engines;
38,842✔
1608
        while (ilist) {
27,286,016✔
1609
            DetectEngineAppInspectionEngine *next = ilist->next;
27,247,174✔
1610
            SCFree(ilist);
27,247,174✔
1611
            ilist = next;
27,247,174✔
1612
        }
27,247,174✔
1613
        DetectBufferMpmRegistry *mlist = de_ctx->app_mpms_list;
38,842✔
1614
        while (mlist) {
15,051,731✔
1615
            DetectBufferMpmRegistry *next = mlist->next;
15,012,889✔
1616
            SCFree(mlist);
15,012,889✔
1617
            mlist = next;
15,012,889✔
1618
        }
15,012,889✔
1619
        DetectEnginePktInspectionEngine *plist = de_ctx->pkt_inspect_engines;
38,842✔
1620
        while (plist) {
389,910✔
1621
            DetectEnginePktInspectionEngine *next = plist->next;
351,068✔
1622
            SCFree(plist);
351,068✔
1623
            plist = next;
351,068✔
1624
        }
351,068✔
1625
        DetectBufferMpmRegistry *pmlist = de_ctx->pkt_mpms_list;
38,842✔
1626
        while (pmlist) {
389,910✔
1627
            DetectBufferMpmRegistry *next = pmlist->next;
351,068✔
1628
            SCFree(pmlist);
351,068✔
1629
            pmlist = next;
351,068✔
1630
        }
351,068✔
1631
        DetectEngineFrameInspectionEngine *framelist = de_ctx->frame_inspect_engines;
38,842✔
1632
        while (framelist) {
46,720✔
1633
            DetectEngineFrameInspectionEngine *next = framelist->next;
7,878✔
1634
            SCFree(framelist);
7,878✔
1635
            framelist = next;
7,878✔
1636
        }
7,878✔
1637
        DetectBufferMpmRegistry *framemlist = de_ctx->frame_mpms_list;
38,842✔
1638
        while (framemlist) {
46,720✔
1639
            DetectBufferMpmRegistry *next = framemlist->next;
7,878✔
1640
            SCFree(framemlist);
7,878✔
1641
            framemlist = next;
7,878✔
1642
        }
7,878✔
1643
        PrefilterDeinit(de_ctx);
38,842✔
1644
    }
38,842✔
1645
}
38,842✔
1646

1647
void DetectBufferTypeCloseRegistration(void)
1648
{
2,193✔
1649
    BUG_ON(g_buffer_type_hash == NULL);
2,193!
1650

1651
    g_buffer_type_reg_closed = 1;
2,193✔
1652
}
2,193✔
1653

1654
int DetectEngineBufferTypeGetByIdTransforms(
1655
        DetectEngineCtx *de_ctx, const int id, TransformData *transforms, int transform_cnt)
1656
{
103,528✔
1657
    const DetectBufferType *base_map = DetectEngineBufferTypeGetById(de_ctx, id);
103,528✔
1658
    if (!base_map) {
103,528!
1659
        return -1;
×
1660
    }
×
1661
    if (!base_map->supports_transforms) {
103,528!
1662
        SCLogError("buffer '%s' does not support transformations", base_map->name);
×
1663
        return -1;
×
1664
    }
×
1665

1666
    SCLogDebug("base_map %s", base_map->name);
103,528!
1667

1668
    DetectEngineTransforms t;
103,528✔
1669
    memset(&t, 0, sizeof(t));
103,528✔
1670
    for (int i = 0; i < transform_cnt; i++) {
237,865✔
1671
        t.transforms[i] = transforms[i];
134,337✔
1672
    }
134,337✔
1673
    t.cnt = transform_cnt;
103,528✔
1674

1675
    DetectBufferType lookup_map;
103,528✔
1676
    memset(&lookup_map, 0, sizeof(lookup_map));
103,528✔
1677
    strlcpy(lookup_map.name, base_map->name, sizeof(lookup_map.name));
103,528✔
1678
    lookup_map.transforms = t;
103,528✔
1679

1680
    /* Add transform identity data from transforms */
1681
    if (t.cnt) {
103,528!
1682
        DetectBufferAddTransformData(&lookup_map);
103,528✔
1683
    }
103,528✔
1684
    DetectBufferType *res = HashListTableLookup(de_ctx->buffer_type_hash_name, &lookup_map, 0);
103,528✔
1685

1686
    SCLogDebug("res %p", res);
103,528!
1687
    if (res != NULL) {
103,528✔
1688
        return res->id;
37,908✔
1689
    }
37,908✔
1690

1691
    DetectBufferType *map = SCCalloc(1, sizeof(*map));
65,620✔
1692
    if (map == NULL)
65,620!
1693
        return -1;
×
1694

1695
    strlcpy(map->name, base_map->name, sizeof(map->name));
65,620✔
1696
    map->id = de_ctx->buffer_type_id++;
65,620✔
1697
    map->parent_id = base_map->id;
65,620✔
1698
    map->transforms = t;
65,620✔
1699
    map->mpm = base_map->mpm;
65,620✔
1700
    map->packet = base_map->packet;
65,620✔
1701
    map->frame = base_map->frame;
65,620✔
1702
    map->SetupCallback = base_map->SetupCallback;
65,620✔
1703
    map->ValidateCallback = base_map->ValidateCallback;
65,620✔
1704
    if (map->frame) {
65,620✔
1705
        DetectFrameMpmRegisterByParentId(de_ctx, map->id, map->parent_id, &map->transforms);
387✔
1706
    } else if (map->packet) {
65,233✔
1707
        DetectPktMpmRegisterByParentId(de_ctx,
1,520✔
1708
                map->id, map->parent_id, &map->transforms);
1,520✔
1709
    } else {
63,713✔
1710
        DetectAppLayerMpmRegisterByParentId(de_ctx,
63,713✔
1711
                map->id, map->parent_id, &map->transforms);
63,713✔
1712
    }
63,713✔
1713

1714
    BUG_ON(HashListTableAdd(de_ctx->buffer_type_hash_name, (void *)map, 0) != 0);
65,620!
1715
    BUG_ON(HashListTableAdd(de_ctx->buffer_type_hash_id, (void *)map, 0) != 0);
65,620!
1716
    SCLogDebug("buffer %s registered with id %d, parent %d", map->name, map->id, map->parent_id);
65,620!
1717

1718
    if (map->frame) {
65,620✔
1719
        DetectFrameInspectEngineCopy(de_ctx, map->parent_id, map->id, &map->transforms);
387✔
1720
    } else if (map->packet) {
65,233✔
1721
        DetectPktInspectEngineCopy(de_ctx, map->parent_id, map->id, &map->transforms);
1,520✔
1722
    } else {
63,713✔
1723
        DetectAppLayerInspectEngineCopy(de_ctx, map->parent_id, map->id, &map->transforms);
63,713✔
1724
    }
63,713✔
1725
    return map->id;
65,620✔
1726
}
65,620✔
1727

1728
/* returns false if no match, true if match */
1729
static int DetectEngineInspectRulePacketMatches(
1730
    DetectEngineThreadCtx *det_ctx,
1731
    const DetectEnginePktInspectionEngine *engine,
1732
    const Signature *s,
1733
    Packet *p, uint8_t *_alert_flags)
1734
{
1,423,353✔
1735
    SCEnter();
1,423,353✔
1736

1737
    /* run the packet match functions */
1738
    KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_MATCH);
1,423,353✔
1739
    const SigMatchData *smd = s->sm_arrays[DETECT_SM_LIST_MATCH];
1,423,353✔
1740

1741
    SCLogDebug("running match functions, sm %p", smd);
1,423,353!
1742
    while (1) {
1,442,212!
1743
        KEYWORD_PROFILING_START;
1,442,207✔
1744
        if (sigmatch_table[smd->type].Match(det_ctx, p, s, smd->ctx) <= 0) {
1,442,207✔
1745
            KEYWORD_PROFILING_END(det_ctx, smd->type, 0);
305,418✔
1746
            SCLogDebug("no match");
305,418!
1747
            return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
305,418✔
1748
        }
305,418✔
1749
        KEYWORD_PROFILING_END(det_ctx, smd->type, 1);
1,136,789✔
1750
        if (smd->is_last) {
1,136,789✔
1751
            SCLogDebug("match and is_last");
1,117,972!
1752
            break;
1,117,972✔
1753
        }
1,117,972✔
1754
        smd++;
18,817✔
1755
    }
18,817✔
1756
    return DETECT_ENGINE_INSPECT_SIG_MATCH;
1,117,935✔
1757
}
1,423,353✔
1758

1759
static int DetectEngineInspectRulePayloadMatches(
1760
     DetectEngineThreadCtx *det_ctx,
1761
     const DetectEnginePktInspectionEngine *engine,
1762
     const Signature *s, Packet *p, uint8_t *alert_flags)
1763
{
62,549✔
1764
    SCEnter();
62,549✔
1765

1766
    DetectEngineCtx *de_ctx = det_ctx->de_ctx;
62,549✔
1767

1768
    KEYWORD_PROFILING_SET_LIST(det_ctx, DETECT_SM_LIST_PMATCH);
62,549✔
1769
    /* if we have stream msgs, inspect against those first,
1770
     * but not for a "dsize" signature */
1771
    if (s->flags & SIG_FLAG_REQUIRE_STREAM) {
62,549✔
1772
        int pmatch = 0;
36,416✔
1773
        if (p->flags & PKT_DETECT_HAS_STREAMDATA) {
36,416✔
1774
            pmatch = DetectEngineInspectStreamPayload(de_ctx, det_ctx, s, p->flow, p);
9,934✔
1775
            if (pmatch) {
9,934✔
1776
                *alert_flags |= PACKET_ALERT_FLAG_STREAM_MATCH;
1,201✔
1777
            }
1,201✔
1778
        }
9,934✔
1779
        /* no match? then inspect packet payload */
1780
        if (pmatch == 0) {
36,416✔
1781
            SCLogDebug("no match in stream, fall back to packet payload");
35,213!
1782

1783
            /* skip if we don't have to inspect the packet and segment was
1784
             * added to stream */
1785
            if (!(s->flags & SIG_FLAG_REQUIRE_PACKET) && (p->flags & PKT_STREAM_ADD)) {
35,213✔
1786
                return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
22,206✔
1787
            }
22,206✔
1788
            if (s->flags & SIG_FLAG_REQUIRE_STREAM_ONLY) {
13,007✔
1789
                SCLogDebug("SIG_FLAG_REQUIRE_STREAM_ONLY, so no match");
4!
1790
                return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
4✔
1791
            }
4✔
1792
            if (DetectEngineInspectPacketPayload(de_ctx, det_ctx, s, p->flow, p) != 1) {
13,003✔
1793
                return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
10,953✔
1794
            }
10,953✔
1795
        }
13,003✔
1796
    } else {
44,165✔
1797
        if (DetectEngineInspectPacketPayload(de_ctx, det_ctx, s, p->flow, p) != 1) {
26,133✔
1798
            return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
21,312✔
1799
        }
21,312✔
1800
    }
26,133✔
1801
    return DETECT_ENGINE_INSPECT_SIG_MATCH;
8,074✔
1802
}
62,549✔
1803

1804
bool DetectEnginePktInspectionRun(ThreadVars *tv,
1805
        DetectEngineThreadCtx *det_ctx, const Signature *s,
1806
        Flow *f, Packet *p,
1807
        uint8_t *alert_flags)
1808
{
2,319,765✔
1809
    SCEnter();
2,319,765✔
1810

1811
    for (DetectEnginePktInspectionEngine *e = s->pkt_inspect; e != NULL; e = e->next) {
3,449,874✔
1812
        if (e->v1.Callback(det_ctx, e, s, p, alert_flags) != DETECT_ENGINE_INSPECT_SIG_MATCH) {
1,493,716✔
1813
            SCLogDebug("sid %u: e %p Callback returned no match", s->id, e);
363,607!
1814
            return false;
363,607✔
1815
        }
363,607✔
1816
        SCLogDebug("sid %u: e %p Callback returned true", s->id, e);
1,130,109!
1817
    }
1,130,109✔
1818

1819
    SCLogDebug("sid %u: returning true", s->id);
1,956,158!
1820
    return true;
1,956,158✔
1821
}
2,319,765✔
1822

1823
/**
1824
 * \param data pointer to SigMatchData. Allowed to be NULL.
1825
 */
1826
static int DetectEnginePktInspectionAppend(Signature *s, InspectionBufferPktInspectFunc Callback,
1827
        SigMatchData *data, const int list_id)
1828
{
129,830✔
1829
    DetectEnginePktInspectionEngine *e = SCCalloc(1, sizeof(*e));
129,830✔
1830
    if (e == NULL)
129,830!
1831
        return -1;
×
1832

1833
    e->mpm = s->init_data->mpm_sm_list == list_id;
129,830✔
1834
    DEBUG_VALIDATE_BUG_ON(list_id < 0 || list_id > UINT16_MAX);
129,830✔
1835
    e->sm_list = (uint16_t)list_id;
129,830✔
1836
    e->sm_list_base = (uint16_t)list_id;
129,830✔
1837
    e->v1.Callback = Callback;
129,830✔
1838
    e->smd = data;
129,830✔
1839

1840
    if (s->pkt_inspect == NULL) {
129,830✔
1841
        s->pkt_inspect = e;
117,770✔
1842
    } else {
117,779✔
1843
        DetectEnginePktInspectionEngine *a = s->pkt_inspect;
12,060✔
1844
        while (a->next != NULL) {
12,200!
1845
            a = a->next;
140✔
1846
        }
140✔
1847
        a->next = e;
12,060✔
1848
    }
12,060✔
1849
    return 0;
129,830✔
1850
}
129,830✔
1851

1852
int DetectEnginePktInspectionSetup(Signature *s)
1853
{
266,105✔
1854
    /* only handle PMATCH here if we're not an app inspect rule */
1855
    if (s->sm_arrays[DETECT_SM_LIST_PMATCH] && (s->init_data->init_flags & SIG_FLAG_INIT_STATE_MATCH) == 0) {
266,105!
1856
        if (DetectEnginePktInspectionAppend(
25,521!
1857
                    s, DetectEngineInspectRulePayloadMatches, NULL, DETECT_SM_LIST_PMATCH) < 0)
25,521✔
1858
            return -1;
×
1859
        SCLogDebug("sid %u: DetectEngineInspectRulePayloadMatches appended", s->id);
25,521!
1860
    }
25,521✔
1861

1862
    if (s->sm_arrays[DETECT_SM_LIST_MATCH]) {
266,105✔
1863
        if (DetectEnginePktInspectionAppend(
104,309!
1864
                    s, DetectEngineInspectRulePacketMatches, NULL, DETECT_SM_LIST_MATCH) < 0)
104,309✔
1865
            return -1;
×
1866
        SCLogDebug("sid %u: DetectEngineInspectRulePacketMatches appended", s->id);
104,309!
1867
    }
104,309✔
1868

1869
    return 0;
266,105✔
1870
}
266,105✔
1871

1872
/* code to control the main thread to do a reload */
1873

1874
enum DetectEngineSyncState {
1875
    IDLE,   /**< ready to start a reload */
1876
    RELOAD, /**< command main thread to do the reload */
1877
};
1878

1879

1880
typedef struct DetectEngineSyncer_ {
1881
    SCMutex m;
1882
    enum DetectEngineSyncState state;
1883
} DetectEngineSyncer;
1884

1885
static DetectEngineSyncer detect_sync = { SCMUTEX_INITIALIZER, IDLE };
1886

1887
/* tell main to start reloading */
1888
int DetectEngineReloadStart(void)
1889
{
8✔
1890
    int r = 0;
8✔
1891
    SCMutexLock(&detect_sync.m);
8✔
1892
    if (detect_sync.state == IDLE) {
8!
1893
        detect_sync.state = RELOAD;
8✔
1894
    } else {
8✔
1895
        r = -1;
×
1896
    }
×
1897
    SCMutexUnlock(&detect_sync.m);
8✔
1898
    return r;
8✔
1899
}
8✔
1900

1901
/* main thread checks this to see if it should start */
1902
int DetectEngineReloadIsStart(void)
1903
{
94,541✔
1904
    int r = 0;
94,541✔
1905
    SCMutexLock(&detect_sync.m);
94,541✔
1906
    if (detect_sync.state == RELOAD) {
94,541!
1907
        r = 1;
8✔
1908
    }
8✔
1909
    SCMutexUnlock(&detect_sync.m);
94,541✔
1910
    return r;
94,541✔
1911
}
94,541✔
1912

1913
/* main thread sets done when it's done */
1914
void DetectEngineReloadSetIdle(void)
1915
{
8✔
1916
    SCMutexLock(&detect_sync.m);
8✔
1917
    detect_sync.state = IDLE;
8✔
1918
    SCMutexUnlock(&detect_sync.m);
8✔
1919
}
8✔
1920

1921
/* caller loops this until it returns 1 */
1922
int DetectEngineReloadIsIdle(void)
1923
{
5,256✔
1924
    int r = 0;
5,256✔
1925
    SCMutexLock(&detect_sync.m);
5,256✔
1926
    if (detect_sync.state == IDLE) {
5,256!
1927
        r = 1;
8✔
1928
    }
8✔
1929
    SCMutexUnlock(&detect_sync.m);
5,256✔
1930
    return r;
5,256✔
1931
}
5,256✔
1932

1933
/** \brief Do the content inspection & validation for a signature
1934
 *
1935
 *  \param de_ctx Detection engine context
1936
 *  \param det_ctx Detection engine thread context
1937
 *  \param s Signature to inspect
1938
 *  \param sm SigMatch to inspect
1939
 *  \param f Flow
1940
 *  \param flags app layer flags
1941
 *  \param state App layer state
1942
 *
1943
 *  \retval 0 no match
1944
 *  \retval 1 match
1945
 */
1946
uint8_t DetectEngineInspectGenericList(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
1947
        const struct DetectEngineAppInspectionEngine_ *engine, const Signature *s, Flow *f,
1948
        uint8_t flags, void *alstate, void *txv, uint64_t tx_id)
1949
{
97,923✔
1950
    SigMatchData *smd = engine->smd;
97,923✔
1951
    SCLogDebug("running match functions, sm %p", smd);
97,923!
1952
    if (smd != NULL) {
97,923✔
1953
        while (1) {
98,733!
1954
            int match = 0;
98,733✔
1955
            KEYWORD_PROFILING_START;
98,733✔
1956
            match = sigmatch_table[smd->type].
98,733✔
1957
                AppLayerTxMatch(det_ctx, f, flags, alstate, txv, s, smd->ctx);
98,733✔
1958
            KEYWORD_PROFILING_END(det_ctx, smd->type, (match == 1));
98,733✔
1959
            if (match == 0)
98,733✔
1960
                return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
72,861✔
1961
            if (match == 2) {
25,872!
1962
                return DETECT_ENGINE_INSPECT_SIG_CANT_MATCH;
×
1963
            }
×
1964

1965
            if (smd->is_last)
25,872✔
1966
                break;
25,062✔
1967
            smd++;
810✔
1968
        }
810✔
1969
    }
97,922✔
1970

1971
    return DETECT_ENGINE_INSPECT_SIG_MATCH;
25,062✔
1972
}
97,923✔
1973

1974
/**
1975
 * \brief Do the content inspection & validation for a signature
1976
 *
1977
 * \param de_ctx Detection engine context
1978
 * \param det_ctx Detection engine thread context
1979
 * \param s Signature to inspect
1980
 * \param f Flow
1981
 * \param flags app layer flags
1982
 * \param state App layer state
1983
 *
1984
 * \retval 0 no match.
1985
 * \retval 1 match.
1986
 * \retval 2 Sig can't match.
1987
 */
1988
uint8_t DetectEngineInspectBufferSingle(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
1989
        const DetectEngineAppInspectionEngine *engine, const Signature *s, Flow *f, uint8_t flags,
1990
        void *alstate, void *txv, uint64_t tx_id)
1991
{
1,693✔
1992
    const int list_id = engine->sm_list;
1,693✔
1993
    SCLogDebug("running inspect on %d", list_id);
1,693!
1994

1995
    const bool eof =
1,693✔
1996
            (AppLayerParserGetStateProgress(f->proto, f->alproto, txv, flags) > engine->progress);
1,693✔
1997

1998
    SCLogDebug("list %d mpm? %s transforms %p", engine->sm_list, engine->mpm ? "true" : "false",
1,693!
1999
            engine->v2.transforms);
1,693✔
2000

2001
    /* if prefilter didn't already run, we need to consider transformations */
2002
    const DetectEngineTransforms *transforms = NULL;
1,693✔
2003
    if (!engine->mpm) {
1,693✔
2004
        transforms = engine->v2.transforms;
201✔
2005
    }
201✔
2006

2007
    const InspectionBuffer *buffer = DetectGetSingleData(
1,693✔
2008
            det_ctx, transforms, f, flags, txv, list_id, engine->v2.GetDataSingle);
1,693✔
2009
    if (unlikely(buffer == NULL)) {
1,693✔
2010
        if (eof && engine->match_on_null) {
100!
2011
            return DETECT_ENGINE_INSPECT_SIG_MATCH;
×
2012
        }
×
2013
        return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH : DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
100!
2014
    }
100✔
2015

2016
    const uint32_t data_len = buffer->inspect_len;
1,593✔
2017
    const uint8_t *data = buffer->inspect;
1,593✔
2018
    const uint64_t offset = buffer->inspect_offset;
1,593✔
2019

2020
    uint8_t ci_flags = eof ? DETECT_CI_FLAGS_END : 0;
1,593✔
2021
    ci_flags |= (offset == 0 ? DETECT_CI_FLAGS_START : 0);
1,593!
2022
    ci_flags |= buffer->flags;
1,593✔
2023

2024
    /* Inspect all the uricontents fetched on each
2025
     * transaction at the app layer */
2026
    const bool match = DetectEngineContentInspection(de_ctx, det_ctx, s, engine->smd, NULL, f, data,
1,593✔
2027
            data_len, offset, ci_flags, DETECT_ENGINE_CONTENT_INSPECTION_MODE_STATE);
1,593✔
2028
    if (match) {
1,593✔
2029
        return DETECT_ENGINE_INSPECT_SIG_MATCH;
1,585✔
2030
    } else {
1,585✔
2031
        return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH : DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
8!
2032
    }
8✔
2033
}
1,593✔
2034

2035
/**
2036
 * \brief Do the content inspection & validation for a signature
2037
 *
2038
 * \param de_ctx Detection engine context
2039
 * \param det_ctx Detection engine thread context
2040
 * \param s Signature to inspect
2041
 * \param f Flow
2042
 * \param flags app layer flags
2043
 * \param state App layer state
2044
 *
2045
 * \retval 0 no match.
2046
 * \retval 1 match.
2047
 * \retval 2 Sig can't match.
2048
 */
2049
uint8_t DetectEngineInspectBufferGeneric(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx,
2050
        const DetectEngineAppInspectionEngine *engine, const Signature *s, Flow *f, uint8_t flags,
2051
        void *alstate, void *txv, uint64_t tx_id)
2052
{
23,374✔
2053
    const int list_id = engine->sm_list;
23,374✔
2054
    SCLogDebug("running inspect on %d", list_id);
23,374!
2055

2056
    const bool eof = (AppLayerParserGetStateProgress(f->proto, f->alproto, txv, flags) > engine->progress);
23,374✔
2057

2058
    SCLogDebug("list %d mpm? %s transforms %p",
23,374!
2059
            engine->sm_list, engine->mpm ? "true" : "false", engine->v2.transforms);
23,374✔
2060

2061
    /* if prefilter didn't already run, we need to consider transformations */
2062
    const DetectEngineTransforms *transforms = NULL;
23,374✔
2063
    if (!engine->mpm) {
23,374✔
2064
        transforms = engine->v2.transforms;
7,953✔
2065
    }
7,953✔
2066

2067
    const InspectionBuffer *buffer = engine->v2.GetData(det_ctx, transforms,
23,374✔
2068
            f, flags, txv, list_id);
23,374✔
2069
    if (unlikely(buffer == NULL)) {
23,374✔
2070
        if (eof && engine->match_on_null) {
483✔
2071
            return DETECT_ENGINE_INSPECT_SIG_MATCH;
5✔
2072
        }
5✔
2073
        return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH :
478✔
2074
                     DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
478✔
2075
    }
483✔
2076

2077
    const uint32_t data_len = buffer->inspect_len;
22,891✔
2078
    const uint8_t *data = buffer->inspect;
22,891✔
2079
    const uint64_t offset = buffer->inspect_offset;
22,891✔
2080

2081
    uint8_t ci_flags = eof ? DETECT_CI_FLAGS_END : 0;
22,891✔
2082
    ci_flags |= (offset == 0 ? DETECT_CI_FLAGS_START : 0);
2,147,489,587!
2083
    ci_flags |= buffer->flags;
22,891✔
2084

2085
    /* Inspect all the uricontents fetched on each
2086
     * transaction at the app layer */
2087
    const bool match = DetectEngineContentInspection(de_ctx, det_ctx, s, engine->smd, NULL, f, data,
22,891✔
2088
            data_len, offset, ci_flags, DETECT_ENGINE_CONTENT_INSPECTION_MODE_STATE);
22,891✔
2089
    if (match) {
22,891✔
2090
        return DETECT_ENGINE_INSPECT_SIG_MATCH;
11,534✔
2091
    } else {
15,625✔
2092
        return eof ? DETECT_ENGINE_INSPECT_SIG_CANT_MATCH :
11,357✔
2093
                     DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
11,357✔
2094
    }
11,357✔
2095
}
22,891✔
2096

2097
// wrapper for both DetectAppLayerInspectEngineRegister and DetectAppLayerMpmRegister
2098
// with cast of callback function
2099
void DetectAppLayerMultiRegister(const char *name, AppProto alproto, uint32_t dir, int progress,
2100
        InspectionMultiBufferGetDataPtr GetData, int priority)
2101
{
166,668✔
2102
    AppLayerInspectEngineRegisterInternal(name, alproto, dir, progress,
166,668✔
2103
            DetectEngineInspectMultiBufferGeneric, NULL, NULL, GetData);
166,668✔
2104
    DetectAppLayerMpmMultiRegister(
166,668✔
2105
            name, dir, priority, PrefilterMultiGenericMpmRegister, GetData, alproto, progress);
166,668✔
2106
}
166,668✔
2107

2108
InspectionBuffer *DetectGetSingleData(struct DetectEngineThreadCtx_ *det_ctx,
2109
        const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv,
2110
        const int list_id, InspectionSingleBufferGetDataPtr GetBuf)
2111
{
8,042✔
2112
    InspectionBuffer *buffer = InspectionBufferGet(det_ctx, list_id);
8,042✔
2113
    if (buffer->inspect == NULL) {
8,042✔
2114
        const uint8_t *b = NULL;
6,544✔
2115
        uint32_t b_len = 0;
6,544✔
2116

2117
        if (!GetBuf(txv, flow_flags, &b, &b_len))
6,544✔
2118
            return NULL;
3,831✔
2119

2120
        InspectionBufferSetupAndApplyTransforms(det_ctx, list_id, buffer, b, b_len, transforms);
2,713✔
2121
    }
2,713✔
2122
    return buffer;
4,211✔
2123
}
8,042✔
2124

2125
InspectionBuffer *DetectGetMultiData(struct DetectEngineThreadCtx_ *det_ctx,
2126
        const DetectEngineTransforms *transforms, Flow *f, const uint8_t flow_flags, void *txv,
2127
        const int list_id, uint32_t index, InspectionMultiBufferGetDataPtr GetBuf)
2128
{
26,210✔
2129
    InspectionBuffer *buffer = InspectionBufferMultipleForListGet(det_ctx, list_id, index);
26,210✔
2130
    if (buffer == NULL) {
26,210!
2131
        return NULL;
×
2132
    }
×
2133
    if (buffer->initialized) {
26,210✔
2134
        return buffer;
3,067✔
2135
    }
3,067✔
2136

2137
    const uint8_t *data = NULL;
23,143✔
2138
    uint32_t data_len = 0;
23,143✔
2139

2140
    if (!GetBuf(det_ctx, txv, flow_flags, index, &data, &data_len)) {
23,143✔
2141
        InspectionBufferSetupMultiEmpty(buffer);
8,648✔
2142
        return NULL;
8,648✔
2143
    }
8,648✔
2144
    InspectionBufferSetupMulti(det_ctx, buffer, transforms, data, data_len);
14,495✔
2145
    buffer->flags = DETECT_CI_FLAGS_SINGLE;
14,495✔
2146
    return buffer;
14,495✔
2147
}
23,143✔
2148

2149
uint8_t DetectEngineInspectMultiBufferGeneric(DetectEngineCtx *de_ctx,
2150
        DetectEngineThreadCtx *det_ctx, const DetectEngineAppInspectionEngine *engine,
2151
        const Signature *s, Flow *f, uint8_t flags, void *alstate, void *txv, uint64_t tx_id)
2152
{
3,190✔
2153
    uint32_t local_id = 0;
3,190✔
2154
    const DetectEngineTransforms *transforms = NULL;
3,190✔
2155
    if (!engine->mpm) {
3,190✔
2156
        transforms = engine->v2.transforms;
1,693✔
2157
    }
1,693✔
2158

2159
    do {
4,850✔
2160
        InspectionBuffer *buffer = DetectGetMultiData(det_ctx, transforms, f, flags, txv,
4,850✔
2161
                engine->sm_list, local_id, engine->v2.GetMultiData);
4,850✔
2162

2163
        if (buffer == NULL || buffer->inspect == NULL)
4,850✔
2164
            break;
567✔
2165

2166
        // The GetData functions set buffer->flags to DETECT_CI_FLAGS_SINGLE
2167
        // This is not meant for streaming buffers
2168
        const bool match = DetectEngineContentInspectionBuffer(de_ctx, det_ctx, s, engine->smd,
4,283✔
2169
                NULL, f, buffer, DETECT_ENGINE_CONTENT_INSPECTION_MODE_STATE);
4,283✔
2170
        if (match) {
4,283✔
2171
            return DETECT_ENGINE_INSPECT_SIG_MATCH;
2,623✔
2172
        }
2,623✔
2173
        local_id++;
1,660✔
2174
    } while (1);
1,660!
2175
    if (local_id == 0) {
567✔
2176
        // That means we did not get even one buffer value from the multi-buffer
2177
        const bool eof = (AppLayerParserGetStateProgress(f->proto, f->alproto, txv, flags) >
60✔
2178
                          engine->progress);
60✔
2179
        if (eof && engine->match_on_null) {
60!
2180
            return DETECT_ENGINE_INSPECT_SIG_MATCH;
22✔
2181
        }
22✔
2182
    }
60✔
2183
    return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
545✔
2184
}
567✔
2185

2186
/**
2187
 * \brief Do the content inspection & validation for a signature
2188
 *
2189
 * \param de_ctx Detection engine context
2190
 * \param det_ctx Detection engine thread context
2191
 * \param s Signature to inspect
2192
 * \param p Packet
2193
 *
2194
 * \retval 0 no match.
2195
 * \retval 1 match.
2196
 */
2197
int DetectEngineInspectPktBufferGeneric(
2198
        DetectEngineThreadCtx *det_ctx,
2199
        const DetectEnginePktInspectionEngine *engine,
2200
        const Signature *s, Packet *p, uint8_t *_alert_flags)
2201
{
7,769✔
2202
    const int list_id = engine->sm_list;
7,769✔
2203
    SCLogDebug("running inspect on %d", list_id);
7,769!
2204

2205
    SCLogDebug("list %d transforms %p",
7,769!
2206
            engine->sm_list, engine->v1.transforms);
7,769✔
2207

2208
    /* if prefilter didn't already run, we need to consider transformations */
2209
    const DetectEngineTransforms *transforms = NULL;
7,769✔
2210
    if (!engine->mpm) {
7,769✔
2211
        transforms = engine->v1.transforms;
5,698✔
2212
    }
5,698✔
2213

2214
    const InspectionBuffer *buffer = engine->v1.GetData(det_ctx, transforms, p,
7,769✔
2215
            list_id);
7,769✔
2216
    if (unlikely(buffer == NULL)) {
7,769!
2217
        return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
1✔
2218
    }
1✔
2219

2220
    uint8_t ci_flags = DETECT_CI_FLAGS_START|DETECT_CI_FLAGS_END;
7,768✔
2221
    ci_flags |= buffer->flags;
7,768✔
2222

2223
    /* Inspect all the uricontents fetched on each
2224
     * transaction at the app layer */
2225
    const bool match = DetectEngineContentInspection(det_ctx->de_ctx, det_ctx, s, engine->smd, p,
7,768✔
2226
            p->flow, buffer->inspect, buffer->inspect_len, 0, ci_flags,
7,768✔
2227
            DETECT_ENGINE_CONTENT_INSPECTION_MODE_HEADER);
7,768✔
2228
    if (match) {
7,768✔
2229
        return DETECT_ENGINE_INSPECT_SIG_MATCH;
4,028✔
2230
    } else {
4,428✔
2231
        return DETECT_ENGINE_INSPECT_SIG_NO_MATCH;
3,740✔
2232
    }
3,740✔
2233
}
7,768✔
2234

2235
/** \internal
2236
 *  \brief inject a pseudo packet into each detect thread
2237
 *         if the thread should flush its output logs.
2238
 */
2239
void InjectPacketsForFlush(ThreadVars **detect_tvs, int no_of_detect_tvs)
2240
{
×
2241
    /* inject a fake packet if the detect thread that needs it. This function
2242
     * is called when a heartbeat log-flush request has been made
2243
     * and it should process a pseudo packet and flush its output logs
2244
     * to speed the process. */
2245
#if DEBUG
2246
    int count = 0;
2247
#endif
2248
    for (int i = 0; i < no_of_detect_tvs; i++) {
×
2249
        if (detect_tvs[i]) { // && detect_tvs[i]->inq != NULL) {
×
2250
            Packet *p = PacketGetFromAlloc();
×
2251
            if (p != NULL) {
×
2252
                SCLogDebug("Injecting pkt for tv %s[i=%d] %d", detect_tvs[i]->name, i, count++);
×
2253
                p->flags |= PKT_PSEUDO_STREAM_END;
×
2254
                p->flags |= PKT_PSEUDO_LOG_FLUSH;
×
2255
                PKT_SET_SRC(p, PKT_SRC_DETECT_RELOAD_FLUSH);
×
2256
                PacketQueue *q = detect_tvs[i]->stream_pq;
×
2257
                SCMutexLock(&q->mutex_q);
×
2258
                PacketEnqueue(q, p);
×
2259
                SCCondSignal(&q->cond_q);
×
2260
                SCMutexUnlock(&q->mutex_q);
×
2261
            }
×
2262
        }
×
2263
    }
×
2264
    SCLogDebug("leaving: thread notification count = %d", count);
×
2265
}
×
2266

2267
/** \internal
2268
 *  \brief inject a pseudo packet into each detect thread
2269
 *      -that doesn't use the new det_ctx yet
2270
 *      -*or*, if the thread should flush its output logs.
2271
 */
2272
static void InjectPackets(
2273
        ThreadVars **detect_tvs, DetectEngineThreadCtx **new_det_ctx, int no_of_detect_tvs)
2274
{
15✔
2275
    /* inject a fake packet if the detect thread that needs it. This function
2276
     * is called if
2277
     *  - A thread isn't using a DE ctx and should
2278
     *  - Or, it should process a pseudo packet and flush its output logs.
2279
     * to speed the process. */
2280
    for (int i = 0; i < no_of_detect_tvs; i++) {
69!
2281
        if (SC_ATOMIC_GET(new_det_ctx[i]->so_far_used_by_detect) != 1) {
54!
2282
            if (detect_tvs[i]->inq != NULL) {
54!
2283
                Packet *p = PacketGetFromAlloc();
40✔
2284
                if (p != NULL) {
40!
2285
                    p->flags |= PKT_PSEUDO_STREAM_END;
40✔
2286
                    PKT_SET_SRC(p, PKT_SRC_DETECT_RELOAD_FLUSH);
40✔
2287
                    PacketQueue *q = detect_tvs[i]->inq->pq;
40✔
2288
                    SCMutexLock(&q->mutex_q);
40✔
2289
                    PacketEnqueue(q, p);
40✔
2290
                    SCCondSignal(&q->cond_q);
40✔
2291
                    SCMutexUnlock(&q->mutex_q);
40✔
2292
                }
40✔
2293
            }
40✔
2294
        }
54✔
2295
    }
54✔
2296
}
15✔
2297

2298
/** \internal
2299
 *  \brief Update detect threads with new detect engine
2300
 *
2301
 *  Atomically update each detect thread with a new thread context
2302
 *  that is associated to the new detection engine(s).
2303
 *
2304
 *  If called in unix socket mode, it's possible that we don't have
2305
 *  detect threads yet.
2306
 *  NOTE: master MUST be locked before calling this
2307
 *
2308
 *  \retval -1 error
2309
 *  \retval 0 no detection threads
2310
 *  \retval 1 successful reload
2311
 */
2312
static int DetectEngineReloadThreads(DetectEngineCtx *new_de_ctx)
2313
{
35,544✔
2314
    SCEnter();
35,544✔
2315
    uint32_t i = 0;
35,544✔
2316

2317
    /* count detect threads in use */
2318
    uint32_t no_of_detect_tvs = TmThreadCountThreadsByTmmFlags(TM_FLAG_FLOWWORKER_TM);
35,544✔
2319
    /* can be zero in unix socket mode */
2320
    if (no_of_detect_tvs == 0) {
35,544!
2321
        return 0;
35,529✔
2322
    }
35,529✔
2323

2324
    /* prepare swap structures */
2325
    DetectEngineThreadCtx *old_det_ctx[no_of_detect_tvs];
15✔
2326
    DetectEngineThreadCtx *new_det_ctx[no_of_detect_tvs];
15✔
2327
    ThreadVars *detect_tvs[no_of_detect_tvs];
15✔
2328
    memset(old_det_ctx, 0x00, (no_of_detect_tvs * sizeof(DetectEngineThreadCtx *)));
15✔
2329
    memset(new_det_ctx, 0x00, (no_of_detect_tvs * sizeof(DetectEngineThreadCtx *)));
15✔
2330
    memset(detect_tvs, 0x00, (no_of_detect_tvs * sizeof(ThreadVars *)));
15✔
2331

2332
    /* start the process of swapping detect threads ctxs */
2333

2334
    /* get reference to tv's and setup new_det_ctx array */
2335
    SCMutexLock(&tv_root_lock);
15✔
2336
    for (ThreadVars *tv = tv_root[TVT_PPT]; tv != NULL; tv = tv->next) {
85!
2337
        if ((tv->tmm_flags & TM_FLAG_FLOWWORKER_TM) == 0) {
70!
2338
            continue;
16✔
2339
        }
16✔
2340
        for (TmSlot *s = tv->tm_slots; s != NULL; s = s->slot_next) {
82!
2341
            TmModule *tm = TmModuleGetById(s->tm_id);
82✔
2342
            if (!(tm->flags & TM_FLAG_FLOWWORKER_TM)) {
82!
2343
                continue;
28✔
2344
            }
28✔
2345

2346
            if (suricata_ctl_flags != 0) {
54!
2347
                SCMutexUnlock(&tv_root_lock);
×
2348
                goto error;
×
2349
            }
×
2350

2351
            old_det_ctx[i] = FlowWorkerGetDetectCtxPtr(SC_ATOMIC_GET(s->slot_data));
54✔
2352
            detect_tvs[i] = tv;
54✔
2353

2354
            new_det_ctx[i] = DetectEngineThreadCtxInitForReload(tv, new_de_ctx, 1);
54✔
2355
            if (new_det_ctx[i] == NULL) {
54!
2356
                SCLogError("Detect engine thread init "
×
2357
                           "failure in live rule swap.  Let's get out of here");
×
2358
                SCMutexUnlock(&tv_root_lock);
×
2359
                goto error;
×
2360
            }
×
2361
            SCLogDebug("live rule swap created new det_ctx - %p and de_ctx "
54!
2362
                       "- %p\n", new_det_ctx[i], new_de_ctx);
54✔
2363
            i++;
54✔
2364
            break;
54✔
2365
        }
54✔
2366
    }
54✔
2367
    BUG_ON(i != no_of_detect_tvs);
15!
2368

2369
    /* atomically replace the det_ctx data */
2370
    i = 0;
15✔
2371
    for (ThreadVars *tv = tv_root[TVT_PPT]; tv != NULL; tv = tv->next) {
85!
2372
        if ((tv->tmm_flags & TM_FLAG_FLOWWORKER_TM) == 0) {
70!
2373
            continue;
16✔
2374
        }
16✔
2375
        for (TmSlot *s = tv->tm_slots; s != NULL; s = s->slot_next) {
82!
2376
            TmModule *tm = TmModuleGetById(s->tm_id);
82✔
2377
            if (!(tm->flags & TM_FLAG_FLOWWORKER_TM)) {
82!
2378
                continue;
28✔
2379
            }
28✔
2380
            SCLogDebug("swapping new det_ctx - %p with older one - %p",
54!
2381
                       new_det_ctx[i], SC_ATOMIC_GET(s->slot_data));
54✔
2382
            FlowWorkerReplaceDetectCtx(SC_ATOMIC_GET(s->slot_data), new_det_ctx[i++]);
54✔
2383
            break;
54✔
2384
        }
82✔
2385
    }
54✔
2386
    SCMutexUnlock(&tv_root_lock);
15✔
2387

2388
    /* threads now all have new data, however they may not have started using
2389
     * it and may still use the old data */
2390

2391
    SCLogDebug("Live rule swap has swapped %d old det_ctx's with new ones, "
15!
2392
               "along with the new de_ctx", no_of_detect_tvs);
15✔
2393

2394
    InjectPackets(detect_tvs, new_det_ctx, no_of_detect_tvs);
15✔
2395

2396
    /* loop waiting for detect threads to switch to the new det_ctx. Try to
2397
     * wake up capture if needed (break loop). */
2398
    uint32_t threads_done = 0;
15✔
2399
retry:
18✔
2400
    for (i = 0; i < no_of_detect_tvs; i++) {
81!
2401
        if (suricata_ctl_flags != 0) {
63!
2402
            threads_done = no_of_detect_tvs;
×
2403
            break;
×
2404
        }
×
2405
        SleepMsec(1);
63✔
2406
        if (SC_ATOMIC_GET(new_det_ctx[i]->so_far_used_by_detect) == 1) {
63!
2407
            SCLogDebug("new_det_ctx - %p used by detect engine", new_det_ctx[i]);
54!
2408
            threads_done++;
54✔
2409
        } else {
54✔
2410
            TmThreadsCaptureBreakLoop(detect_tvs[i]);
9✔
2411
        }
9✔
2412
    }
63✔
2413
    if (threads_done < no_of_detect_tvs) {
18!
2414
        threads_done = 0;
3✔
2415
        SleepMsec(250);
3✔
2416
        goto retry;
3✔
2417
    }
3✔
2418

2419
    /* this is to make sure that if someone initiated shutdown during a live
2420
     * rule swap, the live rule swap won't clean up the old det_ctx and
2421
     * de_ctx, till all detect threads have stopped working and sitting
2422
     * silently after setting RUNNING_DONE flag and while waiting for
2423
     * THV_DEINIT flag */
2424
    if (i != no_of_detect_tvs) { // not all threads we swapped
15!
2425
        for (ThreadVars *tv = tv_root[TVT_PPT]; tv != NULL; tv = tv->next) {
×
2426
            if ((tv->tmm_flags & TM_FLAG_FLOWWORKER_TM) == 0) {
×
2427
                continue;
×
2428
            }
×
2429

2430
            while (!TmThreadsCheckFlag(tv, THV_RUNNING_DONE)) {
×
2431
                SleepUsec(100);
×
2432
            }
×
2433
        }
×
2434
    }
×
2435

2436
    /* free all the ctxs */
2437
    for (i = 0; i < no_of_detect_tvs; i++) {
69!
2438
        SCLogDebug("Freeing old_det_ctx - %p used by detect",
54!
2439
                   old_det_ctx[i]);
54✔
2440
        DetectEngineThreadCtxDeinit(NULL, old_det_ctx[i]);
54✔
2441
    }
54✔
2442

2443
    SRepReloadComplete();
15✔
2444

2445
    return 1;
15✔
2446

2447
 error:
×
2448
    for (i = 0; i < no_of_detect_tvs; i++) {
×
2449
        if (new_det_ctx[i] != NULL)
×
2450
            DetectEngineThreadCtxDeinit(NULL, new_det_ctx[i]);
×
2451
    }
×
2452
    return -1;
×
2453
}
18✔
2454

2455
bool DetectEngineMpmCachingEnabled(void)
2456
{
1,511✔
2457
    int sgh_mpm_caching = 0;
1,511✔
2458
    if (SCConfGetBool("detect.sgh-mpm-caching", &sgh_mpm_caching) != 1) {
1,511!
2459
        return false;
1,509✔
2460
    }
1,509✔
2461
    return (bool)sgh_mpm_caching;
2✔
2462
}
1,511✔
2463

2464
const char *DetectEngineMpmCachingGetPath(void)
2465
{
1✔
2466
    if (DetectEngineMpmCachingEnabled() == false) {
1!
2467
        return NULL;
×
2468
    }
×
2469

2470
    char yamlpath[] = "detect.sgh-mpm-caching-path";
1✔
2471
    const char *strval = NULL;
1✔
2472
    if (SCConfGet(yamlpath, &strval) == 1 && strval != NULL) {
1!
2473
        return strval;
1✔
2474
    }
1✔
2475

2476
    static bool notified = false;
×
2477
    if (!notified) {
×
2478
        SCLogInfo("%s has no path specified, using %s", yamlpath, SGH_CACHE_DIR);
×
2479
        notified = true;
×
2480
    }
×
2481
    return SGH_CACHE_DIR;
×
2482
}
1✔
2483

2484
void DetectEngineMpmCacheService(uint32_t op_flags)
2485
{
37,291✔
2486
    DetectEngineCtx *de_ctx = DetectEngineGetCurrent();
37,291✔
2487
    if (!de_ctx) {
37,291!
2488
        return;
×
2489
    }
×
2490

2491
    if (!de_ctx->mpm_cfg || !de_ctx->mpm_cfg->cache_dir_path) {
37,291!
2492
        goto error;
37,290✔
2493
    }
37,290✔
2494

2495
    if (mpm_table[de_ctx->mpm_matcher].CacheStatsInit != NULL) {
1!
2496
        de_ctx->mpm_cfg->cache_stats = mpm_table[de_ctx->mpm_matcher].CacheStatsInit();
1✔
2497
        if (de_ctx->mpm_cfg->cache_stats == NULL) {
1!
2498
            goto error;
×
2499
        }
×
2500
    }
1✔
2501

2502
    if (op_flags & DETECT_ENGINE_MPM_CACHE_OP_SAVE) {
1!
2503
        if (mpm_table[de_ctx->mpm_matcher].CacheRuleset != NULL) {
1!
2504
            mpm_table[de_ctx->mpm_matcher].CacheRuleset(de_ctx->mpm_cfg);
1✔
2505
        }
1✔
2506
    }
1✔
2507

2508
    if (op_flags & DETECT_ENGINE_MPM_CACHE_OP_PRUNE) {
1!
2509
        if (mpm_table[de_ctx->mpm_matcher].CachePrune != NULL) {
1!
2510
            mpm_table[de_ctx->mpm_matcher].CachePrune(de_ctx->mpm_cfg);
1✔
2511
        }
1✔
2512
    }
1✔
2513

2514
    if (mpm_table[de_ctx->mpm_matcher].CacheStatsPrint != NULL) {
1!
2515
        mpm_table[de_ctx->mpm_matcher].CacheStatsPrint(de_ctx->mpm_cfg->cache_stats);
1✔
2516
    }
1✔
2517

2518
    if (mpm_table[de_ctx->mpm_matcher].CacheStatsDeinit != NULL) {
1!
2519
        mpm_table[de_ctx->mpm_matcher].CacheStatsDeinit(de_ctx->mpm_cfg->cache_stats);
1✔
2520
        de_ctx->mpm_cfg->cache_stats = NULL;
1✔
2521
    }
1✔
2522

2523
error:
37,291✔
2524
    DetectEngineDeReference(&de_ctx);
37,291✔
2525
}
37,291✔
2526

2527
static DetectEngineCtx *DetectEngineCtxInitReal(
2528
        enum DetectEngineType type, const char *prefix, uint32_t tenant_id)
2529
{
38,901✔
2530
    DetectEngineCtx *de_ctx = SCCalloc(1, sizeof(DetectEngineCtx));
38,901✔
2531
    if (unlikely(de_ctx == NULL))
38,901!
2532
        goto error;
×
2533

2534
    memset(&de_ctx->sig_stat, 0, sizeof(SigFileLoaderStat));
38,901✔
2535
    TAILQ_INIT(&de_ctx->sig_stat.failed_sigs);
38,901!
2536
    de_ctx->sigerror = NULL;
38,901✔
2537
    de_ctx->type = type;
38,901✔
2538
    de_ctx->filemagic_thread_ctx_id = -1;
38,901✔
2539
    de_ctx->tenant_id = tenant_id;
38,901✔
2540

2541
    de_ctx->mpm_matcher = PatternMatchDefaultMatcher();
38,901✔
2542
    de_ctx->spm_matcher = SinglePatternMatchDefaultMatcher();
38,901✔
2543

2544
    if (mpm_table[de_ctx->mpm_matcher].ConfigInit) {
38,901!
2545
        de_ctx->mpm_cfg = mpm_table[de_ctx->mpm_matcher].ConfigInit();
1,510✔
2546
        if (de_ctx->mpm_cfg == NULL) {
1,510!
2547
            goto error;
×
2548
        }
×
2549

2550
        if (DetectEngineMpmCachingEnabled() && mpm_table[de_ctx->mpm_matcher].ConfigCacheDirSet) {
1,510!
2551
            mpm_table[de_ctx->mpm_matcher].ConfigCacheDirSet(
1✔
2552
                    de_ctx->mpm_cfg, DetectEngineMpmCachingGetPath());
1✔
2553

2554
            if (mpm_table[de_ctx->mpm_matcher].CachePrune) {
1!
2555
                if (SCConfGetTime("detect.sgh-mpm-caching-max-age",
1!
2556
                            &de_ctx->mpm_cfg->cache_max_age_seconds) != 1) {
1✔
2557
                    de_ctx->mpm_cfg->cache_max_age_seconds = 7ULL * 24ULL * 60ULL * 60ULL;
1✔
2558
                }
1✔
2559
            }
1✔
2560
        }
1✔
2561
    }
1,510✔
2562

2563
    if (type == DETECT_ENGINE_TYPE_DD_STUB || type == DETECT_ENGINE_TYPE_MT_STUB) {
38,901!
2564
        de_ctx->version = DetectEngineGetVersion();
3✔
2565
        SCLogDebug("stub %u with version %u", type, de_ctx->version);
3!
2566
        return de_ctx;
3✔
2567
    }
3✔
2568

2569
    if (prefix != NULL) {
38,898✔
2570
        strlcpy(de_ctx->config_prefix, prefix, sizeof(de_ctx->config_prefix));
29✔
2571
    }
29✔
2572

2573
    int failure_fatal = 0;
38,898✔
2574
    if (SCConfGetBool("engine.init-failure-fatal", (int *)&failure_fatal) != 1) {
38,898✔
2575
        SCLogDebug("ConfGetBool could not load the value.");
37,176!
2576
    }
37,176✔
2577
    de_ctx->failure_fatal = (failure_fatal == 1);
38,898✔
2578

2579
    SCLogConfig("pattern matchers: MPM: %s, SPM: %s", mpm_table[de_ctx->mpm_matcher].name,
38,898✔
2580
            spm_table[de_ctx->spm_matcher].name);
38,898✔
2581
    de_ctx->spm_global_thread_ctx = SpmInitGlobalThreadCtx(de_ctx->spm_matcher);
38,898✔
2582
    if (de_ctx->spm_global_thread_ctx == NULL) {
38,898!
2583
        SCLogDebug("Unable to alloc SpmGlobalThreadCtx.");
×
2584
        goto error;
×
2585
    }
×
2586

2587
    de_ctx->sm_types_prefilter = SCCalloc(DETECT_TBLSIZE, sizeof(bool));
38,898✔
2588
    if (de_ctx->sm_types_prefilter == NULL) {
38,898!
2589
        goto error;
×
2590
    }
×
2591
    de_ctx->sm_types_silent_error = SCCalloc(DETECT_TBLSIZE, sizeof(bool));
38,898✔
2592
    if (de_ctx->sm_types_silent_error == NULL) {
38,898!
2593
        goto error;
×
2594
    }
×
2595
    if (DetectEngineCtxLoadConf(de_ctx) == -1) {
38,898!
2596
        goto error;
×
2597
    }
×
2598

2599
    SigGroupHeadHashInit(de_ctx);
38,898✔
2600
    MpmStoreInit(de_ctx);
38,898✔
2601
    DetectParseDupSigHashInit(de_ctx);
38,898✔
2602
    DetectAddressMapInit(de_ctx);
38,898✔
2603
    DetectMetadataHashInit(de_ctx);
38,898✔
2604
    DetectBufferTypeSetupDetectEngine(de_ctx);
38,898✔
2605
    DetectEngineInitializeFastPatternList(de_ctx);
38,898✔
2606

2607
    /* init iprep... ignore errors for now */
2608
    (void)SRepInit(de_ctx);
38,898✔
2609

2610
    SCClassSCConfInit(de_ctx);
38,898✔
2611
    if (!SCClassConfLoadClassificationConfigFile(de_ctx, NULL)) {
38,898✔
2612
        if (SCRunmodeGet() == RUNMODE_CONF_TEST)
37,169✔
2613
            goto error;
1✔
2614
    }
37,169✔
2615

2616
    if (ActionInitConfig() < 0) {
38,897!
2617
        goto error;
×
2618
    }
×
2619
    SCReferenceSCConfInit(de_ctx);
38,897✔
2620
    if (SCRConfLoadReferenceConfigFile(de_ctx, NULL) < 0) {
38,897✔
2621
        if (SCRunmodeGet() == RUNMODE_CONF_TEST)
37,168✔
2622
            goto error;
1✔
2623
    }
37,168✔
2624

2625
    de_ctx->version = DetectEngineGetVersion();
38,896✔
2626
    SCLogDebug("dectx with version %u", de_ctx->version);
38,896!
2627
    return de_ctx;
38,896✔
2628
error:
2✔
2629
    if (de_ctx != NULL) {
2!
2630
        DetectEngineCtxFree(de_ctx);
2✔
2631
    }
2✔
2632
    return NULL;
2✔
2633
}
38,897✔
2634

2635
DetectEngineCtx *DetectEngineCtxInitStubForMT(void)
2636
{
3✔
2637
    return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_MT_STUB, NULL, 0);
3✔
2638
}
3✔
2639

2640
DetectEngineCtx *DetectEngineCtxInitStubForDD(void)
2641
{
×
2642
    return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_DD_STUB, NULL, 0);
×
2643
}
×
2644

2645
DetectEngineCtx *DetectEngineCtxInit(void)
2646
{
38,869✔
2647
    return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_NORMAL, NULL, 0);
38,869✔
2648
}
38,869✔
2649

2650
DetectEngineCtx *DetectEngineCtxInitWithPrefix(const char *prefix, uint32_t tenant_id)
2651
{
35,558✔
2652
    if (prefix == NULL || strlen(prefix) == 0)
35,558!
2653
        return DetectEngineCtxInit();
35,529✔
2654
    else
29✔
2655
        return DetectEngineCtxInitReal(DETECT_ENGINE_TYPE_NORMAL, prefix, tenant_id);
29✔
2656
}
35,558✔
2657

2658
static void DetectEngineCtxFreeThreadKeywordData(DetectEngineCtx *de_ctx)
2659
{
38,842✔
2660
    HashListTableFree(de_ctx->keyword_hash);
38,842✔
2661
}
38,842✔
2662

2663
static void DetectEngineCtxFreeFailedSigs(DetectEngineCtx *de_ctx)
2664
{
38,842✔
2665
    SigString *item = NULL;
38,842✔
2666
    SigString *sitem;
38,842✔
2667

2668
    TAILQ_FOREACH_SAFE(item, &de_ctx->sig_stat.failed_sigs, next, sitem) {
4,844,421✔
2669
        SCFree(item->filename);
4,841,170✔
2670
        SCFree(item->sig_str);
4,841,170✔
2671
        if (item->sig_error) {
4,841,170✔
2672
            SCFree(item->sig_error);
12,248✔
2673
        }
12,248✔
2674
        TAILQ_REMOVE(&de_ctx->sig_stat.failed_sigs, item, next);
4,841,170✔
2675
        SCFree(item);
4,841,170✔
2676
    }
4,841,170✔
2677
}
38,842✔
2678

2679
/**
2680
 * \brief Free a DetectEngineCtx::
2681
 *
2682
 * \param de_ctx DetectEngineCtx:: to be freed
2683
 */
2684
void DetectEngineCtxFree(DetectEngineCtx *de_ctx)
2685
{
38,842✔
2686

2687
    if (de_ctx == NULL)
38,842!
2688
        return;
×
2689

2690
#ifdef PROFILE_RULES
2691
    if (de_ctx->profile_ctx != NULL) {
2692
        SCProfilingRuleDestroyCtx(de_ctx->profile_ctx);
2693
        de_ctx->profile_ctx = NULL;
2694
    }
2695
#endif
2696
#ifdef PROFILING
2697
    if (de_ctx->profile_keyword_ctx != NULL) {
2698
        SCProfilingKeywordDestroyCtx(de_ctx);//->profile_keyword_ctx);
2699
//        de_ctx->profile_keyword_ctx = NULL;
2700
    }
2701
    if (de_ctx->profile_sgh_ctx != NULL) {
2702
        SCProfilingSghDestroyCtx(de_ctx);
2703
    }
2704
    SCProfilingPrefilterDestroyCtx(de_ctx);
2705
#endif
2706

2707
    if (mpm_table[de_ctx->mpm_matcher].ConfigDeinit) {
38,842!
2708
        mpm_table[de_ctx->mpm_matcher].ConfigDeinit(&de_ctx->mpm_cfg);
1,510✔
2709
    }
1,510✔
2710
    /* Normally the hashes are freed elsewhere, but
2711
     * to be sure look at them again here.
2712
     */
2713
    SigGroupHeadHashFree(de_ctx);
38,842✔
2714
    MpmStoreFree(de_ctx);
38,842✔
2715
    DetectParseDupSigHashFree(de_ctx);
38,842✔
2716
    SCSigSignatureOrderingModuleCleanup(de_ctx);
38,842✔
2717
    SigCleanSignatures(de_ctx);
38,842✔
2718
    if (de_ctx->sig_array)
38,842✔
2719
        SCFree(de_ctx->sig_array);
38,183✔
2720

2721
    if (de_ctx->filedata_config)
38,842✔
2722
        SCFree(de_ctx->filedata_config);
3,423✔
2723

2724
    DetectEngineFreeFastPatternList(de_ctx);
38,842✔
2725
    SCClassConfDeInitContext(de_ctx);
38,842✔
2726
    SCRConfDeInitContext(de_ctx);
38,842✔
2727

2728
    SigGroupCleanup(de_ctx);
38,842✔
2729

2730
    SpmDestroyGlobalThreadCtx(de_ctx->spm_global_thread_ctx);
38,842✔
2731
    SCFree(de_ctx->sm_types_prefilter);
38,842✔
2732
    SCFree(de_ctx->sm_types_silent_error);
38,842✔
2733

2734
    MpmFactoryDeRegisterAllMpmCtxProfiles(de_ctx);
38,842✔
2735

2736
    DetectEngineCtxFreeThreadKeywordData(de_ctx);
38,842✔
2737
    SRepDestroy(de_ctx);
38,842✔
2738
    DetectEngineCtxFreeFailedSigs(de_ctx);
38,842✔
2739

2740
    DetectAddressMapFree(de_ctx);
38,842✔
2741
    DetectMetadataHashFree(de_ctx);
38,842✔
2742

2743
    /* if we have a config prefix, remove the config from the tree */
2744
    if (strlen(de_ctx->config_prefix) > 0) {
38,842✔
2745
        /* remove config */
2746
        SCConfNode *node = SCConfGetNode(de_ctx->config_prefix);
30✔
2747
        if (node != NULL) {
30!
2748
            SCConfNodeRemove(node); /* frees node */
26✔
2749
        }
26✔
2750
#if 0
2751
        SCConfDump();
2752
#endif
2753
    }
30✔
2754

2755
    DetectPortCleanupList(de_ctx, de_ctx->tcp_priorityports);
38,842✔
2756
    DetectPortCleanupList(de_ctx, de_ctx->udp_priorityports);
38,842✔
2757

2758
    DetectBufferTypeFreeDetectEngine(de_ctx);
38,842✔
2759
    SCClassConfDeinit(de_ctx);
38,842✔
2760
    SCReferenceConfDeinit(de_ctx);
38,842✔
2761

2762
    if (de_ctx->tenant_path) {
38,842✔
2763
        SCFree(de_ctx->tenant_path);
21✔
2764
    }
21✔
2765

2766
    if (de_ctx->requirements) {
38,842✔
2767
        SCDetectRequiresStatusFree(de_ctx->requirements);
739✔
2768
    }
739✔
2769

2770
    if (de_ctx->non_pf_engine_names) {
38,842✔
2771
        HashTableFree(de_ctx->non_pf_engine_names);
22,277✔
2772
    }
22,277✔
2773
    SCFree(de_ctx);
38,842✔
2774
    //DetectAddressGroupPrintMemory();
2775
    //DetectSigGroupPrintMemory();
2776
    //DetectPortPrintMemory();
2777
}
38,842✔
2778

2779
/** \brief  Function that load DetectEngineCtx config for grouping sigs
2780
 *          used by the engine
2781
 *  \retval 0 if no config provided, 1 if config was provided
2782
 *          and loaded successfully
2783
 */
2784
static int DetectEngineCtxLoadConf(DetectEngineCtx *de_ctx)
2785
{
38,898✔
2786
    uint8_t profile = ENGINE_PROFILE_MEDIUM;
38,898✔
2787
    const char *max_uniq_toclient_groups_str = NULL;
38,898✔
2788
    const char *max_uniq_toserver_groups_str = NULL;
38,898✔
2789
    const char *sgh_mpm_context = NULL;
38,898✔
2790
    const char *de_ctx_profile = NULL;
38,898✔
2791

2792
    (void)SCConfGet("detect.profile", &de_ctx_profile);
38,898✔
2793
    (void)SCConfGet("detect.sgh-mpm-context", &sgh_mpm_context);
38,898✔
2794

2795
    SCConfNode *de_ctx_custom = SCConfGetNode("detect-engine");
38,898✔
2796
    SCConfNode *opt = NULL;
38,898✔
2797

2798
    if (de_ctx_custom != NULL) {
38,898!
2799
        TAILQ_FOREACH(opt, &de_ctx_custom->head, next) {
16!
2800
            if (de_ctx_profile == NULL) {
16!
2801
                if (opt->val && strcmp(opt->val, "profile") == 0) {
6!
2802
                    de_ctx_profile = opt->head.tqh_first->val;
6✔
2803
                }
6✔
2804
            }
6✔
2805

2806
            if (sgh_mpm_context == NULL) {
16!
2807
                if (opt->val && strcmp(opt->val, "sgh-mpm-context") == 0) {
16!
2808
                    sgh_mpm_context = opt->head.tqh_first->val;
×
2809
                }
×
2810
            }
16✔
2811
        }
16✔
2812
    }
6✔
2813

2814
    if (de_ctx_profile != NULL) {
38,898✔
2815
        if (strcmp(de_ctx_profile, "low") == 0 ||
1,334!
2816
            strcmp(de_ctx_profile, "lowest") == 0) {        // legacy
1,334!
2817
            profile = ENGINE_PROFILE_LOW;
×
2818
        } else if (strcmp(de_ctx_profile, "medium") == 0) {
1,334✔
2819
            profile = ENGINE_PROFILE_MEDIUM;
1,331✔
2820
        } else if (strcmp(de_ctx_profile, "high") == 0 ||
1,331!
2821
                   strcmp(de_ctx_profile, "highest") == 0) { // legacy
3!
2822
            profile = ENGINE_PROFILE_HIGH;
×
2823
        } else if (strcmp(de_ctx_profile, "custom") == 0) {
3!
2824
            profile = ENGINE_PROFILE_CUSTOM;
3✔
2825
        } else {
3✔
2826
            SCLogError("invalid value for detect.profile: '%s'. "
×
2827
                       "Valid options: low, medium, high and custom.",
×
2828
                    de_ctx_profile);
×
2829
            return -1;
×
2830
        }
×
2831

2832
        SCLogDebug("Profile for detection engine groups is \"%s\"", de_ctx_profile);
1,334!
2833
    } else {
38,401✔
2834
        SCLogDebug("Profile for detection engine groups not provided "
37,564!
2835
                   "at suricata.yaml. Using default (\"medium\").");
37,564✔
2836
    }
37,564✔
2837

2838
    /* detect-engine.sgh-mpm-context option parsing */
2839
    if (sgh_mpm_context == NULL || strcmp(sgh_mpm_context, "auto") == 0) {
38,898!
2840
        /* for now, since we still haven't implemented any intelligence into
2841
         * understanding the patterns and distributing mpm_ctx across sgh */
2842
        if (de_ctx->mpm_matcher == MPM_AC || de_ctx->mpm_matcher == MPM_AC_KS ||
38,898!
2843
                de_ctx->mpm_matcher == MPM_HS) {
38,898!
2844
            de_ctx->sgh_mpm_ctx_cnf = ENGINE_SGH_MPM_FACTORY_CONTEXT_SINGLE;
38,898✔
2845
        } else {
38,898✔
2846
            de_ctx->sgh_mpm_ctx_cnf = ENGINE_SGH_MPM_FACTORY_CONTEXT_FULL;
×
2847
        }
×
2848
    } else {
38,898✔
UNCOV
2849
        if (strcmp(sgh_mpm_context, "single") == 0) {
×
2850
            de_ctx->sgh_mpm_ctx_cnf = ENGINE_SGH_MPM_FACTORY_CONTEXT_SINGLE;
×
UNCOV
2851
        } else if (strcmp(sgh_mpm_context, "full") == 0) {
×
2852
            de_ctx->sgh_mpm_ctx_cnf = ENGINE_SGH_MPM_FACTORY_CONTEXT_FULL;
×
UNCOV
2853
        } else {
×
UNCOV
2854
            SCLogError("You have supplied an "
×
UNCOV
2855
                       "invalid conf value for detect-engine.sgh-mpm-context-"
×
UNCOV
2856
                       "%s",
×
UNCOV
2857
                    sgh_mpm_context);
×
UNCOV
2858
            exit(EXIT_FAILURE);
×
UNCOV
2859
        }
×
UNCOV
2860
    }
×
2861

2862
    if (RunmodeIsUnittests()) {
38,898!
2863
        de_ctx->sgh_mpm_ctx_cnf = ENGINE_SGH_MPM_FACTORY_CONTEXT_FULL;
1,481✔
2864
    }
1,481✔
2865

2866
    /* parse profile custom-values */
2867
    opt = NULL;
38,898✔
2868
    switch (profile) {
38,898✔
2869
        case ENGINE_PROFILE_LOW:
×
2870
            de_ctx->max_uniq_toclient_groups = 15;
×
2871
            de_ctx->max_uniq_toserver_groups = 25;
×
2872
            break;
×
2873

2874
        case ENGINE_PROFILE_HIGH:
×
2875
            de_ctx->max_uniq_toclient_groups = 75;
×
2876
            de_ctx->max_uniq_toserver_groups = 75;
×
2877
            break;
×
2878

2879
        case ENGINE_PROFILE_CUSTOM:
3✔
2880
            (void)SCConfGet("detect.custom-values.toclient-groups", &max_uniq_toclient_groups_str);
3✔
2881
            (void)SCConfGet("detect.custom-values.toserver-groups", &max_uniq_toserver_groups_str);
3✔
2882

2883
            if (de_ctx_custom != NULL) {
3!
2884
                TAILQ_FOREACH(opt, &de_ctx_custom->head, next) {
5!
2885
                    if (opt->val && strcmp(opt->val, "custom-values") == 0) {
5!
2886
                        if (max_uniq_toclient_groups_str == NULL) {
2!
2887
                            max_uniq_toclient_groups_str = (char *)SCConfNodeLookupChildValue(
2✔
2888
                                    opt->head.tqh_first, "toclient-sp-groups");
2✔
2889
                        }
2✔
2890
                        if (max_uniq_toclient_groups_str == NULL) {
2!
2891
                            max_uniq_toclient_groups_str = (char *)SCConfNodeLookupChildValue(
2✔
2892
                                    opt->head.tqh_first, "toclient-groups");
2✔
2893
                        }
2✔
2894
                        if (max_uniq_toserver_groups_str == NULL) {
2!
2895
                            max_uniq_toserver_groups_str = (char *)SCConfNodeLookupChildValue(
2✔
2896
                                    opt->head.tqh_first, "toserver-dp-groups");
2✔
2897
                        }
2✔
2898
                        if (max_uniq_toserver_groups_str == NULL) {
2!
2899
                            max_uniq_toserver_groups_str = (char *)SCConfNodeLookupChildValue(
2✔
2900
                                    opt->head.tqh_first, "toserver-groups");
2✔
2901
                        }
2✔
2902
                    }
2✔
2903
                }
5✔
2904
            }
2✔
2905
            if (max_uniq_toclient_groups_str != NULL) {
3!
2906
                if (StringParseUint16(&de_ctx->max_uniq_toclient_groups, 10,
2!
2907
                            (uint16_t)strlen(max_uniq_toclient_groups_str),
2✔
2908
                            (const char *)max_uniq_toclient_groups_str) <= 0) {
2✔
2909
                    de_ctx->max_uniq_toclient_groups = 20;
1✔
2910

2911
                    SCLogWarning("parsing '%s' for "
1✔
2912
                                 "toclient-groups failed, using %u",
1✔
2913
                            max_uniq_toclient_groups_str, de_ctx->max_uniq_toclient_groups);
1✔
2914
                }
1✔
2915
            } else {
3✔
2916
                de_ctx->max_uniq_toclient_groups = 20;
1✔
2917
            }
1✔
2918
            SCLogConfig("toclient-groups %u", de_ctx->max_uniq_toclient_groups);
3✔
2919

2920
            if (max_uniq_toserver_groups_str != NULL) {
3!
2921
                if (StringParseUint16(&de_ctx->max_uniq_toserver_groups, 10,
3!
2922
                            (uint16_t)strlen(max_uniq_toserver_groups_str),
3✔
2923
                            (const char *)max_uniq_toserver_groups_str) <= 0) {
3✔
2924
                    de_ctx->max_uniq_toserver_groups = 40;
1✔
2925

2926
                    SCLogWarning("parsing '%s' for "
1✔
2927
                                 "toserver-groups failed, using %u",
1✔
2928
                            max_uniq_toserver_groups_str, de_ctx->max_uniq_toserver_groups);
1✔
2929
                }
1✔
2930
            } else {
3✔
2931
                de_ctx->max_uniq_toserver_groups = 40;
×
2932
            }
×
2933
            SCLogConfig("toserver-groups %u", de_ctx->max_uniq_toserver_groups);
3✔
2934
            break;
3✔
2935

2936
        /* Default (or no config provided) is profile medium */
2937
        case ENGINE_PROFILE_MEDIUM:
38,895✔
2938
        case ENGINE_PROFILE_UNKNOWN:
38,895!
2939
        default:
38,895!
2940
            de_ctx->max_uniq_toclient_groups = 20;
38,895✔
2941
            de_ctx->max_uniq_toserver_groups = 40;
38,895✔
2942
            break;
38,895✔
2943
    }
38,898✔
2944

2945
    intmax_t value = 0;
38,898✔
2946
    de_ctx->inspection_recursion_limit = DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT;
38,898✔
2947
    if (SCConfGetInt("detect.inspection-recursion-limit", &value) == 1) {
38,898✔
2948
        if (value >= 0 && value <= INT_MAX) {
35,552!
2949
            de_ctx->inspection_recursion_limit = (int)value;
35,552✔
2950
        }
35,552✔
2951

2952
    /* fall back to old config parsing */
2953
    } else {
38,846✔
2954
        SCConfNode *insp_recursion_limit_node = NULL;
3,346✔
2955
        char *insp_recursion_limit = NULL;
3,346✔
2956

2957
        if (de_ctx_custom != NULL) {
3,346!
2958
            opt = NULL;
6✔
2959
            TAILQ_FOREACH(opt, &de_ctx_custom->head, next) {
16!
2960
                if (opt->val && strcmp(opt->val, "inspection-recursion-limit") != 0)
16!
2961
                    continue;
12✔
2962

2963
                insp_recursion_limit_node = SCConfNodeLookupChild(opt, opt->val);
4✔
2964
                if (insp_recursion_limit_node == NULL) {
4!
2965
                    SCLogError("Error retrieving conf "
×
2966
                               "entry for detect-engine:inspection-recursion-limit");
×
2967
                    break;
×
2968
                }
×
2969
                insp_recursion_limit = insp_recursion_limit_node->val;
4✔
2970
                SCLogDebug("Found detect-engine.inspection-recursion-limit - %s:%s",
4!
2971
                        insp_recursion_limit_node->name, insp_recursion_limit_node->val);
4✔
2972
                break;
4✔
2973
            }
4✔
2974

2975
            if (insp_recursion_limit != NULL) {
6!
2976
                if (StringParseInt32(&de_ctx->inspection_recursion_limit, 10,
3!
2977
                                     0, (const char *)insp_recursion_limit) < 0) {
3✔
2978
                    SCLogWarning("Invalid value for "
×
2979
                                 "detect-engine.inspection-recursion-limit: %s "
×
2980
                                 "resetting to %d",
×
2981
                            insp_recursion_limit, DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT);
×
2982
                    de_ctx->inspection_recursion_limit =
×
2983
                        DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT;
×
2984
                }
×
2985
            }
3✔
2986
        }
6✔
2987
    }
3,346✔
2988

2989
    if (de_ctx->inspection_recursion_limit == 0)
38,898!
2990
        de_ctx->inspection_recursion_limit = -1;
35,531✔
2991

2992
    SCLogDebug("de_ctx->inspection_recursion_limit: %d",
38,898!
2993
               de_ctx->inspection_recursion_limit);
38,898✔
2994

2995
    // default value is 4
2996
    de_ctx->guess_applayer_log_limit = 4;
38,898✔
2997
    if (SCConfGetInt("detect.stream-tx-log-limit", &value) == 1) {
38,898✔
2998
        if (value >= 0 && value <= UINT8_MAX) {
1!
2999
            de_ctx->guess_applayer_log_limit = (uint8_t)value;
1✔
3000
        } else {
1✔
3001
            SCLogWarning("Invalid value for detect-engine.stream-tx-log-limit: must be between 0 "
×
3002
                         "and 255, will default to 4");
×
3003
        }
×
3004
    }
1✔
3005
    int guess_applayer = 0;
38,898✔
3006
    if ((SCConfGetBool("detect.guess-applayer-tx", &guess_applayer)) == 1) {
38,898✔
3007
        if (guess_applayer == 1) {
9!
3008
            de_ctx->guess_applayer = true;
9✔
3009
        }
9✔
3010
    }
9✔
3011

3012
    /* parse port grouping priority settings */
3013

3014
    const char *ports = NULL;
38,898✔
3015
    (void)SCConfGet("detect.grouping.tcp-priority-ports", &ports);
38,898✔
3016
    if (ports) {
38,898!
3017
        SCLogConfig("grouping: tcp-priority-ports %s", ports);
×
3018
    } else {
38,898✔
3019
        (void)SCConfGet("detect.grouping.tcp-whitelist", &ports);
38,898✔
3020
        if (ports) {
38,898!
3021
            SCLogConfig(
×
3022
                    "grouping: tcp-priority-ports from legacy 'tcp-whitelist' setting: %s", ports);
×
3023
        } else {
38,898✔
3024
            ports = "53, 80, 139, 443, 445, 1433, 3306, 3389, 6666, 6667, 8080";
38,898✔
3025
            SCLogConfig("grouping: tcp-priority-ports (default) %s", ports);
38,898✔
3026
        }
38,898✔
3027
    }
38,898✔
3028
    if (DetectPortParse(de_ctx, &de_ctx->tcp_priorityports, ports) != 0) {
38,898!
3029
        SCLogWarning("'%s' is not a valid value "
×
3030
                     "for detect.grouping.tcp-priority-ports",
×
3031
                ports);
×
3032
    }
×
3033
    DetectPort *x = de_ctx->tcp_priorityports;
38,898✔
3034
    for ( ; x != NULL;  x = x->next) {
466,776✔
3035
        if (x->port != x->port2) {
427,878!
3036
            SCLogWarning("'%s' is not a valid value "
×
3037
                         "for detect.grouping.tcp-priority-ports: only single ports allowed",
×
3038
                    ports);
×
3039
            DetectPortCleanupList(de_ctx, de_ctx->tcp_priorityports);
×
3040
            de_ctx->tcp_priorityports = NULL;
×
3041
            break;
×
3042
        }
×
3043
    }
427,878✔
3044

3045
    ports = NULL;
38,898✔
3046
    (void)SCConfGet("detect.grouping.udp-priority-ports", &ports);
38,898✔
3047
    if (ports) {
38,898!
3048
        SCLogConfig("grouping: udp-priority-ports %s", ports);
×
3049
    } else {
38,898✔
3050
        (void)SCConfGet("detect.grouping.udp-whitelist", &ports);
38,898✔
3051
        if (ports) {
38,898!
3052
            SCLogConfig(
×
3053
                    "grouping: udp-priority-ports from legacy 'udp-whitelist' setting: %s", ports);
×
3054
        } else {
38,898✔
3055
            ports = "53, 135, 5060";
38,898✔
3056
            SCLogConfig("grouping: udp-priority-ports (default) %s", ports);
38,898✔
3057
        }
38,898✔
3058
    }
38,898✔
3059
    if (DetectPortParse(de_ctx, &de_ctx->udp_priorityports, ports) != 0) {
38,898!
3060
        SCLogWarning("'%s' is not a valid value "
×
3061
                     "for detect.grouping.udp-priority-ports",
×
3062
                ports);
×
3063
    }
×
3064
    for (x = de_ctx->udp_priorityports; x != NULL; x = x->next) {
155,592✔
3065
        if (x->port != x->port2) {
116,694!
3066
            SCLogWarning("'%s' is not a valid value "
×
3067
                         "for detect.grouping.udp-priority-ports: only single ports allowed",
×
3068
                    ports);
×
3069
            DetectPortCleanupList(de_ctx, de_ctx->udp_priorityports);
×
3070
            de_ctx->udp_priorityports = NULL;
×
3071
            break;
×
3072
        }
×
3073
    }
116,694✔
3074

3075
    de_ctx->prefilter_setting = DETECT_PREFILTER_MPM;
38,898✔
3076
    const char *pf_setting = NULL;
38,898✔
3077
    if (SCConfGet("detect.prefilter.default", &pf_setting) == 1 && pf_setting) {
38,898!
3078
        if (strcasecmp(pf_setting, "mpm") == 0) {
1,318✔
3079
            de_ctx->prefilter_setting = DETECT_PREFILTER_MPM;
1,314✔
3080
        } else if (strcasecmp(pf_setting, "auto") == 0) {
1,314!
3081
            de_ctx->prefilter_setting = DETECT_PREFILTER_AUTO;
4✔
3082
        }
4✔
3083
    }
1,318✔
3084
    switch (de_ctx->prefilter_setting) {
38,898!
3085
        case DETECT_PREFILTER_MPM:
38,894✔
3086
            SCLogConfig("prefilter engines: MPM");
38,894✔
3087
            break;
38,894✔
3088
        case DETECT_PREFILTER_AUTO:
4✔
3089
            SCLogConfig("prefilter engines: MPM and keywords");
4✔
3090
            break;
4✔
3091
    }
38,898✔
3092

3093
    return 0;
38,898✔
3094
}
38,898✔
3095

3096
void DetectEngineResetMaxSigId(DetectEngineCtx *de_ctx)
3097
{
38,893✔
3098
    de_ctx->signum = 0;
38,893✔
3099
}
38,893✔
3100

3101
static int DetectEngineThreadCtxInitGlobalKeywords(DetectEngineThreadCtx *det_ctx)
3102
{
48,481✔
3103
    const DetectEngineMasterCtx *master = &g_master_de_ctx;
48,481✔
3104

3105
    if (master->keyword_id > 0) {
48,481!
3106
        // coverity[suspicious_sizeof : FALSE]
3107
        det_ctx->global_keyword_ctxs_array = (void **)SCCalloc(master->keyword_id, sizeof(void *));
48,481✔
3108
        if (det_ctx->global_keyword_ctxs_array == NULL) {
48,481!
3109
            SCLogError("setting up thread local detect ctx");
×
3110
            return TM_ECODE_FAILED;
×
3111
        }
×
3112
        det_ctx->global_keyword_ctxs_size = master->keyword_id;
48,481✔
3113

3114
        const DetectEngineThreadKeywordCtxItem *item = master->keyword_list;
48,481✔
3115
        while (item) {
290,886✔
3116
            det_ctx->global_keyword_ctxs_array[item->id] = item->InitFunc(item->data);
242,405✔
3117
            if (det_ctx->global_keyword_ctxs_array[item->id] == NULL) {
242,405!
3118
                SCLogError("setting up thread local detect ctx "
×
3119
                           "for keyword \"%s\" failed",
×
3120
                        item->name);
×
3121
                return TM_ECODE_FAILED;
×
3122
            }
×
3123
            item = item->next;
242,405✔
3124
        }
242,405✔
3125
    }
48,481✔
3126
    return TM_ECODE_OK;
48,481✔
3127
}
48,481✔
3128

3129
static void DetectEngineThreadCtxDeinitGlobalKeywords(DetectEngineThreadCtx *det_ctx)
3130
{
48,516✔
3131
    if (det_ctx->global_keyword_ctxs_array == NULL ||
48,516✔
3132
        det_ctx->global_keyword_ctxs_size == 0) {
48,516!
3133
        return;
36✔
3134
    }
36✔
3135

3136
    const DetectEngineMasterCtx *master = &g_master_de_ctx;
48,480✔
3137
    if (master->keyword_id > 0) {
48,480!
3138
        const DetectEngineThreadKeywordCtxItem *item = master->keyword_list;
48,480✔
3139
        while (item) {
290,880✔
3140
            if (det_ctx->global_keyword_ctxs_array[item->id] != NULL)
242,400!
3141
                item->FreeFunc(det_ctx->global_keyword_ctxs_array[item->id]);
242,400✔
3142

3143
            item = item->next;
242,400✔
3144
        }
242,400✔
3145
        det_ctx->global_keyword_ctxs_size = 0;
48,480✔
3146
        SCFree(det_ctx->global_keyword_ctxs_array);
48,480✔
3147
        det_ctx->global_keyword_ctxs_array = NULL;
48,480✔
3148
    }
48,480✔
3149
}
48,480✔
3150

3151
static int DetectEngineThreadCtxInitKeywords(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx)
3152
{
48,481✔
3153
    if (de_ctx->keyword_id > 0) {
48,481✔
3154
        // coverity[suspicious_sizeof : FALSE]
3155
        det_ctx->keyword_ctxs_array = SCCalloc(de_ctx->keyword_id, sizeof(void *));
12,781✔
3156
        if (det_ctx->keyword_ctxs_array == NULL) {
12,781!
3157
            SCLogError("setting up thread local detect ctx");
×
3158
            return TM_ECODE_FAILED;
×
3159
        }
×
3160

3161
        det_ctx->keyword_ctxs_size = de_ctx->keyword_id;
12,781✔
3162

3163
        HashListTableBucket *hb = HashListTableGetListHead(de_ctx->keyword_hash);
12,781✔
3164
        for (; hb != NULL; hb = HashListTableGetListNext(hb)) {
37,956,302✔
3165
            DetectEngineThreadKeywordCtxItem *item = HashListTableGetListData(hb);
37,943,521✔
3166

3167
            det_ctx->keyword_ctxs_array[item->id] = item->InitFunc(item->data);
37,943,521✔
3168
            if (det_ctx->keyword_ctxs_array[item->id] == NULL) {
37,943,521!
3169
                SCLogError("setting up thread local detect ctx "
×
3170
                           "for keyword \"%s\" failed",
×
3171
                        item->name);
×
3172
                return TM_ECODE_FAILED;
×
3173
            }
×
3174
        }
37,943,521✔
3175
    }
12,781✔
3176
    return TM_ECODE_OK;
48,481✔
3177
}
48,481✔
3178

3179
static void DetectEngineThreadCtxDeinitKeywords(DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx)
3180
{
48,516✔
3181
    if (de_ctx->keyword_id > 0) {
48,516✔
3182
        HashListTableBucket *hb = HashListTableGetListHead(de_ctx->keyword_hash);
12,781✔
3183
        for (; hb != NULL; hb = HashListTableGetListNext(hb)) {
37,956,302✔
3184
            DetectEngineThreadKeywordCtxItem *item = HashListTableGetListData(hb);
37,943,521✔
3185

3186
            if (det_ctx->keyword_ctxs_array[item->id] != NULL)
37,943,521!
3187
                item->FreeFunc(det_ctx->keyword_ctxs_array[item->id]);
37,943,521✔
3188
        }
37,943,521✔
3189
        det_ctx->keyword_ctxs_size = 0;
12,781✔
3190
        SCFree(det_ctx->keyword_ctxs_array);
12,781✔
3191
        det_ctx->keyword_ctxs_array = NULL;
12,781✔
3192
    }
12,781✔
3193
}
48,516✔
3194

3195
/** NOTE: master MUST be locked before calling this */
3196
static TmEcode DetectEngineThreadCtxInitForMT(ThreadVars *tv, DetectEngineThreadCtx *det_ctx)
3197
{
36✔
3198
    DetectEngineMasterCtx *master = &g_master_de_ctx;
36✔
3199

3200
    DetectEngineTenantMapping *map_array = NULL;
36✔
3201
    uint32_t map_array_size = 0;
36✔
3202
    uint32_t map_cnt = 0;
36✔
3203
    uint32_t max_tenant_id = 0;
36✔
3204
    DetectEngineCtx *list = master->list;
36✔
3205

3206
    DEBUG_VALIDATE_BUG_ON(!SCMutexIsLocked(&master->lock));
36✔
3207

3208
    /* coverity[missing_lock] */
3209
    if (master->tenant_selector == TENANT_SELECTOR_UNKNOWN) {
36!
3210
        SCLogError("no tenant selector set: "
×
3211
                   "set using multi-detect.selector");
×
3212
        return TM_ECODE_FAILED;
×
3213
    }
×
3214

3215
    uint32_t tcnt = 0;
36✔
3216
    while (list) {
148✔
3217
        if (list->tenant_id > max_tenant_id)
112✔
3218
            max_tenant_id = list->tenant_id;
48✔
3219

3220
        list = list->next;
112✔
3221
        tcnt++;
112✔
3222
    }
112✔
3223

3224
    HashTable *mt_det_ctxs_hash =
36✔
3225
            HashTableInit(tcnt * 2, TenantIdHash, TenantIdCompare, TenantIdFree);
36✔
3226
    if (mt_det_ctxs_hash == NULL) {
36!
3227
        goto error;
×
3228
    }
×
3229

3230
    if (tcnt == 0) {
36!
3231
        SCLogInfo("no tenants left, or none registered yet");
×
3232
    } else {
36✔
3233
        max_tenant_id++;
36✔
3234

3235
        DetectEngineTenantMapping *map = master->tenant_mapping_list;
36✔
3236
        while (map) {
84✔
3237
            map_cnt++;
48✔
3238
            map = map->next;
48✔
3239
        }
48✔
3240

3241
        if (map_cnt > 0) {
36!
3242
            map_array_size = map_cnt + 1;
36✔
3243

3244
            map_array = SCCalloc(map_array_size, sizeof(*map_array));
36✔
3245
            if (map_array == NULL)
36!
3246
                goto error;
×
3247

3248
            /* fill the array */
3249
            map_cnt = 0;
36✔
3250
            map = master->tenant_mapping_list;
36✔
3251
            while (map) {
84✔
3252
                if (map_cnt >= map_array_size) {
48!
3253
                    goto error;
×
3254
                }
×
3255
                map_array[map_cnt].traffic_id = map->traffic_id;
48✔
3256
                map_array[map_cnt].tenant_id = map->tenant_id;
48✔
3257
                map_cnt++;
48✔
3258
                map = map->next;
48✔
3259
            }
48✔
3260

3261
        }
36✔
3262

3263
        /* set up hash for tenant lookup */
3264
        list = master->list;
36✔
3265
        while (list) {
148✔
3266
            SCLogDebug("tenant-id %u", list->tenant_id);
112!
3267
            if (list->tenant_id != 0) {
112✔
3268
                DetectEngineThreadCtx *mt_det_ctx = DetectEngineThreadCtxInitForReload(tv, list, 0);
76✔
3269
                if (mt_det_ctx == NULL)
76!
3270
                    goto error;
×
3271
                if (HashTableAdd(mt_det_ctxs_hash, mt_det_ctx, 0) != 0) {
76!
3272
                    goto error;
×
3273
                }
×
3274
            }
76✔
3275
            list = list->next;
112✔
3276
        }
112✔
3277
    }
36✔
3278

3279
    det_ctx->mt_det_ctxs_hash = mt_det_ctxs_hash;
36✔
3280
    mt_det_ctxs_hash = NULL;
36✔
3281

3282
    det_ctx->mt_det_ctxs_cnt = max_tenant_id;
36✔
3283

3284
    det_ctx->tenant_array = map_array;
36✔
3285
    det_ctx->tenant_array_size = map_array_size;
36✔
3286

3287
    switch (master->tenant_selector) {
36!
3288
        case TENANT_SELECTOR_UNKNOWN:
×
3289
            SCLogDebug("TENANT_SELECTOR_UNKNOWN");
×
3290
            break;
×
3291
        case TENANT_SELECTOR_VLAN:
36!
3292
            det_ctx->TenantGetId = DetectEngineTenantGetIdFromVlanId;
36✔
3293
            SCLogDebug("TENANT_SELECTOR_VLAN");
36!
3294
            break;
36✔
3295
        case TENANT_SELECTOR_LIVEDEV:
×
3296
            det_ctx->TenantGetId = DetectEngineTenantGetIdFromLivedev;
×
3297
            SCLogDebug("TENANT_SELECTOR_LIVEDEV");
×
3298
            break;
×
3299
        case TENANT_SELECTOR_DIRECT:
×
3300
            det_ctx->TenantGetId = DetectEngineTenantGetIdFromPcap;
×
3301
            SCLogDebug("TENANT_SELECTOR_DIRECT");
×
3302
            break;
×
3303
    }
36✔
3304

3305
    return TM_ECODE_OK;
36✔
3306
error:
×
3307
    if (map_array != NULL)
×
3308
        SCFree(map_array);
×
3309
    if (mt_det_ctxs_hash != NULL)
×
3310
        HashTableFree(mt_det_ctxs_hash);
×
3311

3312
    return TM_ECODE_FAILED;
×
3313
}
36✔
3314

3315
/** \internal
3316
 *  \brief Helper for DetectThread setup functions
3317
 */
3318
static TmEcode ThreadCtxDoInit (DetectEngineCtx *de_ctx, DetectEngineThreadCtx *det_ctx)
3319
{
48,481✔
3320
    PatternMatchThreadPrepare(&det_ctx->mtc, de_ctx->mpm_matcher);
48,481✔
3321

3322
    PmqSetup(&det_ctx->pmq);
48,481✔
3323

3324
    det_ctx->spm_thread_ctx = SpmMakeThreadCtx(de_ctx->spm_global_thread_ctx);
48,481✔
3325
    if (det_ctx->spm_thread_ctx == NULL) {
48,481!
3326
        return TM_ECODE_FAILED;
×
3327
    }
×
3328

3329
    /* DeState */
3330
    if (de_ctx->sig_array_len > 0) {
48,481✔
3331
        det_ctx->match_array_len = de_ctx->sig_array_len;
33,353✔
3332
        det_ctx->match_array = SCCalloc(det_ctx->match_array_len, sizeof(Signature *));
33,353✔
3333
        if (det_ctx->match_array == NULL) {
33,353!
3334
            return TM_ECODE_FAILED;
×
3335
        }
×
3336

3337
        RuleMatchCandidateTxArrayInit(det_ctx, de_ctx->sig_array_len);
33,353✔
3338
    }
33,353✔
3339

3340
    /* Alert processing queue */
3341
    AlertQueueInit(det_ctx);
48,481✔
3342

3343
    /* byte_extract storage */
3344
    det_ctx->byte_values = SCMalloc(sizeof(*det_ctx->byte_values) *
48,481✔
3345
                                  (de_ctx->byte_extract_max_local_id + 1));
48,481✔
3346
    if (det_ctx->byte_values == NULL) {
48,481!
3347
        return TM_ECODE_FAILED;
×
3348
    }
×
3349

3350
    /* Allocate space for base64 decoded data. */
3351
    if (de_ctx->base64_decode_max_len) {
48,481✔
3352
        det_ctx->base64_decoded = SCMalloc(de_ctx->base64_decode_max_len);
6,043✔
3353
        if (det_ctx->base64_decoded == NULL) {
6,043!
3354
            return TM_ECODE_FAILED;
×
3355
        }
×
3356
        det_ctx->base64_decoded_len = 0;
6,043✔
3357
    }
6,043✔
3358

3359
    det_ctx->inspect.buffers_size = de_ctx->buffer_type_id;
48,481✔
3360
    det_ctx->inspect.buffers = SCCalloc(det_ctx->inspect.buffers_size, sizeof(InspectionBuffer));
48,481✔
3361
    if (det_ctx->inspect.buffers == NULL) {
48,481!
3362
        return TM_ECODE_FAILED;
×
3363
    }
×
3364
    det_ctx->inspect.to_clear_queue = SCCalloc(det_ctx->inspect.buffers_size, sizeof(uint32_t));
48,481✔
3365
    if (det_ctx->inspect.to_clear_queue == NULL) {
48,481!
3366
        return TM_ECODE_FAILED;
×
3367
    }
×
3368
    det_ctx->inspect.to_clear_idx = 0;
48,481✔
3369

3370
    det_ctx->multi_inspect.buffers_size = de_ctx->buffer_type_id;
48,481✔
3371
    det_ctx->multi_inspect.buffers = SCCalloc(det_ctx->multi_inspect.buffers_size, sizeof(InspectionBufferMultipleForList));
48,481✔
3372
    if (det_ctx->multi_inspect.buffers == NULL) {
48,481!
3373
        return TM_ECODE_FAILED;
×
3374
    }
×
3375
    det_ctx->multi_inspect.to_clear_queue = SCCalloc(det_ctx->multi_inspect.buffers_size, sizeof(uint32_t));
48,481✔
3376
    if (det_ctx->multi_inspect.to_clear_queue == NULL) {
48,481!
3377
        return TM_ECODE_FAILED;
×
3378
    }
×
3379
    det_ctx->multi_inspect.to_clear_idx = 0;
48,481✔
3380

3381

3382
    DetectEngineThreadCtxInitKeywords(de_ctx, det_ctx);
48,481✔
3383
    DetectEngineThreadCtxInitGlobalKeywords(det_ctx);
48,481✔
3384
#ifdef PROFILE_RULES
3385
    SCProfilingRuleThreadSetup(de_ctx->profile_ctx, det_ctx);
3386
#endif
3387
#ifdef PROFILING
3388
    SCProfilingKeywordThreadSetup(de_ctx->profile_keyword_ctx, det_ctx);
3389
    SCProfilingPrefilterThreadSetup(de_ctx->profile_prefilter_ctx, det_ctx);
3390
    SCProfilingSghThreadSetup(de_ctx->profile_sgh_ctx, det_ctx);
3391
#endif
3392
    SC_ATOMIC_INIT(det_ctx->so_far_used_by_detect);
48,481✔
3393

3394
    return TM_ECODE_OK;
48,481✔
3395
}
48,481✔
3396

3397
/** \brief initialize thread specific detection engine context
3398
 *
3399
 *  \note there is a special case when using delayed detect. In this case the
3400
 *        function is called twice per thread. The first time the rules are not
3401
 *        yet loaded. de_ctx->delayed_detect_initialized will be 0. The 2nd
3402
 *        time they will be loaded. de_ctx->delayed_detect_initialized will be 1.
3403
 *        This is needed to do the per thread counter registration before the
3404
 *        packet runtime starts. In delayed detect mode, the first call will
3405
 *        return a NULL ptr through the data ptr.
3406
 *
3407
 *  \param tv ThreadVars for this thread
3408
 *  \param initdata pointer to de_ctx
3409
 *  \param data[out] pointer to store our thread detection ctx
3410
 *
3411
 *  \retval TM_ECODE_OK if all went well
3412
 *  \retval TM_ECODE_FAILED on serious errors
3413
 */
3414
TmEcode DetectEngineThreadCtxInit(ThreadVars *tv, void *initdata, void **data)
3415
{
12,858✔
3416
    DetectEngineThreadCtx *det_ctx = SCCalloc(1, sizeof(DetectEngineThreadCtx));
12,858✔
3417
    if (unlikely(det_ctx == NULL))
12,858!
3418
        return TM_ECODE_FAILED;
×
3419

3420
    det_ctx->tv = tv;
12,858✔
3421
    det_ctx->de_ctx = DetectEngineGetCurrent();
12,858✔
3422
    if (det_ctx->de_ctx == NULL) {
12,858!
3423
#ifdef UNITTESTS
827✔
3424
        if (RunmodeIsUnittests()) {
827✔
3425
            det_ctx->de_ctx = (DetectEngineCtx *)initdata;
827✔
3426
        } else {
827✔
3427
            DetectEngineThreadCtxDeinit(tv, det_ctx);
3428
            return TM_ECODE_FAILED;
3429
        }
3430
#else
3431
        DetectEngineThreadCtxDeinit(tv, det_ctx);
3432
        return TM_ECODE_FAILED;
3433
#endif
3434
    }
827✔
3435

3436
    if (det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
12,858✔
3437
        det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_TENANT)
12,858!
3438
    {
12,850✔
3439
        if (ThreadCtxDoInit(det_ctx->de_ctx, det_ctx) != TM_ECODE_OK) {
12,850!
3440
            DetectEngineThreadCtxDeinit(tv, det_ctx);
×
3441
            return TM_ECODE_FAILED;
×
3442
        }
×
3443
    }
12,850✔
3444

3445
    /** alert counter setup */
3446
    det_ctx->counter_alerts = StatsRegisterCounter("detect.alert", &tv->stats);
12,858✔
3447
    det_ctx->counter_alerts_overflow =
12,858✔
3448
            StatsRegisterCounter("detect.alert_queue_overflow", &tv->stats);
12,858✔
3449
    det_ctx->counter_alerts_suppressed =
12,858✔
3450
            StatsRegisterCounter("detect.alerts_suppressed", &tv->stats);
12,858✔
3451

3452
    /* Register counter for Lua rule errors. */
3453
    det_ctx->lua_rule_errors = StatsRegisterCounter("detect.lua.errors", &tv->stats);
12,858✔
3454

3455
    /* Register a counter for Lua blocked function attempts. */
3456
    det_ctx->lua_blocked_function_errors =
12,858✔
3457
            StatsRegisterCounter("detect.lua.blocked_function_errors", &tv->stats);
12,858✔
3458

3459
    /* Register a counter for Lua instruction limit errors. */
3460
    det_ctx->lua_instruction_limit_errors =
12,858✔
3461
            StatsRegisterCounter("detect.lua.instruction_limit_errors", &tv->stats);
12,858✔
3462

3463
    /* Register a counter for Lua memory limit errors. */
3464
    det_ctx->lua_memory_limit_errors =
12,858✔
3465
            StatsRegisterCounter("detect.lua.memory_limit_errors", &tv->stats);
12,858✔
3466

3467
    det_ctx->json_content = NULL;
12,858✔
3468
    det_ctx->json_content_capacity = 0;
12,858✔
3469
    det_ctx->json_content_len = 0;
12,858✔
3470

3471
#ifdef PROFILING
3472
    det_ctx->counter_mpm_list = StatsRegisterAvgCounter("detect.mpm_list", &tv->stats);
3473
    det_ctx->counter_match_list = StatsRegisterAvgCounter("detect.match_list", &tv->stats);
3474
#endif
3475

3476
    if (DetectEngineMultiTenantEnabled()) {
12,858✔
3477
        DetectEngineMasterCtx *master = &g_master_de_ctx;
8✔
3478
        SCMutexLock(&master->lock);
8✔
3479
        if (DetectEngineThreadCtxInitForMT(tv, det_ctx) != TM_ECODE_OK) {
8!
3480
            DetectEngineThreadCtxDeinit(tv, det_ctx);
×
3481
            SCMutexUnlock(&master->lock);
×
3482
            return TM_ECODE_FAILED;
×
3483
        }
×
3484
        SCMutexUnlock(&master->lock);
8✔
3485
    }
8✔
3486

3487
    /* pass thread data back to caller */
3488
    *data = (void *)det_ctx;
12,858✔
3489

3490
    return TM_ECODE_OK;
12,858✔
3491
}
12,858✔
3492

3493
/**
3494
 * \internal
3495
 * \brief initialize a det_ctx for reload cases
3496
 * \param new_de_ctx the new detection engine
3497
 * \param mt flag to indicate if MT should be set up for this det_ctx
3498
 *           this should only be done for the 'root' det_ctx
3499
 *
3500
 * \retval det_ctx detection engine thread ctx or NULL in case of error
3501
 */
3502
DetectEngineThreadCtx *DetectEngineThreadCtxInitForReload(
3503
        ThreadVars *tv, DetectEngineCtx *new_de_ctx, int mt)
3504
{
35,659✔
3505
    DetectEngineThreadCtx *det_ctx = SCCalloc(1, sizeof(DetectEngineThreadCtx));
35,659✔
3506
    if (unlikely(det_ctx == NULL))
35,659!
3507
        return NULL;
×
3508

3509
    det_ctx->tenant_id = new_de_ctx->tenant_id;
35,659✔
3510
    det_ctx->tv = tv;
35,659✔
3511
    det_ctx->de_ctx = DetectEngineReference(new_de_ctx);
35,659✔
3512
    if (det_ctx->de_ctx == NULL) {
35,659!
3513
        SCFree(det_ctx);
×
3514
        return NULL;
×
3515
    }
×
3516

3517
    /* most of the init happens here */
3518
    if (det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
35,659!
3519
        det_ctx->de_ctx->type == DETECT_ENGINE_TYPE_TENANT)
35,659!
3520
    {
35,631✔
3521
        if (ThreadCtxDoInit(det_ctx->de_ctx, det_ctx) != TM_ECODE_OK) {
35,631!
3522
            DetectEngineDeReference(&det_ctx->de_ctx);
×
3523
            SCFree(det_ctx);
×
3524
            return NULL;
×
3525
        }
×
3526
    }
35,631✔
3527

3528
    /** alert counter setup */
3529
    det_ctx->counter_alerts = StatsRegisterCounter("detect.alert", &tv->stats);
35,659✔
3530
    det_ctx->counter_alerts_overflow =
35,659✔
3531
            StatsRegisterCounter("detect.alert_queue_overflow", &tv->stats);
35,659✔
3532
    det_ctx->counter_alerts_suppressed =
35,659✔
3533
            StatsRegisterCounter("detect.alerts_suppressed", &tv->stats);
35,659✔
3534
#ifdef PROFILING
3535
    det_ctx->counter_mpm_list = StatsRegisterAvgCounter("detect.mpm_list", &tv->stats);
3536
    det_ctx->counter_match_list = StatsRegisterAvgCounter("detect.match_list", &tv->stats);
3537
#endif
3538

3539
    if (mt && DetectEngineMultiTenantEnabledWithLock()) {
35,659!
3540
        if (DetectEngineThreadCtxInitForMT(tv, det_ctx) != TM_ECODE_OK) {
28!
3541
            DetectEngineDeReference(&det_ctx->de_ctx);
×
3542
            SCFree(det_ctx);
×
3543
            return NULL;
×
3544
        }
×
3545
    }
28✔
3546

3547
    return det_ctx;
35,659✔
3548
}
35,659✔
3549

3550
static void DetectEngineThreadCtxFree(DetectEngineThreadCtx *det_ctx)
3551
{
48,516✔
3552
#if  DEBUG
3553
    SCLogDebug("PACKET PKT_STREAM_ADD: %"PRIu64, det_ctx->pkt_stream_add_cnt);
3554

3555
    SCLogDebug("PAYLOAD MPM %"PRIu64"/%"PRIu64, det_ctx->payload_mpm_cnt, det_ctx->payload_mpm_size);
3556
    SCLogDebug("STREAM  MPM %"PRIu64"/%"PRIu64, det_ctx->stream_mpm_cnt, det_ctx->stream_mpm_size);
3557

3558
    SCLogDebug("PAYLOAD SIG %"PRIu64"/%"PRIu64, det_ctx->payload_persig_cnt, det_ctx->payload_persig_size);
3559
    SCLogDebug("STREAM  SIG %"PRIu64"/%"PRIu64, det_ctx->stream_persig_cnt, det_ctx->stream_persig_size);
3560
#endif
3561

3562
    if (det_ctx->tenant_array != NULL) {
48,516✔
3563
        SCFree(det_ctx->tenant_array);
36✔
3564
        det_ctx->tenant_array = NULL;
36✔
3565
    }
36✔
3566

3567
#ifdef PROFILE_RULES
3568
    SCProfilingRuleThreadCleanup(det_ctx);
3569
#endif
3570
#ifdef PROFILING
3571
    SCProfilingKeywordThreadCleanup(det_ctx);
3572
    SCProfilingPrefilterThreadCleanup(det_ctx);
3573
    SCProfilingSghThreadCleanup(det_ctx);
3574
#endif
3575

3576
    /** \todo get rid of this static */
3577
    if (det_ctx->de_ctx != NULL) {
48,516!
3578
        PatternMatchThreadDestroy(&det_ctx->mtc, det_ctx->de_ctx->mpm_matcher);
48,516✔
3579
    }
48,516✔
3580

3581
    PmqFree(&det_ctx->pmq);
48,516✔
3582

3583
    if (det_ctx->spm_thread_ctx != NULL) {
48,516✔
3584
        SpmDestroyThreadCtx(det_ctx->spm_thread_ctx);
48,480✔
3585
    }
48,480✔
3586
    if (det_ctx->match_array != NULL)
48,516✔
3587
        SCFree(det_ctx->match_array);
33,353✔
3588

3589
    RuleMatchCandidateTxArrayFree(det_ctx);
48,516✔
3590

3591
    AlertQueueFree(det_ctx);
48,516✔
3592

3593
    if (det_ctx->post_rule_work_queue.q)
48,516✔
3594
        SCFree(det_ctx->post_rule_work_queue.q);
18✔
3595

3596
    if (det_ctx->byte_values != NULL)
48,516✔
3597
        SCFree(det_ctx->byte_values);
48,480✔
3598

3599
    /* Decoded base64 data. */
3600
    if (det_ctx->base64_decoded != NULL) {
48,516✔
3601
        SCFree(det_ctx->base64_decoded);
6,043✔
3602
    }
6,043✔
3603

3604
    if (det_ctx->inspect.buffers) {
48,516✔
3605
        for (uint32_t i = 0; i < det_ctx->inspect.buffers_size; i++) {
20,384,582✔
3606
            InspectionBufferFree(&det_ctx->inspect.buffers[i]);
20,336,102✔
3607
        }
20,336,102✔
3608
        SCFree(det_ctx->inspect.buffers);
48,480✔
3609
    }
48,480✔
3610
    if (det_ctx->inspect.to_clear_queue) {
48,516✔
3611
        SCFree(det_ctx->inspect.to_clear_queue);
48,480✔
3612
    }
48,480✔
3613
    if (det_ctx->multi_inspect.buffers) {
48,516✔
3614
        for (uint32_t i = 0; i < det_ctx->multi_inspect.buffers_size; i++) {
20,384,582✔
3615
            InspectionBufferMultipleForList *fb = &det_ctx->multi_inspect.buffers[i];
20,336,102✔
3616
            for (uint32_t x = 0; x < fb->size; x++) {
20,344,698✔
3617
                InspectionBufferFree(&fb->inspection_buffers[x]);
8,596✔
3618
            }
8,596✔
3619
            SCFree(fb->inspection_buffers);
20,336,102✔
3620
        }
20,336,102✔
3621
        SCFree(det_ctx->multi_inspect.buffers);
48,480✔
3622
    }
48,480✔
3623
    if (det_ctx->multi_inspect.to_clear_queue) {
48,516✔
3624
        SCFree(det_ctx->multi_inspect.to_clear_queue);
48,480✔
3625
    }
48,480✔
3626

3627
    DetectEngineThreadCtxDeinitGlobalKeywords(det_ctx);
48,516✔
3628
    if (det_ctx->de_ctx != NULL) {
48,516!
3629
        DetectEngineThreadCtxDeinitKeywords(det_ctx->de_ctx, det_ctx);
48,516✔
3630
#ifdef UNITTESTS
852✔
3631
        if (!RunmodeIsUnittests() || det_ctx->de_ctx->ref_cnt > 0)
852✔
3632
            DetectEngineDeReference(&det_ctx->de_ctx);
25✔
3633
#else
3634
        DetectEngineDeReference(&det_ctx->de_ctx);
47,664✔
3635
#endif
47,664✔
3636
    }
48,516✔
3637

3638
    if (det_ctx->json_content) {
48,516✔
3639
        SCFree(det_ctx->json_content);
11✔
3640
        det_ctx->json_content = NULL;
11✔
3641
        det_ctx->json_content_capacity = 0;
11✔
3642
    }
11✔
3643

3644
    SCAppLayerDecoderEventsFreeEvents(&det_ctx->decoder_events);
48,516✔
3645
    PrefilterPktNonPFStatsDump();
48,516✔
3646
    SCFree(det_ctx);
48,516✔
3647

3648
    ThresholdCacheThreadFree();
48,516✔
3649
}
48,516✔
3650

3651
TmEcode DetectEngineThreadCtxDeinit(ThreadVars *tv, void *data)
3652
{
48,440✔
3653
    DetectEngineThreadCtx *det_ctx = (DetectEngineThreadCtx *)data;
48,440✔
3654

3655
    if (det_ctx == NULL) {
48,440!
3656
        SCLogWarning("argument \"data\" NULL");
×
3657
        return TM_ECODE_OK;
×
3658
    }
×
3659

3660
    if (det_ctx->mt_det_ctxs_hash != NULL) {
48,440✔
3661
        HashTableFree(det_ctx->mt_det_ctxs_hash);
36✔
3662
        det_ctx->mt_det_ctxs_hash = NULL;
36✔
3663
    }
36✔
3664
    DetectEngineThreadCtxFree(det_ctx);
48,440✔
3665

3666
    return TM_ECODE_OK;
48,440✔
3667
}
48,440✔
3668

3669
static uint32_t DetectKeywordCtxHashFunc(HashListTable *ht, void *data, uint16_t datalen)
3670
{
758,639✔
3671
    DetectEngineThreadKeywordCtxItem *ctx = data;
758,639✔
3672
    const char *name = ctx->name;
758,639✔
3673
    uint64_t hash =
758,639✔
3674
            StringHashDjb2((const uint8_t *)name, (uint32_t)strlen(name)) + (ptrdiff_t)ctx->data;
758,639✔
3675
    hash %= ht->array_size;
758,639✔
3676
    return (uint32_t)hash;
758,639✔
3677
}
758,639✔
3678

3679
static char DetectKeywordCtxCompareFunc(void *data1, uint16_t len1, void *data2, uint16_t len2)
3680
{
485,530✔
3681
    DetectEngineThreadKeywordCtxItem *ctx1 = data1;
485,530✔
3682
    DetectEngineThreadKeywordCtxItem *ctx2 = data2;
485,530✔
3683
    const char *name1 = ctx1->name;
485,530✔
3684
    const char *name2 = ctx2->name;
485,530✔
3685
    return (strcmp(name1, name2) == 0 && ctx1->data == ctx2->data);
485,530!
3686
}
485,530✔
3687

3688
static void DetectKeywordCtxFreeFunc(void *ptr)
3689
{
355,948✔
3690
    SCFree(ptr);
355,948✔
3691
}
355,948✔
3692

3693
/** \brief Register Thread keyword context Funcs
3694
 *
3695
 *  \param de_ctx detection engine to register in
3696
 *  \param name keyword name for error printing
3697
 *  \param InitFunc function ptr
3698
 *  \param data keyword init data to pass to Func. Can be NULL.
3699
 *  \param FreeFunc function ptr
3700
 *  \param mode 0 normal (ctx per keyword instance) 1 shared (one ctx per det_ct)
3701
 *
3702
 *  \retval id for retrieval of ctx at runtime
3703
 *  \retval -1 on error
3704
 *
3705
 *  \note make sure "data" remains valid and it free'd elsewhere. It's
3706
 *        recommended to store it in the keywords global ctx so that
3707
 *        it's freed when the de_ctx is freed.
3708
 */
3709
int DetectRegisterThreadCtxFuncs(DetectEngineCtx *de_ctx, const char *name, void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *), int mode)
3710
{
355,959✔
3711
    BUG_ON(de_ctx == NULL || InitFunc == NULL || FreeFunc == NULL);
355,959!
3712

3713
    if (de_ctx->keyword_hash == NULL) {
355,959✔
3714
        de_ctx->keyword_hash = HashListTableInit(4096, // TODO
7,020✔
3715
                DetectKeywordCtxHashFunc, DetectKeywordCtxCompareFunc, DetectKeywordCtxFreeFunc);
7,020✔
3716
        BUG_ON(de_ctx->keyword_hash == NULL);
7,020!
3717
    }
7,020✔
3718

3719
    if (mode) {
355,959✔
3720
        DetectEngineThreadKeywordCtxItem search = { .data = data, .name = name };
471✔
3721

3722
        DetectEngineThreadKeywordCtxItem *item =
471✔
3723
                HashListTableLookup(de_ctx->keyword_hash, (void *)&search, 0);
471✔
3724
        if (item)
471!
3725
            return item->id;
×
3726

3727
        /* fall through */
3728
    }
471✔
3729

3730
    DetectEngineThreadKeywordCtxItem *item = SCCalloc(1, sizeof(DetectEngineThreadKeywordCtxItem));
355,959✔
3731
    if (unlikely(item == NULL))
355,959!
3732
        return -1;
×
3733

3734
    item->InitFunc = InitFunc;
355,959✔
3735
    item->FreeFunc = FreeFunc;
355,959✔
3736
    item->data = data;
355,959✔
3737
    item->name = name;
355,959✔
3738
    item->id = de_ctx->keyword_id++;
355,959✔
3739

3740
    if (HashListTableAdd(de_ctx->keyword_hash, (void *)item, 0) < 0) {
355,959!
3741
        SCFree(item);
×
3742
        return -1;
×
3743
    }
×
3744
    return item->id;
355,959✔
3745
}
355,959✔
3746

3747
/** \brief Remove Thread keyword context registration
3748
 *
3749
 *  \param de_ctx detection engine to deregister from
3750
 *  \param det_ctx detection engine thread context to deregister from
3751
 *  \param data keyword init data to pass to Func. Can be NULL.
3752
 *  \param name keyword name for error printing
3753
 *
3754
 *  \retval 1 Item unregistered
3755
 *  \retval 0 otherwise
3756
 *
3757
 *  \note make sure "data" remains valid and it free'd elsewhere. It's
3758
 *        recommended to store it in the keywords global ctx so that
3759
 *        it's freed when the de_ctx is freed.
3760
 */
3761
int DetectUnregisterThreadCtxFuncs(DetectEngineCtx *de_ctx, void *data, const char *name)
3762
{
414,366✔
3763
    /* might happen if we call this before a call to *Register* */
3764
    if (de_ctx->keyword_hash == NULL)
414,366✔
3765
        return 1;
12,157✔
3766
    DetectEngineThreadKeywordCtxItem remove = { .data = data, .name = name };
402,209✔
3767
    if (HashListTableRemove(de_ctx->keyword_hash, (void *)&remove, 0) == 0)
402,209!
3768
        return 1;
355,465✔
3769
    return 0;
46,744✔
3770
}
402,209✔
3771
/** \brief Retrieve thread local keyword ctx by id
3772
 *
3773
 *  \param det_ctx detection engine thread ctx to retrieve the ctx from
3774
 *  \param id id of the ctx returned by DetectRegisterThreadCtxInitFunc at
3775
 *            keyword init.
3776
 *
3777
 *  \retval ctx or NULL on error
3778
 */
3779
void *DetectThreadCtxGetKeywordThreadCtx(DetectEngineThreadCtx *det_ctx, int id)
3780
{
16,761✔
3781
    if (id < 0 || id > det_ctx->keyword_ctxs_size || det_ctx->keyword_ctxs_array == NULL)
16,762!
3782
        return NULL;
×
3783

3784
    return det_ctx->keyword_ctxs_array[id];
16,761✔
3785
}
16,761✔
3786

3787

3788
/** \brief Register Thread keyword context Funcs (Global)
3789
 *
3790
 *  IDs stay static over reloads and between tenants
3791
 *
3792
 *  \param name keyword name for error printing
3793
 *  \param InitFunc function ptr
3794
 *  \param FreeFunc function ptr
3795
 *
3796
 *  \retval id for retrieval of ctx at runtime
3797
 *  \retval -1 on error
3798
 */
3799
int DetectRegisterThreadCtxGlobalFuncs(const char *name,
3800
        void *(*InitFunc)(void *), void *data, void (*FreeFunc)(void *))
3801
{
10,965✔
3802
    int id;
10,965✔
3803
    BUG_ON(InitFunc == NULL || FreeFunc == NULL);
10,965!
3804

3805
    DetectEngineMasterCtx *master = &g_master_de_ctx;
10,965✔
3806

3807
    /* if already registered, return existing id */
3808
    DetectEngineThreadKeywordCtxItem *item = master->keyword_list;
10,965✔
3809
    while (item != NULL) {
32,895✔
3810
        if (strcmp(name, item->name) == 0) {
21,930!
3811
            id = item->id;
×
3812
            return id;
×
3813
        }
×
3814

3815
        item = item->next;
21,930✔
3816
    }
21,930✔
3817

3818
    item = SCCalloc(1, sizeof(*item));
10,965✔
3819
    if (unlikely(item == NULL)) {
10,965!
3820
        return -1;
×
3821
    }
×
3822
    item->InitFunc = InitFunc;
10,965✔
3823
    item->FreeFunc = FreeFunc;
10,965✔
3824
    item->name = name;
10,965✔
3825
    item->data = data;
10,965✔
3826

3827
    item->next = master->keyword_list;
10,965✔
3828
    master->keyword_list = item;
10,965✔
3829
    item->id = master->keyword_id++;
10,965✔
3830

3831
    id = item->id;
10,965✔
3832
    return id;
10,965✔
3833
}
10,965✔
3834

3835
/** \brief Retrieve thread local keyword ctx by id
3836
 *
3837
 *  \param det_ctx detection engine thread ctx to retrieve the ctx from
3838
 *  \param id id of the ctx returned by DetectRegisterThreadCtxInitFunc at
3839
 *            keyword init.
3840
 *
3841
 *  \retval ctx or NULL on error
3842
 */
3843
void *DetectThreadCtxGetGlobalKeywordThreadCtx(DetectEngineThreadCtx *det_ctx, int id)
3844
{
16,791✔
3845
    if (id < 0 || id > det_ctx->global_keyword_ctxs_size ||
16,792!
3846
        det_ctx->global_keyword_ctxs_array == NULL) {
16,794!
3847
        return NULL;
×
3848
    }
×
3849

3850
    return det_ctx->global_keyword_ctxs_array[id];
16,791✔
3851
}
16,791✔
3852

3853
/** \brief Check if detection is enabled
3854
 *  \retval bool true or false */
3855
int DetectEngineEnabled(void)
3856
{
15,470✔
3857
    DetectEngineMasterCtx *master = &g_master_de_ctx;
15,470✔
3858
    SCMutexLock(&master->lock);
15,470✔
3859

3860
    if (master->list == NULL) {
15,470✔
3861
        SCMutexUnlock(&master->lock);
1,825✔
3862
        return 0;
1,825✔
3863
    }
1,825✔
3864

3865
    SCMutexUnlock(&master->lock);
13,645✔
3866
    return 1;
13,645✔
3867
}
15,470✔
3868

3869
uint32_t DetectEngineGetVersion(void)
3870
{
38,899✔
3871
    uint32_t version;
38,899✔
3872
    DetectEngineMasterCtx *master = &g_master_de_ctx;
38,899✔
3873
    SCMutexLock(&master->lock);
38,899✔
3874
    version = master->version;
38,899✔
3875
    SCMutexUnlock(&master->lock);
38,899✔
3876
    return version;
38,899✔
3877
}
38,899✔
3878

3879
void DetectEngineBumpVersion(void)
3880
{
37,291✔
3881
    DetectEngineMasterCtx *master = &g_master_de_ctx;
37,291✔
3882
    SCMutexLock(&master->lock);
37,291✔
3883
    master->version++;
37,291✔
3884
    SCLogDebug("master version now %u", master->version);
37,291!
3885
    SCMutexUnlock(&master->lock);
37,291✔
3886
}
37,291✔
3887

3888
DetectEngineCtx *DetectEngineGetCurrent(void)
3889
{
126,369✔
3890
    DetectEngineMasterCtx *master = &g_master_de_ctx;
126,369✔
3891
    SCMutexLock(&master->lock);
126,369✔
3892

3893
    DetectEngineCtx *de_ctx = master->list;
126,369✔
3894
    while (de_ctx) {
126,385✔
3895
        if (de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
124,991✔
3896
            de_ctx->type == DETECT_ENGINE_TYPE_DD_STUB ||
124,991!
3897
            de_ctx->type == DETECT_ENGINE_TYPE_MT_STUB)
124,991!
3898
        {
124,975✔
3899
            de_ctx->ref_cnt++;
124,975✔
3900
            SCLogDebug("de_ctx %p ref_cnt %u", de_ctx, de_ctx->ref_cnt);
124,975!
3901
            SCMutexUnlock(&master->lock);
124,975✔
3902
            return de_ctx;
124,975✔
3903
        }
124,975✔
3904
        de_ctx = de_ctx->next;
16✔
3905
    }
16✔
3906

3907
    SCMutexUnlock(&master->lock);
1,394✔
3908
    return NULL;
1,394✔
3909
}
126,369✔
3910

3911
DetectEngineCtx *DetectEngineReference(DetectEngineCtx *de_ctx)
3912
{
35,659✔
3913
    if (de_ctx == NULL)
35,659!
3914
        return NULL;
×
3915
    de_ctx->ref_cnt++;
35,659✔
3916
    return de_ctx;
35,659✔
3917
}
35,659✔
3918

3919
static bool DetectEngineMultiTenantEnabledWithLock(void)
3920
{
86,597✔
3921
    DetectEngineMasterCtx *master = &g_master_de_ctx;
86,597✔
3922
    return master->multi_tenant_enabled;
86,597✔
3923
}
86,597✔
3924

3925
bool DetectEngineMultiTenantEnabled(void)
3926
{
51,014✔
3927
    DetectEngineMasterCtx *master = &g_master_de_ctx;
51,014✔
3928
    SCMutexLock(&master->lock);
51,014✔
3929
    bool enabled = DetectEngineMultiTenantEnabledWithLock();
51,014✔
3930
    SCMutexUnlock(&master->lock);
51,014✔
3931
    return enabled;
51,014✔
3932
}
51,014✔
3933

3934
/** \internal
3935
 *  \brief load a tenant from a yaml file
3936
 *
3937
 *  \param tenant_id the tenant id by which the config is known
3938
 *  \param filename full path of a yaml file
3939
 *  \param loader_id id of loader thread or -1
3940
 *
3941
 *  \retval 0 ok
3942
 *  \retval -1 failed
3943
 */
3944
static int DetectEngineMultiTenantLoadTenant(uint32_t tenant_id, const char *filename, int loader_id)
3945
{
15✔
3946
    DetectEngineCtx *de_ctx = NULL;
15✔
3947
    char prefix[64];
15✔
3948

3949
    snprintf(prefix, sizeof(prefix), "multi-detect.%u", tenant_id);
15✔
3950

3951
    SCStat st;
15✔
3952
    if (SCStatFn(filename, &st) != 0) {
15!
3953
        SCLogError("failed to stat file %s", filename);
×
3954
        goto error;
×
3955
    }
×
3956

3957
    de_ctx = DetectEngineGetByTenantId(tenant_id);
15✔
3958
    if (de_ctx != NULL) {
15!
3959
        SCLogError("tenant %u already registered", tenant_id);
×
3960
        DetectEngineDeReference(&de_ctx);
×
3961
        goto error;
×
3962
    }
×
3963

3964
    SCConfNode *node = SCConfGetNode(prefix);
15✔
3965
    if (node == NULL) {
15!
3966
        SCLogError("failed to properly setup yaml %s", filename);
×
3967
        goto error;
×
3968
    }
×
3969

3970
    de_ctx = DetectEngineCtxInitWithPrefix(prefix, tenant_id);
15✔
3971
    if (de_ctx == NULL) {
15!
3972
        SCLogError("initializing detection engine "
×
3973
                   "context failed.");
×
3974
        goto error;
×
3975
    }
×
3976
    SCLogDebug("de_ctx %p with prefix %s", de_ctx, de_ctx->config_prefix);
15!
3977

3978
    de_ctx->type = DETECT_ENGINE_TYPE_TENANT;
15✔
3979
    de_ctx->tenant_id = tenant_id;
15✔
3980
    de_ctx->loader_id = loader_id;
15✔
3981
    de_ctx->tenant_path = SCStrdup(filename);
15✔
3982
    if (de_ctx->tenant_path == NULL) {
15!
3983
        SCLogError("Failed to duplicate path");
×
3984
        goto error;
×
3985
    }
×
3986

3987
    if (SigLoadSignatures(de_ctx, NULL, false) < 0) {
15!
3988
        SCLogError("Loading signatures failed.");
×
3989
        goto error;
×
3990
    }
×
3991

3992
    DetectEngineAddToMaster(de_ctx);
15✔
3993

3994
    return 0;
15✔
3995

3996
error:
×
3997
    if (de_ctx != NULL) {
×
3998
        DetectEngineCtxFree(de_ctx);
×
3999
    }
×
4000
    return -1;
×
4001
}
15✔
4002

4003
static int DetectEngineMultiTenantReloadTenant(uint32_t tenant_id, const char *filename, int reload_cnt)
4004
{
6✔
4005
    DetectEngineCtx *old_de_ctx = DetectEngineGetByTenantId(tenant_id);
6✔
4006
    if (old_de_ctx == NULL) {
6!
4007
        SCLogError("tenant detect engine not found");
×
4008
        return -1;
×
4009
    }
×
4010

4011
    if (filename == NULL)
6!
4012
        filename = old_de_ctx->tenant_path;
6✔
4013

4014
    char prefix[64];
6✔
4015
    snprintf(prefix, sizeof(prefix), "multi-detect.%u.reload.%d", tenant_id, reload_cnt);
6✔
4016
    reload_cnt++;
6✔
4017
    SCLogDebug("prefix %s", prefix);
6!
4018

4019
    if (SCConfYamlLoadFileWithPrefix(filename, prefix) != 0) {
6!
4020
        SCLogError("failed to load yaml");
×
4021
        goto error;
×
4022
    }
×
4023

4024
    SCConfNode *node = SCConfGetNode(prefix);
6✔
4025
    if (node == NULL) {
6!
4026
        SCLogError("failed to properly setup yaml %s", filename);
×
4027
        goto error;
×
4028
    }
×
4029

4030
    DetectEngineCtx *new_de_ctx = DetectEngineCtxInitWithPrefix(prefix, tenant_id);
6✔
4031
    if (new_de_ctx == NULL) {
6!
4032
        SCLogError("initializing detection engine "
×
4033
                   "context failed.");
×
4034
        goto error;
×
4035
    }
×
4036
    SCLogDebug("de_ctx %p with prefix %s", new_de_ctx, new_de_ctx->config_prefix);
6!
4037

4038
    new_de_ctx->type = DETECT_ENGINE_TYPE_TENANT;
6✔
4039
    new_de_ctx->tenant_id = tenant_id;
6✔
4040
    new_de_ctx->loader_id = old_de_ctx->loader_id;
6✔
4041
    new_de_ctx->tenant_path = SCStrdup(filename);
6✔
4042
    if (new_de_ctx->tenant_path == NULL) {
6!
4043
        SCLogError("Failed to duplicate path");
×
4044
        goto new_de_ctx_error;
×
4045
    }
×
4046

4047
    if (SigLoadSignatures(new_de_ctx, NULL, false) < 0) {
6!
4048
        SCLogError("Loading signatures failed.");
×
4049
        goto new_de_ctx_error;
×
4050
    }
×
4051

4052
    DetectEngineAddToMaster(new_de_ctx);
6✔
4053

4054
    /* move to free list */
4055
    DetectEngineMoveToFreeList(old_de_ctx);
6✔
4056
    DetectEngineDeReference(&old_de_ctx);
6✔
4057
    return 0;
6✔
4058

4059
new_de_ctx_error:
×
4060
    DetectEngineCtxFree(new_de_ctx);
×
4061

4062
error:
×
4063
    DetectEngineDeReference(&old_de_ctx);
×
4064
    return -1;
×
4065
}
×
4066

4067

4068
typedef struct TenantLoaderCtx_ {
4069
    uint32_t tenant_id;
4070
    int reload_cnt; /**< used by reload */
4071
    char *yaml;     /**< heap alloc'd copy of file path for the yaml */
4072
} TenantLoaderCtx;
4073

4074
static void DetectLoaderFreeTenant(void *ctx)
4075
{
21✔
4076
    TenantLoaderCtx *t = (TenantLoaderCtx *)ctx;
21✔
4077
    if (t->yaml != NULL) {
21!
4078
        SCFree(t->yaml);
15✔
4079
    }
15✔
4080
    SCFree(t);
21✔
4081
}
21✔
4082

4083
static int DetectLoaderFuncLoadTenant(void *vctx, int loader_id)
4084
{
15✔
4085
    TenantLoaderCtx *ctx = (TenantLoaderCtx *)vctx;
15✔
4086

4087
    SCLogDebug("loader %d", loader_id);
15!
4088
    if (DetectEngineMultiTenantLoadTenant(ctx->tenant_id, ctx->yaml, loader_id) != 0) {
15!
4089
        return -1;
×
4090
    }
×
4091
    return 0;
15✔
4092
}
15✔
4093

4094
static int DetectLoaderSetupLoadTenant(uint32_t tenant_id, const char *yaml)
4095
{
15✔
4096
    TenantLoaderCtx *t = SCCalloc(1, sizeof(*t));
15✔
4097
    if (t == NULL)
15!
4098
        return -ENOMEM;
×
4099

4100
    t->tenant_id = tenant_id;
15✔
4101
    t->yaml = SCStrdup(yaml);
15✔
4102
    if (t->yaml == NULL) {
15!
4103
        SCFree(t);
×
4104
        return -ENOMEM;
×
4105
    }
×
4106

4107
    return DetectLoaderQueueTask(-1, DetectLoaderFuncLoadTenant, t, DetectLoaderFreeTenant);
15✔
4108
}
15✔
4109

4110
static int DetectLoaderFuncReloadTenant(void *vctx, int loader_id)
4111
{
6✔
4112
    TenantLoaderCtx *ctx = (TenantLoaderCtx *)vctx;
6✔
4113

4114
    SCLogDebug("loader_id %d", loader_id);
6!
4115

4116
    if (DetectEngineMultiTenantReloadTenant(ctx->tenant_id, ctx->yaml, ctx->reload_cnt) != 0) {
6!
4117
        return -1;
×
4118
    }
×
4119
    return 0;
6✔
4120
}
6✔
4121

4122
static int DetectLoaderSetupReloadTenants(const int reload_cnt)
4123
{
3✔
4124
    int ret = 0;
3✔
4125
    DetectEngineMasterCtx *master = &g_master_de_ctx;
3✔
4126
    SCMutexLock(&master->lock);
3✔
4127

4128
    DetectEngineCtx *de_ctx = master->list;
3✔
4129
    while (de_ctx) {
12!
4130
        if (de_ctx->type == DETECT_ENGINE_TYPE_TENANT) {
9!
4131
            TenantLoaderCtx *t = SCCalloc(1, sizeof(*t));
6✔
4132
            if (t == NULL) {
6!
4133
                ret = -1;
×
4134
                goto error;
×
4135
            }
×
4136
            t->tenant_id = de_ctx->tenant_id;
6✔
4137
            t->reload_cnt = reload_cnt;
6✔
4138
            int loader_id = de_ctx->loader_id;
6✔
4139

4140
            int r = DetectLoaderQueueTask(
6✔
4141
                    loader_id, DetectLoaderFuncReloadTenant, t, DetectLoaderFreeTenant);
6✔
4142
            if (r < 0) {
6!
4143
                ret = -2;
×
4144
                goto error;
×
4145
            }
×
4146
        }
6✔
4147

4148
        de_ctx = de_ctx->next;
9✔
4149
    }
9✔
4150
error:
3✔
4151
    SCMutexUnlock(&master->lock);
3✔
4152
    return ret;
3✔
4153
}
3✔
4154

4155
static int DetectLoaderSetupReloadTenant(uint32_t tenant_id, const char *yaml, int reload_cnt)
4156
{
×
4157
    DetectEngineCtx *old_de_ctx = DetectEngineGetByTenantId(tenant_id);
×
4158
    if (old_de_ctx == NULL)
×
4159
        return -ENOENT;
×
4160
    int loader_id = old_de_ctx->loader_id;
×
4161
    DetectEngineDeReference(&old_de_ctx);
×
4162

4163
    TenantLoaderCtx *t = SCCalloc(1, sizeof(*t));
×
4164
    if (t == NULL)
×
4165
        return -ENOMEM;
×
4166

4167
    t->tenant_id = tenant_id;
×
4168
    if (yaml != NULL) {
×
4169
        t->yaml = SCStrdup(yaml);
×
4170
        if (t->yaml == NULL) {
×
4171
            SCFree(t);
×
4172
            return -ENOMEM;
×
4173
        }
×
4174
    }
×
4175
    t->reload_cnt = reload_cnt;
×
4176

4177
    SCLogDebug("loader_id %d", loader_id);
×
4178

4179
    return DetectLoaderQueueTask(
×
4180
            loader_id, DetectLoaderFuncReloadTenant, t, DetectLoaderFreeTenant);
×
4181
}
×
4182

4183
/** \brief Load a tenant and wait for loading to complete
4184
 */
4185
int DetectEngineLoadTenantBlocking(uint32_t tenant_id, const char *yaml)
4186
{
2✔
4187
    int r = DetectLoaderSetupLoadTenant(tenant_id, yaml);
2✔
4188
    if (r < 0)
2!
4189
        return r;
×
4190

4191
    if (DetectLoadersSync() != 0)
2!
4192
        return -1;
×
4193

4194
    return 0;
2✔
4195
}
2✔
4196

4197
/** \brief Reload a tenant and wait for loading to complete
4198
 */
4199
int DetectEngineReloadTenantBlocking(uint32_t tenant_id, const char *yaml, int reload_cnt)
4200
{
×
4201
    int r = DetectLoaderSetupReloadTenant(tenant_id, yaml, reload_cnt);
×
4202
    if (r < 0)
×
4203
        return r;
×
4204

4205
    if (DetectLoadersSync() != 0)
×
4206
        return -1;
×
4207

4208
    return 0;
×
4209
}
×
4210

4211
/** \brief Reload all tenants and wait for loading to complete
4212
 */
4213
int DetectEngineReloadTenantsBlocking(const int reload_cnt)
4214
{
3✔
4215
    int r = DetectLoaderSetupReloadTenants(reload_cnt);
3✔
4216
    if (r < 0)
3!
4217
        return r;
×
4218

4219
    if (DetectLoadersSync() != 0)
3!
4220
        return -1;
×
4221

4222
    return 0;
3✔
4223
}
3✔
4224

4225
static int DetectEngineMultiTenantSetupLoadLivedevMappings(
4226
        const SCConfNode *mappings_root_node, bool failure_fatal)
4227
{
×
4228
    SCConfNode *mapping_node = NULL;
×
4229

4230
    int mapping_cnt = 0;
×
4231
    if (mappings_root_node != NULL) {
×
4232
        TAILQ_FOREACH(mapping_node, &mappings_root_node->head, next) {
×
4233
            SCConfNode *tenant_id_node = SCConfNodeLookupChild(mapping_node, "tenant-id");
×
4234
            if (tenant_id_node == NULL)
×
4235
                goto bad_mapping;
×
4236
            SCConfNode *device_node = SCConfNodeLookupChild(mapping_node, "device");
×
4237
            if (device_node == NULL)
×
4238
                goto bad_mapping;
×
4239

4240
            uint32_t tenant_id = 0;
×
4241
            if (StringParseUint32(&tenant_id, 10, (uint16_t)strlen(tenant_id_node->val),
×
4242
                        tenant_id_node->val) < 0) {
×
4243
                SCLogError("tenant-id  "
×
4244
                           "of %s is invalid",
×
4245
                        tenant_id_node->val);
×
4246
                goto bad_mapping;
×
4247
            }
×
4248

4249
            const char *dev = device_node->val;
×
4250
            LiveDevice *ld = LiveGetDevice(dev);
×
4251
            if (ld == NULL) {
×
4252
                SCLogWarning("device %s not found", dev);
×
4253
                goto bad_mapping;
×
4254
            }
×
4255

4256
            if (ld->tenant_id_set) {
×
4257
                SCLogWarning("device %s already mapped to tenant-id %u", dev, ld->tenant_id);
×
4258
                goto bad_mapping;
×
4259
            }
×
4260

4261
            ld->tenant_id = tenant_id;
×
4262
            ld->tenant_id_set = true;
×
4263

4264
            if (DetectEngineTenantRegisterLivedev(tenant_id, ld->id) != 0) {
×
4265
                goto error;
×
4266
            }
×
4267

4268
            SCLogConfig("device %s connected to tenant-id %u", dev, tenant_id);
×
4269
            mapping_cnt++;
×
4270
            continue;
×
4271

4272
        bad_mapping:
×
4273
            if (failure_fatal)
×
4274
                goto error;
×
4275
        }
×
4276
    }
×
4277
    SCLogConfig("%d device - tenant-id mappings defined", mapping_cnt);
×
4278
    return mapping_cnt;
×
4279

4280
error:
×
4281
    return 0;
×
4282
}
×
4283

4284
static int DetectEngineMultiTenantSetupLoadVlanMappings(
4285
        const SCConfNode *mappings_root_node, bool failure_fatal)
4286
{
4✔
4287
    SCConfNode *mapping_node = NULL;
4✔
4288

4289
    int mapping_cnt = 0;
4✔
4290
    if (mappings_root_node != NULL) {
4!
4291
        TAILQ_FOREACH(mapping_node, &mappings_root_node->head, next) {
13✔
4292
            SCConfNode *tenant_id_node = SCConfNodeLookupChild(mapping_node, "tenant-id");
13✔
4293
            if (tenant_id_node == NULL)
13!
4294
                goto bad_mapping;
×
4295
            SCConfNode *vlan_id_node = SCConfNodeLookupChild(mapping_node, "vlan-id");
13✔
4296
            if (vlan_id_node == NULL)
13!
4297
                goto bad_mapping;
×
4298

4299
            uint32_t tenant_id = 0;
13✔
4300
            if (StringParseUint32(&tenant_id, 10, (uint16_t)strlen(tenant_id_node->val),
13!
4301
                        tenant_id_node->val) < 0) {
13✔
4302
                SCLogError("tenant-id  "
×
4303
                           "of %s is invalid",
×
4304
                        tenant_id_node->val);
×
4305
                goto bad_mapping;
×
4306
            }
×
4307

4308
            uint16_t vlan_id = 0;
13✔
4309
            if (StringParseUint16(
13!
4310
                        &vlan_id, 10, (uint16_t)strlen(vlan_id_node->val), vlan_id_node->val) < 0) {
13✔
4311
                SCLogError("vlan-id  "
×
4312
                           "of %s is invalid",
×
4313
                        vlan_id_node->val);
×
4314
                goto bad_mapping;
×
4315
            }
×
4316
            if (vlan_id == 0 || vlan_id >= 4095) {
13!
4317
                SCLogError("vlan-id  "
×
4318
                           "of %s is invalid. Valid range 1-4094.",
×
4319
                        vlan_id_node->val);
×
4320
                goto bad_mapping;
×
4321
            }
×
4322

4323
            if (DetectEngineTenantRegisterVlanId(tenant_id, vlan_id) != 0) {
13!
4324
                goto error;
×
4325
            }
×
4326
            SCLogConfig("vlan %u connected to tenant-id %u", vlan_id, tenant_id);
13✔
4327
            mapping_cnt++;
13✔
4328
            continue;
13✔
4329

4330
        bad_mapping:
×
4331
            if (failure_fatal)
×
4332
                goto error;
×
4333
        }
×
4334
    }
4✔
4335
    return mapping_cnt;
4✔
4336

4337
error:
×
4338
    return 0;
×
4339
}
4✔
4340

4341
/**
4342
 *  \brief setup multi-detect / multi-tenancy
4343
 *
4344
 *  See if MT is enabled. If so, setup the selector, tenants and mappings.
4345
 *  Tenants and mappings are optional, and can also dynamically be added
4346
 *  and removed from the unix socket.
4347
 */
4348
int DetectEngineMultiTenantSetup(const bool unix_socket)
4349
{
1,800✔
4350
    enum DetectEngineTenantSelectors tenant_selector = TENANT_SELECTOR_UNKNOWN;
1,800✔
4351
    DetectEngineMasterCtx *master = &g_master_de_ctx;
1,800✔
4352
    int failure_fatal = 0;
1,800✔
4353
    (void)SCConfGetBool("engine.init-failure-fatal", &failure_fatal);
1,800✔
4354

4355
    int enabled = 0;
1,800✔
4356
    (void)SCConfGetBool("multi-detect.enabled", &enabled);
1,800✔
4357
    if (enabled == 1) {
1,800✔
4358
        DetectLoadersInit();
4✔
4359
        TmModuleDetectLoaderRegister();
4✔
4360
        DetectLoaderThreadSpawn();
4✔
4361
        TmThreadContinueDetectLoaderThreads();
4✔
4362

4363
        SCMutexLock(&master->lock);
4✔
4364
        master->multi_tenant_enabled = 1;
4✔
4365

4366
        const char *handler = NULL;
4✔
4367
        if (SCConfGet("multi-detect.selector", &handler) == 1) {
4!
4368
            SCLogConfig("multi-tenant selector type %s", handler);
4✔
4369

4370
            if (strcmp(handler, "vlan") == 0) {
4!
4371
                tenant_selector = master->tenant_selector = TENANT_SELECTOR_VLAN;
4✔
4372

4373
                int vlanbool = 0;
4✔
4374
                if ((SCConfGetBool("vlan.use-for-tracking", &vlanbool)) == 1 && vlanbool == 0) {
4!
4375
                    SCLogError("vlan tracking is disabled, "
×
4376
                               "can't use multi-detect selector 'vlan'");
×
4377
                    SCMutexUnlock(&master->lock);
×
4378
                    goto error;
×
4379
                }
×
4380

4381
            } else if (strcmp(handler, "direct") == 0) {
4!
4382
                tenant_selector = master->tenant_selector = TENANT_SELECTOR_DIRECT;
×
4383
            } else if (strcmp(handler, "device") == 0) {
×
4384
                tenant_selector = master->tenant_selector = TENANT_SELECTOR_LIVEDEV;
×
4385
                if (EngineModeIsIPS()) {
×
4386
                    SCLogWarning("multi-tenant 'device' mode not supported for IPS");
×
4387
                    SCMutexUnlock(&master->lock);
×
4388
                    goto error;
×
4389
                }
×
4390

4391
            } else {
×
4392
                SCLogError("unknown value %s "
×
4393
                           "multi-detect.selector",
×
4394
                        handler);
×
4395
                SCMutexUnlock(&master->lock);
×
4396
                goto error;
×
4397
            }
×
4398
        }
4✔
4399
        SCMutexUnlock(&master->lock);
4✔
4400
        SCLogConfig("multi-detect is enabled (multi tenancy). Selector: %s", handler);
4✔
4401

4402
        /* traffic -- tenant mappings */
4403
        SCConfNode *mappings_root_node = SCConfGetNode("multi-detect.mappings");
4✔
4404

4405
        if (tenant_selector == TENANT_SELECTOR_VLAN) {
4!
4406
            int mapping_cnt = DetectEngineMultiTenantSetupLoadVlanMappings(mappings_root_node,
4✔
4407
                    failure_fatal);
4✔
4408
            if (mapping_cnt == 0) {
4!
4409
                /* no mappings are valid when we're in unix socket mode,
4410
                 * they can be added on the fly. Otherwise warn/error
4411
                 * depending on failure_fatal */
4412

4413
                if (unix_socket) {
×
4414
                    SCLogNotice("no tenant traffic mappings defined, "
×
4415
                            "tenants won't be used until mappings are added");
×
4416
                } else {
×
4417
                    if (failure_fatal) {
×
4418
                        SCLogError("no multi-detect mappings defined");
×
4419
                        goto error;
×
4420
                    } else {
×
4421
                        SCLogWarning("no multi-detect mappings defined");
×
4422
                    }
×
4423
                }
×
4424
            }
×
4425
        } else if (tenant_selector == TENANT_SELECTOR_LIVEDEV) {
4!
4426
            int mapping_cnt = DetectEngineMultiTenantSetupLoadLivedevMappings(mappings_root_node,
×
4427
                    failure_fatal);
×
4428
            if (mapping_cnt == 0) {
×
4429
                if (failure_fatal) {
×
4430
                    SCLogError("no multi-detect mappings defined");
×
4431
                    goto error;
×
4432
                } else {
×
4433
                    SCLogWarning("no multi-detect mappings defined");
×
4434
                }
×
4435
            }
×
4436
        }
×
4437

4438
        /* tenants */
4439
        SCConfNode *tenants_root_node = SCConfGetNode("multi-detect.tenants");
4✔
4440
        SCConfNode *tenant_node = NULL;
4✔
4441

4442
        if (tenants_root_node != NULL) {
4!
4443
            const char *path = NULL;
4✔
4444
            SCConfNode *path_node = SCConfGetNode("multi-detect.config-path");
4✔
4445
            if (path_node) {
4!
4446
                path = path_node->val;
3✔
4447
                SCLogConfig("tenants config path: %s", path);
3✔
4448
            }
3✔
4449

4450
            TAILQ_FOREACH(tenant_node, &tenants_root_node->head, next) {
13✔
4451
                SCConfNode *id_node = SCConfNodeLookupChild(tenant_node, "id");
13✔
4452
                if (id_node == NULL) {
13!
4453
                    goto bad_tenant;
×
4454
                }
×
4455
                SCConfNode *yaml_node = SCConfNodeLookupChild(tenant_node, "yaml");
13✔
4456
                if (yaml_node == NULL) {
13!
4457
                    goto bad_tenant;
×
4458
                }
×
4459

4460
                uint32_t tenant_id = 0;
13✔
4461
                if (StringParseUint32(
13!
4462
                            &tenant_id, 10, (uint16_t)strlen(id_node->val), id_node->val) < 0) {
13✔
4463
                    SCLogError("tenant_id  "
×
4464
                               "of %s is invalid",
×
4465
                            id_node->val);
×
4466
                    goto bad_tenant;
×
4467
                }
×
4468
                SCLogDebug("tenant id: %u, %s", tenant_id, yaml_node->val);
13!
4469

4470
                char yaml_path[PATH_MAX] = "";
13✔
4471
                if (path) {
13!
4472
                    if (PathMerge(yaml_path, PATH_MAX, path, yaml_node->val) < 0)
12!
4473
                        goto bad_tenant;
×
4474
                } else {
13✔
4475
                    size_t r = strlcpy(yaml_path, yaml_node->val, sizeof(yaml_path));
1✔
4476
                    if (r >= sizeof(yaml_path))
1!
4477
                        goto bad_tenant;
×
4478
                }
1✔
4479
                SCLogDebug("tenant path: %s", yaml_path);
13!
4480

4481
                /* setup the yaml in this loop so that it's not done by the loader
4482
                 * threads. SCConfYamlLoadFileWithPrefix is not thread safe. */
4483
                char prefix[64];
13✔
4484
                snprintf(prefix, sizeof(prefix), "multi-detect.%u", tenant_id);
13✔
4485
                if (SCConfYamlLoadFileWithPrefix(yaml_path, prefix) != 0) {
13!
4486
                    SCLogError("failed to load yaml %s", yaml_path);
×
4487
                    goto bad_tenant;
×
4488
                }
×
4489

4490
                int r = DetectLoaderSetupLoadTenant(tenant_id, yaml_path);
13✔
4491
                if (r < 0) {
13!
4492
                    /* error logged already */
4493
                    goto bad_tenant;
×
4494
                }
×
4495
                continue;
13✔
4496

4497
            bad_tenant:
13✔
4498
                if (failure_fatal)
×
4499
                    goto error;
×
4500
            }
×
4501
        }
4✔
4502

4503
        /* wait for our loaders to complete their tasks */
4504
        if (DetectLoadersSync() != 0) {
4!
4505
            goto error;
×
4506
        }
×
4507

4508
        VarNameStoreActivate();
4✔
4509

4510
    } else {
1,796✔
4511
        SCLogDebug("multi-detect not enabled (multi tenancy)");
1,796!
4512
    }
1,796✔
4513
    return 0;
1,800✔
4514
error:
×
4515
    return -1;
×
4516
}
1,800✔
4517

4518
static uint32_t DetectEngineTenantGetIdFromVlanId(const void *ctx, const Packet *p)
4519
{
154✔
4520
    const DetectEngineThreadCtx *det_ctx = ctx;
154✔
4521
    uint32_t x = 0;
154✔
4522
    uint32_t vlan_id = 0;
154✔
4523

4524
    if (p->vlan_idx == 0)
154!
4525
        return 0;
60✔
4526

4527
    vlan_id = p->vlan_id[0];
94✔
4528

4529
    if (det_ctx == NULL || det_ctx->tenant_array == NULL || det_ctx->tenant_array_size == 0)
94!
4530
        return 0;
×
4531

4532
    /* not very efficient, but for now we're targeting only limited amounts.
4533
     * Can use hash/tree approach later. */
4534
    for (x = 0; x < det_ctx->tenant_array_size; x++) {
564✔
4535
        if (det_ctx->tenant_array[x].traffic_id == vlan_id)
470!
4536
            return det_ctx->tenant_array[x].tenant_id;
×
4537
    }
470✔
4538

4539
    return 0;
94✔
4540
}
94✔
4541

4542
static uint32_t DetectEngineTenantGetIdFromLivedev(const void *ctx, const Packet *p)
4543
{
×
4544
    const DetectEngineThreadCtx *det_ctx = ctx;
×
4545
    const LiveDevice *ld = p->livedev;
×
4546

4547
    if (ld == NULL || det_ctx == NULL)
×
4548
        return 0;
×
4549

4550
    SCLogDebug("using tenant-id %u for packet on device %s", ld->tenant_id, ld->dev);
×
4551
    return ld->tenant_id;
×
4552
}
×
4553

4554
static int DetectEngineTenantRegisterSelector(
4555
        enum DetectEngineTenantSelectors selector, uint32_t tenant_id, uint32_t traffic_id)
4556
{
13✔
4557
    DetectEngineMasterCtx *master = &g_master_de_ctx;
13✔
4558
    SCMutexLock(&master->lock);
13✔
4559

4560
    if (!(master->tenant_selector == TENANT_SELECTOR_UNKNOWN || master->tenant_selector == selector)) {
13!
4561
        SCLogInfo("conflicting selector already set");
×
4562
        SCMutexUnlock(&master->lock);
×
4563
        return -1;
×
4564
    }
×
4565

4566
    DetectEngineTenantMapping *m = master->tenant_mapping_list;
13✔
4567
    while (m) {
31✔
4568
        if (m->traffic_id == traffic_id) {
18!
4569
            SCLogInfo("traffic id already registered");
×
4570
            SCMutexUnlock(&master->lock);
×
4571
            return -1;
×
4572
        }
×
4573
        m = m->next;
18✔
4574
    }
18✔
4575

4576
    DetectEngineTenantMapping *map = SCCalloc(1, sizeof(*map));
13✔
4577
    if (map == NULL) {
13!
4578
        SCLogInfo("memory fail");
×
4579
        SCMutexUnlock(&master->lock);
×
4580
        return -1;
×
4581
    }
×
4582
    map->traffic_id = traffic_id;
13✔
4583
    map->tenant_id = tenant_id;
13✔
4584

4585
    map->next = master->tenant_mapping_list;
13✔
4586
    master->tenant_mapping_list = map;
13✔
4587

4588
    master->tenant_selector = selector;
13✔
4589

4590
    SCLogDebug("tenant handler %u %u %u registered", selector, tenant_id, traffic_id);
13!
4591
    SCMutexUnlock(&master->lock);
13✔
4592
    return 0;
13✔
4593
}
13✔
4594

4595
static int DetectEngineTenantUnregisterSelector(
4596
        enum DetectEngineTenantSelectors selector, uint32_t tenant_id, uint32_t traffic_id)
4597
{
×
4598
    DetectEngineMasterCtx *master = &g_master_de_ctx;
×
4599
    SCMutexLock(&master->lock);
×
4600

4601
    if (master->tenant_mapping_list == NULL) {
×
4602
        SCMutexUnlock(&master->lock);
×
4603
        return -1;
×
4604
    }
×
4605

4606
    DetectEngineTenantMapping *prev = NULL;
×
4607
    DetectEngineTenantMapping *map = master->tenant_mapping_list;
×
4608
    while (map) {
×
4609
        if (map->traffic_id == traffic_id &&
×
4610
            map->tenant_id == tenant_id)
×
4611
        {
×
4612
            if (prev != NULL)
×
4613
                prev->next = map->next;
×
4614
            else
×
4615
                master->tenant_mapping_list = map->next;
×
4616

4617
            map->next = NULL;
×
4618
            SCFree(map);
×
4619
            SCLogInfo("tenant handler %u %u %u unregistered", selector, tenant_id, traffic_id);
×
4620
            SCMutexUnlock(&master->lock);
×
4621
            return 0;
×
4622
        }
×
4623
        prev = map;
×
4624
        map = map->next;
×
4625
    }
×
4626

4627
    SCMutexUnlock(&master->lock);
×
4628
    return -1;
×
4629
}
×
4630

4631
int DetectEngineTenantRegisterLivedev(uint32_t tenant_id, int device_id)
4632
{
×
4633
    return DetectEngineTenantRegisterSelector(
×
4634
            TENANT_SELECTOR_LIVEDEV, tenant_id, (uint32_t)device_id);
×
4635
}
×
4636

4637
int DetectEngineTenantRegisterVlanId(uint32_t tenant_id, uint16_t vlan_id)
4638
{
13✔
4639
    return DetectEngineTenantRegisterSelector(TENANT_SELECTOR_VLAN, tenant_id, (uint32_t)vlan_id);
13✔
4640
}
13✔
4641

4642
int DetectEngineTenantUnregisterVlanId(uint32_t tenant_id, uint16_t vlan_id)
4643
{
×
4644
    return DetectEngineTenantUnregisterSelector(TENANT_SELECTOR_VLAN, tenant_id, (uint32_t)vlan_id);
×
4645
}
×
4646

4647
int DetectEngineTenantRegisterPcapFile(uint32_t tenant_id)
4648
{
×
4649
    SCLogInfo("registering %u %d 0", TENANT_SELECTOR_DIRECT, tenant_id);
×
4650
    return DetectEngineTenantRegisterSelector(TENANT_SELECTOR_DIRECT, tenant_id, 0);
×
4651
}
×
4652

4653
int DetectEngineTenantUnregisterPcapFile(uint32_t tenant_id)
4654
{
×
4655
    SCLogInfo("unregistering %u %d 0", TENANT_SELECTOR_DIRECT, tenant_id);
×
4656
    return DetectEngineTenantUnregisterSelector(TENANT_SELECTOR_DIRECT, tenant_id, 0);
×
4657
}
×
4658

4659
static uint32_t DetectEngineTenantGetIdFromPcap(const void *ctx, const Packet *p)
4660
{
×
4661
    return p->pcap_v.tenant_id;
×
4662
}
×
4663

4664
DetectEngineCtx *DetectEngineGetByTenantId(uint32_t tenant_id)
4665
{
24✔
4666
    DetectEngineMasterCtx *master = &g_master_de_ctx;
24✔
4667
    SCMutexLock(&master->lock);
24✔
4668

4669
    if (master->list == NULL) {
24!
4670
        SCMutexUnlock(&master->lock);
13✔
4671
        return NULL;
13✔
4672
    }
13✔
4673

4674
    DetectEngineCtx *de_ctx = master->list;
11✔
4675
    while (de_ctx) {
26!
4676
        if (de_ctx->type == DETECT_ENGINE_TYPE_TENANT &&
23!
4677
                de_ctx->tenant_id == tenant_id)
23!
4678
        {
8✔
4679
            de_ctx->ref_cnt++;
8✔
4680
            break;
8✔
4681
        }
8✔
4682

4683
        de_ctx = de_ctx->next;
15✔
4684
    }
15✔
4685

4686
    SCMutexUnlock(&master->lock);
11✔
4687
    return de_ctx;
11✔
4688
}
24✔
4689

4690
void DetectEngineDeReference(DetectEngineCtx **de_ctx)
4691
{
125,112✔
4692
    DEBUG_VALIDATE_BUG_ON((*de_ctx)->ref_cnt == 0);
125,112✔
4693
    (*de_ctx)->ref_cnt--;
125,112✔
4694
    *de_ctx = NULL;
125,112✔
4695
}
125,112✔
4696

4697
static int DetectEngineAddToList(DetectEngineCtx *instance)
4698
{
37,330✔
4699
    DetectEngineMasterCtx *master = &g_master_de_ctx;
37,330✔
4700

4701
    if (instance == NULL)
37,330!
4702
        return -1;
×
4703

4704
    if (master->list == NULL) {
37,330✔
4705
        master->list = instance;
1,772✔
4706
    } else {
37,300✔
4707
        instance->next = master->list;
35,558✔
4708
        master->list = instance;
35,558✔
4709
    }
35,558✔
4710

4711
    return 0;
37,330✔
4712
}
37,330✔
4713

4714
int DetectEngineAddToMaster(DetectEngineCtx *de_ctx)
4715
{
37,330✔
4716
    int r;
37,330✔
4717

4718
    if (de_ctx == NULL)
37,330!
4719
        return -1;
×
4720

4721
    SCLogDebug("adding de_ctx %p to master", de_ctx);
37,330!
4722

4723
    DetectEngineMasterCtx *master = &g_master_de_ctx;
37,330✔
4724
    SCMutexLock(&master->lock);
37,330✔
4725
    r = DetectEngineAddToList(de_ctx);
37,330✔
4726
    SCMutexUnlock(&master->lock);
37,330✔
4727
    return r;
37,330✔
4728
}
37,330✔
4729

4730
static int DetectEngineMoveToFreeListNoLock(DetectEngineMasterCtx *master, DetectEngineCtx *de_ctx)
4731
{
37,324✔
4732
    DetectEngineCtx *instance = master->list;
37,324✔
4733
    if (instance == NULL) {
37,324!
4734
        return -1;
×
4735
    }
×
4736

4737
    /* remove from active list */
4738
    if (instance == de_ctx) {
37,324!
4739
        master->list = instance->next;
1,778✔
4740
    } else {
37,307✔
4741
        DetectEngineCtx *prev = instance;
35,546✔
4742
        instance = instance->next; /* already checked first element */
35,546✔
4743

4744
        while (instance) {
35,554!
4745
            DetectEngineCtx *next = instance->next;
35,554✔
4746

4747
            if (instance == de_ctx) {
35,554!
4748
                prev->next = instance->next;
35,546✔
4749
                break;
35,546✔
4750
            }
35,546✔
4751

4752
            prev = instance;
8✔
4753
            instance = next;
8✔
4754
        }
8✔
4755
        if (instance == NULL) {
35,546!
4756
            return -1;
×
4757
        }
×
4758
    }
35,546✔
4759

4760
    /* instance is now detached from list */
4761
    instance->next = NULL;
37,324✔
4762

4763
    /* add to free list */
4764
    if (master->free_list == NULL) {
37,324✔
4765
        master->free_list = instance;
1,780✔
4766
    } else {
37,307✔
4767
        instance->next = master->free_list;
35,544✔
4768
        master->free_list = instance;
35,544✔
4769
    }
35,544✔
4770
    SCLogDebug("detect engine %p moved to free list (%u refs)", de_ctx, de_ctx->ref_cnt);
37,324!
4771
    return 0;
37,324✔
4772
}
37,324✔
4773

4774
int DetectEngineMoveToFreeList(DetectEngineCtx *de_ctx)
4775
{
37,311✔
4776
    int ret = 0;
37,311✔
4777
    DetectEngineMasterCtx *master = &g_master_de_ctx;
37,311✔
4778
    SCMutexLock(&master->lock);
37,311✔
4779
    ret = DetectEngineMoveToFreeListNoLock(master, de_ctx);
37,311✔
4780
    SCMutexUnlock(&master->lock);
37,311✔
4781
    return ret;
37,311✔
4782
}
37,311✔
4783

4784
void DetectEnginePruneFreeList(void)
4785
{
37,682✔
4786
    DetectEngineMasterCtx *master = &g_master_de_ctx;
37,682✔
4787
    SCMutexLock(&master->lock);
37,682✔
4788

4789
    DetectEngineCtx *prev = NULL;
37,682✔
4790
    DetectEngineCtx *instance = master->free_list;
37,682✔
4791
    while (instance) {
110,534✔
4792
        DetectEngineCtx *next = instance->next;
72,852✔
4793

4794
        SCLogDebug("detect engine %p has %u ref(s)", instance, instance->ref_cnt);
72,852!
4795

4796
        if (instance->ref_cnt == 0) {
72,852!
4797
            if (prev == NULL) {
37,323!
4798
                master->free_list = next;
1,795✔
4799
            } else {
37,323✔
4800
                prev->next = next;
35,528✔
4801
            }
35,528✔
4802

4803
            SCLogDebug("freeing detect engine %p", instance);
37,323!
4804
            DetectEngineCtxFree(instance);
37,323✔
4805
            instance = NULL;
37,323✔
4806
        }
37,323✔
4807

4808
        prev = instance;
72,852✔
4809
        instance = next;
72,852✔
4810
    }
72,852✔
4811
    SCMutexUnlock(&master->lock);
37,682✔
4812
}
37,682✔
4813

4814
void DetectEngineClearMaster(void)
4815
{
2,111✔
4816
    DetectEngineMasterCtx *master = &g_master_de_ctx;
2,111✔
4817
    SCMutexLock(&master->lock);
2,111✔
4818

4819
    DetectEngineCtx *instance = master->list;
2,111✔
4820
    while (instance) {
2,124✔
4821
        DetectEngineCtx *next = instance->next;
13✔
4822
        DEBUG_VALIDATE_BUG_ON(instance->ref_cnt);
13✔
4823
        SCLogDebug("detect engine %p has %u ref(s)", instance, instance->ref_cnt);
13!
4824
        instance->ref_cnt = 0;
13✔
4825
        DetectEngineMoveToFreeListNoLock(master, instance);
13✔
4826
        instance = next;
13✔
4827
    }
13✔
4828
    SCMutexUnlock(&master->lock);
2,111✔
4829
    DetectEnginePruneFreeList();
2,111✔
4830
}
2,111✔
4831

4832
static int reloads = 0;
4833

4834
/** \brief Reload the detection engine
4835
 *
4836
 *  \param filename YAML file to load for the detect config
4837
 *
4838
 *  \retval -1 error
4839
 *  \retval 0 ok
4840
 */
4841
int DetectEngineReload(const SCInstance *suri)
4842
{
35,537✔
4843
    DetectEngineCtx *new_de_ctx = NULL;
35,537✔
4844
    DetectEngineCtx *old_de_ctx = NULL;
35,537✔
4845

4846
    char prefix[128];
35,537✔
4847
    memset(prefix, 0, sizeof(prefix));
35,537✔
4848

4849
    SCLogNotice("rule reload starting");
35,537✔
4850

4851
    if (suri->conf_filename != NULL) {
35,537!
4852
        snprintf(prefix, sizeof(prefix), "detect-engine-reloads.%d", reloads++);
8✔
4853
        SCLogConfig("Reloading %s", suri->conf_filename);
8✔
4854
        if (SCConfYamlLoadFileWithPrefix(suri->conf_filename, prefix) != 0) {
8!
4855
            SCLogError("failed to load yaml %s", suri->conf_filename);
×
4856
            return -1;
×
4857
        }
×
4858

4859
        SCConfNode *node = SCConfGetNode(prefix);
8✔
4860
        if (node == NULL) {
8!
4861
            SCLogError("failed to properly setup yaml %s", suri->conf_filename);
×
4862
            return -1;
×
4863
        }
×
4864

4865
        if (suri->additional_configs) {
8!
4866
            for (int i = 0; suri->additional_configs[i] != NULL; i++) {
×
4867
                SCLogConfig("Reloading %s", suri->additional_configs[i]);
×
4868
                SCConfYamlHandleInclude(node, suri->additional_configs[i]);
×
4869
            }
×
4870
        }
×
4871

4872
#if 0
4873
        SCConfDump();
4874
#endif
4875
    }
8✔
4876

4877
    /* get a reference to the current de_ctx */
4878
    old_de_ctx = DetectEngineGetCurrent();
35,537✔
4879
    if (old_de_ctx == NULL)
35,537!
4880
        return -1;
×
4881
    SCLogDebug("get ref to old_de_ctx %p", old_de_ctx);
35,537!
4882
    DatasetReload();
35,537✔
4883

4884
    /* only reload a regular 'normal' and 'delayed detect stub' detect engines */
4885
    if (!(old_de_ctx->type == DETECT_ENGINE_TYPE_NORMAL ||
35,537!
4886
          old_de_ctx->type == DETECT_ENGINE_TYPE_DD_STUB))
35,537!
4887
    {
×
4888
        DetectEngineDeReference(&old_de_ctx);
×
4889
        SCLogNotice("rule reload complete");
×
4890
        return -1;
×
4891
    }
×
4892

4893
    /* get new detection engine */
4894
    new_de_ctx = DetectEngineCtxInitWithPrefix(prefix, old_de_ctx->tenant_id);
35,537✔
4895
    if (new_de_ctx == NULL) {
35,537!
4896
        SCLogError("initializing detection engine "
×
4897
                   "context failed.");
×
4898
        DetectEngineDeReference(&old_de_ctx);
×
4899
        return -1;
×
4900
    }
×
4901
    if (SigLoadSignatures(new_de_ctx,
35,537!
4902
                          suri->sig_file, suri->sig_file_exclusive) != 0) {
35,537✔
4903
        DetectEngineCtxFree(new_de_ctx);
×
4904
        DetectEngineDeReference(&old_de_ctx);
×
4905
        return -1;
×
4906
    }
×
4907
    SCLogDebug("set up new_de_ctx %p", new_de_ctx);
35,537!
4908

4909
    /* Copy over callbacks. */
4910
    new_de_ctx->RateFilterCallback = old_de_ctx->RateFilterCallback;
35,537✔
4911
    new_de_ctx->rate_filter_callback_arg = old_de_ctx->rate_filter_callback_arg;
35,537✔
4912

4913
    /* add to master */
4914
    DetectEngineAddToMaster(new_de_ctx);
35,537✔
4915

4916
    /* move to old free list */
4917
    DetectEngineMoveToFreeList(old_de_ctx);
35,537✔
4918
    DetectEngineDeReference(&old_de_ctx);
35,537✔
4919

4920
    SCLogDebug("going to reload the threads to use new_de_ctx %p", new_de_ctx);
35,537!
4921

4922
    DetectEngineMasterCtx *master = &g_master_de_ctx;
35,537✔
4923
    SCMutexLock(&master->lock);
35,537✔
4924
    /* update the threads */
4925
    DetectEngineReloadThreads(new_de_ctx);
35,537✔
4926
    SCMutexUnlock(&master->lock);
35,537✔
4927

4928
    SCLogDebug("threads now run new_de_ctx %p", new_de_ctx);
35,537!
4929

4930
    /* walk free list, freeing the old_de_ctx */
4931
    DetectEnginePruneFreeList();
35,537✔
4932

4933
    DatasetPostReloadCleanup();
35,537✔
4934

4935
    DetectEngineBumpVersion();
35,537✔
4936

4937
    SCLogDebug("old_de_ctx should have been freed");
35,537!
4938

4939
    DetectEngineMpmCacheService(DETECT_ENGINE_MPM_CACHE_OP_SAVE | DETECT_ENGINE_MPM_CACHE_OP_PRUNE);
35,537✔
4940

4941
    SCLogNotice("rule reload complete");
35,537✔
4942

4943
#ifdef HAVE_MALLOC_TRIM
35,537✔
4944
    /* The reload process potentially frees up large amounts of memory.
4945
     * Encourage the memory management system to reclaim as much as it
4946
     * can.
4947
     */
4948
    malloc_trim(0);
35,537✔
4949
#endif
35,537✔
4950

4951
    return 0;
35,537✔
4952
}
35,537✔
4953

4954
static uint32_t TenantIdHash(HashTable *h, void *data, uint16_t data_len)
4955
{
76✔
4956
    DetectEngineThreadCtx *det_ctx = (DetectEngineThreadCtx *)data;
76✔
4957
    return det_ctx->tenant_id % h->array_size;
76✔
4958
}
76✔
4959

4960
static char TenantIdCompare(void *d1, uint16_t d1_len, void *d2, uint16_t d2_len)
4961
{
×
4962
    DetectEngineThreadCtx *det1 = (DetectEngineThreadCtx *)d1;
×
4963
    DetectEngineThreadCtx *det2 = (DetectEngineThreadCtx *)d2;
×
4964
    return (det1->tenant_id == det2->tenant_id);
×
4965
}
×
4966

4967
static void TenantIdFree(void *d)
4968
{
76✔
4969
    DetectEngineThreadCtxFree(d);
76✔
4970
}
76✔
4971

4972
int DetectEngineMTApply(void)
4973
{
7✔
4974
    DetectEngineMasterCtx *master = &g_master_de_ctx;
7✔
4975
    SCMutexLock(&master->lock);
7✔
4976

4977
    if (master->tenant_selector == TENANT_SELECTOR_UNKNOWN) {
7!
4978
        SCLogInfo("error, no tenant selector");
×
4979
        SCMutexUnlock(&master->lock);
×
4980
        return -1;
×
4981
    }
×
4982

4983
    DetectEngineCtx *stub_de_ctx = NULL;
7✔
4984
    DetectEngineCtx *list = master->list;
7✔
4985
    for ( ; list != NULL; list = list->next) {
20!
4986
        SCLogDebug("list %p tenant %u", list, list->tenant_id);
20!
4987

4988
        if (list->type == DETECT_ENGINE_TYPE_NORMAL ||
20!
4989
            list->type == DETECT_ENGINE_TYPE_MT_STUB ||
20!
4990
            list->type == DETECT_ENGINE_TYPE_DD_STUB)
20!
4991
        {
7✔
4992
            stub_de_ctx = list;
7✔
4993
            break;
7✔
4994
        }
7✔
4995
    }
20✔
4996
    if (stub_de_ctx == NULL) {
7!
4997
        stub_de_ctx = DetectEngineCtxInitStubForMT();
×
4998
        if (stub_de_ctx == NULL) {
×
4999
            SCMutexUnlock(&master->lock);
×
5000
            return -1;
×
5001
        }
×
5002

5003
        if (master->list == NULL) {
×
5004
            master->list = stub_de_ctx;
×
5005
        } else {
×
5006
            stub_de_ctx->next = master->list;
×
5007
            master->list = stub_de_ctx;
×
5008
        }
×
5009
    }
×
5010

5011
    /* update the threads */
5012
    SCLogDebug("MT reload starting");
7!
5013
    DetectEngineReloadThreads(stub_de_ctx);
7✔
5014
    SCLogDebug("MT reload done");
7!
5015

5016
    SCMutexUnlock(&master->lock);
7✔
5017

5018
    /* walk free list, freeing the old_de_ctx */
5019
    DetectEnginePruneFreeList();
7✔
5020
    // needed for VarNameStoreFree
5021
    DetectEngineBumpVersion();
7✔
5022

5023
    SCLogDebug("old_de_ctx should have been freed");
7!
5024
    return 0;
7✔
5025
}
7✔
5026

5027
static int g_parse_metadata = 0;
5028

5029
void DetectEngineSetParseMetadata(void)
5030
{
3,260✔
5031
    g_parse_metadata = 1;
3,260✔
5032
}
3,260✔
5033

5034
void DetectEngineUnsetParseMetadata(void)
5035
{
1✔
5036
    g_parse_metadata = 0;
1✔
5037
}
1✔
5038

5039
int DetectEngineMustParseMetadata(void)
5040
{
148,533✔
5041
    return g_parse_metadata;
148,533✔
5042
}
148,533✔
5043

5044
const char *DetectSigmatchListEnumToString(enum DetectSigmatchListEnum type)
5045
{
23✔
5046
    switch (type) {
23!
5047
        case DETECT_SM_LIST_MATCH:
×
5048
            return "packet";
×
5049
        case DETECT_SM_LIST_PMATCH:
23!
5050
            return "packet/stream payload";
23✔
5051

5052
        case DETECT_SM_LIST_TMATCH:
×
5053
            return "tag";
×
5054

5055
        case DETECT_SM_LIST_BASE64_DATA:
×
5056
            return "base64_data";
×
5057

5058
        case DETECT_SM_LIST_POSTMATCH:
×
5059
            return "post-match";
×
5060

5061
        case DETECT_SM_LIST_SUPPRESS:
×
5062
            return "suppress";
×
5063
        case DETECT_SM_LIST_THRESHOLD:
×
5064
            return "threshold";
×
5065

5066
        case DETECT_SM_LIST_MAX:
×
5067
            return "max (internal)";
×
5068
    }
23✔
5069
    return "error";
×
5070
}
23✔
5071

5072
/* events api */
5073
void DetectEngineSetEvent(DetectEngineThreadCtx *det_ctx, uint8_t e)
5074
{
2✔
5075
    SCAppLayerDecoderEventsSetEventRaw(&det_ctx->decoder_events, e);
2✔
5076
    det_ctx->events++;
2✔
5077
}
2✔
5078

5079
bool DetectMd5ValidateCallback(
5080
        const Signature *s, const char **sigerror, const DetectBufferType *map)
5081
{
10,866✔
5082
    for (uint32_t x = 0; x < s->init_data->buffer_index; x++) {
17,297✔
5083
        if (s->init_data->buffers[x].id != (uint32_t)map->id)
13,839✔
5084
            continue;
1,848✔
5085
        const SigMatch *sm = s->init_data->buffers[x].head;
11,991✔
5086
        for (; sm != NULL; sm = sm->next) {
21,083✔
5087
            if (sm->type != DETECT_CONTENT)
16,500!
5088
                continue;
4,811✔
5089

5090
            const DetectContentData *cd = (DetectContentData *)sm->ctx;
11,689✔
5091
            if (cd->flags & DETECT_CONTENT_NOCASE) {
11,689!
5092
                *sigerror = "md5-like keyword should not be used together with "
569✔
5093
                            "nocase, since the rule is automatically "
569✔
5094
                            "lowercased anyway which makes nocase redundant.";
569✔
5095
                SCLogWarning("rule %u: buffer %s: %s", s->id, map->name, *sigerror);
569✔
5096
            }
569✔
5097

5098
            if (cd->content_len != SC_MD5_HEX_LEN) {
11,689!
5099
                *sigerror = "Invalid length for md5-like keyword (should "
6,220✔
5100
                            "be 32 characters long). This rule will therefore "
6,220✔
5101
                            "never match.";
6,220✔
5102
                SCLogError("rule %u: buffer %s: %s", s->id, map->name, *sigerror);
6,220✔
5103
                return false;
6,220✔
5104
            }
6,220✔
5105

5106
            for (size_t i = 0; i < cd->content_len; ++i) {
146,789✔
5107
                if (!isxdigit(cd->content[i])) {
142,508!
5108
                    *sigerror =
1,188✔
5109
                            "Invalid md5-like string (should be string of hexadecimal characters)."
1,188✔
5110
                            "This rule will therefore never match.";
1,188✔
5111
                    SCLogWarning("rule %u: buffer %s: %s", s->id, map->name, *sigerror);
1,188✔
5112
                    return false;
1,188✔
5113
                }
1,188✔
5114
            }
142,508✔
5115
        }
5,469✔
5116
    }
11,991✔
5117
    return true;
3,458✔
5118
}
10,866✔
5119

5120
void DetectLowerSetupCallback(
5121
        const DetectEngineCtx *de_ctx, Signature *s, const DetectBufferType *map)
5122
{
17,432✔
5123
    for (uint32_t x = 0; x < s->init_data->buffer_index; x++) {
59,712✔
5124
        if (s->init_data->buffers[x].id != (uint32_t)map->id)
42,280✔
5125
            continue;
5,510✔
5126
        SigMatch *sm = s->init_data->buffers[x].head;
36,770✔
5127
        for (; sm != NULL; sm = sm->next) {
104,884✔
5128
            if (sm->type != DETECT_CONTENT)
68,114!
5129
                continue;
47,253✔
5130

5131
            DetectContentData *cd = (DetectContentData *)sm->ctx;
20,861✔
5132

5133
            bool changed = false;
20,861✔
5134
            uint32_t u;
20,861✔
5135
            for (u = 0; u < cd->content_len; u++) {
986,068✔
5136
                if (isupper(cd->content[u])) {
965,207✔
5137
                    cd->content[u] = u8_tolower(cd->content[u]);
118,584✔
5138
                    changed = true;
118,584✔
5139
                }
118,584✔
5140
            }
965,207✔
5141

5142
            if (changed) {
20,861✔
5143
                SpmDestroyCtx(cd->spm_ctx);
8,715✔
5144
                cd->spm_ctx =
8,715✔
5145
                        SpmInitCtx(cd->content, cd->content_len, 1, de_ctx->spm_global_thread_ctx);
8,715✔
5146
            }
8,715✔
5147
        }
20,861✔
5148
    }
36,770✔
5149
}
17,432✔
5150

5151
void SCDetectEngineRegisterRateFilterCallback(SCDetectRateFilterFunc fn, void *arg)
5152
{
×
5153
    DetectEngineCtx *de_ctx = DetectEngineGetCurrent();
×
5154
    de_ctx->RateFilterCallback = fn;
×
5155
    de_ctx->rate_filter_callback_arg = arg;
×
5156
    DetectEngineDeReference(&de_ctx);
×
5157
}
×
5158

5159
int DetectEngineThreadCtxGetJsonContext(DetectEngineThreadCtx *det_ctx)
5160
{
26✔
5161
    if (det_ctx->json_content_len > SIG_JSON_CONTENT_ARRAY_LEN - 1) {
26!
5162
        SCLogDebug("json content length %u exceeds maximum %u", det_ctx->json_content_len,
×
5163
                SIG_JSON_CONTENT_ARRAY_LEN);
×
5164
        return -1;
×
5165
    }
×
5166
    if (det_ctx->json_content_len >= det_ctx->json_content_capacity) {
26✔
5167
        if (det_ctx->json_content_capacity == 0) {
22✔
5168
            det_ctx->json_content_capacity = 1;
11✔
5169
        } else {
11✔
5170
            det_ctx->json_content_capacity *= 2;
11✔
5171
        }
11✔
5172
        void *tmp = SCRealloc(
22✔
5173
                det_ctx->json_content, det_ctx->json_content_capacity * sizeof(SigJsonContent));
22✔
5174
        if (unlikely(tmp == NULL)) {
22!
5175
            return -1;
×
5176
        }
×
5177
        SCLogDebug("reallocated json content array to %u items", det_ctx->json_content_capacity);
22!
5178
        det_ctx->json_content = tmp;
22✔
5179
    }
22✔
5180
    return 0;
26✔
5181
}
26✔
5182

5183
/*************************************Unittest*********************************/
5184

5185
#ifdef UNITTESTS
5186

5187
static int DetectEngineInitYamlConf(const char *conf)
5188
{
6✔
5189
    SCConfCreateContextBackup();
6✔
5190
    SCConfInit();
6✔
5191
    return SCConfYamlLoadString(conf, strlen(conf));
6✔
5192
}
6✔
5193

5194
static void DetectEngineDeInitYamlConf(void)
5195
{
6✔
5196
    SCConfDeInit();
6✔
5197
    SCConfRestoreContextBackup();
6✔
5198
}
6✔
5199

5200
static int DetectEngineTest01(void)
5201
{
1✔
5202
    const char *conf =
1✔
5203
        "%YAML 1.1\n"
1✔
5204
        "---\n"
1✔
5205
        "detect-engine:\n"
1✔
5206
        "  - profile: medium\n"
1✔
5207
        "  - custom-values:\n"
1✔
5208
        "      toclient_src_groups: 2\n"
1✔
5209
        "      toclient_dst_groups: 2\n"
1✔
5210
        "      toclient_sp_groups: 2\n"
1✔
5211
        "      toclient_dp_groups: 3\n"
1✔
5212
        "      toserver_src_groups: 2\n"
1✔
5213
        "      toserver_dst_groups: 4\n"
1✔
5214
        "      toserver_sp_groups: 2\n"
1✔
5215
        "      toserver_dp_groups: 25\n"
1✔
5216
        "  - inspection-recursion-limit: 0\n";
1✔
5217

5218
    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);
1✔
5219

5220
    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
1✔
5221
    FAIL_IF_NULL(de_ctx);
1✔
5222

5223
    FAIL_IF_NOT(de_ctx->inspection_recursion_limit == -1);
1✔
5224

5225
    DetectEngineCtxFree(de_ctx);
1✔
5226

5227
    DetectEngineDeInitYamlConf();
1✔
5228

5229
    PASS;
1✔
5230
}
1✔
5231

5232
static int DetectEngineTest02(void)
5233
{
1✔
5234
    const char *conf =
1✔
5235
        "%YAML 1.1\n"
1✔
5236
        "---\n"
1✔
5237
        "detect-engine:\n"
1✔
5238
        "  - profile: medium\n"
1✔
5239
        "  - custom-values:\n"
1✔
5240
        "      toclient_src_groups: 2\n"
1✔
5241
        "      toclient_dst_groups: 2\n"
1✔
5242
        "      toclient_sp_groups: 2\n"
1✔
5243
        "      toclient_dp_groups: 3\n"
1✔
5244
        "      toserver_src_groups: 2\n"
1✔
5245
        "      toserver_dst_groups: 4\n"
1✔
5246
        "      toserver_sp_groups: 2\n"
1✔
5247
        "      toserver_dp_groups: 25\n"
1✔
5248
        "  - inspection-recursion-limit:\n";
1✔
5249

5250
    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);
1✔
5251

5252
    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
1✔
5253
    FAIL_IF_NULL(de_ctx);
1✔
5254

5255
    FAIL_IF_NOT(
1✔
5256
            de_ctx->inspection_recursion_limit == DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT);
1✔
5257

5258
    DetectEngineCtxFree(de_ctx);
1✔
5259

5260
    DetectEngineDeInitYamlConf();
1✔
5261

5262
    PASS;
1✔
5263
}
1✔
5264

5265
static int DetectEngineTest03(void)
5266
{
1✔
5267
    const char *conf =
1✔
5268
        "%YAML 1.1\n"
1✔
5269
        "---\n"
1✔
5270
        "detect-engine:\n"
1✔
5271
        "  - profile: medium\n"
1✔
5272
        "  - custom-values:\n"
1✔
5273
        "      toclient_src_groups: 2\n"
1✔
5274
        "      toclient_dst_groups: 2\n"
1✔
5275
        "      toclient_sp_groups: 2\n"
1✔
5276
        "      toclient_dp_groups: 3\n"
1✔
5277
        "      toserver_src_groups: 2\n"
1✔
5278
        "      toserver_dst_groups: 4\n"
1✔
5279
        "      toserver_sp_groups: 2\n"
1✔
5280
        "      toserver_dp_groups: 25\n";
1✔
5281

5282
    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);
1✔
5283

5284
    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
1✔
5285
    FAIL_IF_NULL(de_ctx);
1✔
5286

5287
    FAIL_IF_NOT(
1✔
5288
            de_ctx->inspection_recursion_limit == DETECT_ENGINE_DEFAULT_INSPECTION_RECURSION_LIMIT);
1✔
5289

5290
    DetectEngineCtxFree(de_ctx);
1✔
5291

5292
    DetectEngineDeInitYamlConf();
1✔
5293

5294
    PASS;
1✔
5295
}
1✔
5296

5297
static int DetectEngineTest04(void)
5298
{
1✔
5299
    const char *conf =
1✔
5300
        "%YAML 1.1\n"
1✔
5301
        "---\n"
1✔
5302
        "detect-engine:\n"
1✔
5303
        "  - profile: medium\n"
1✔
5304
        "  - custom-values:\n"
1✔
5305
        "      toclient_src_groups: 2\n"
1✔
5306
        "      toclient_dst_groups: 2\n"
1✔
5307
        "      toclient_sp_groups: 2\n"
1✔
5308
        "      toclient_dp_groups: 3\n"
1✔
5309
        "      toserver_src_groups: 2\n"
1✔
5310
        "      toserver_dst_groups: 4\n"
1✔
5311
        "      toserver_sp_groups: 2\n"
1✔
5312
        "      toserver_dp_groups: 25\n"
1✔
5313
        "  - inspection-recursion-limit: 10\n";
1✔
5314

5315
    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);
1✔
5316

5317
    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
1✔
5318
    FAIL_IF_NULL(de_ctx);
1✔
5319

5320
    FAIL_IF_NOT(de_ctx->inspection_recursion_limit == 10);
1✔
5321

5322
    DetectEngineCtxFree(de_ctx);
1✔
5323

5324
    DetectEngineDeInitYamlConf();
1✔
5325

5326
    PASS;
1✔
5327
}
1✔
5328

5329
static int DetectEngineTest08(void)
5330
{
1✔
5331
    const char *conf =
1✔
5332
        "%YAML 1.1\n"
1✔
5333
        "---\n"
1✔
5334
        "detect-engine:\n"
1✔
5335
        "  - profile: custom\n"
1✔
5336
        "  - custom-values:\n"
1✔
5337
        "      toclient-groups: 23\n"
1✔
5338
        "      toserver-groups: 27\n";
1✔
5339

5340
    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);
1✔
5341

5342
    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
1✔
5343
    FAIL_IF_NULL(de_ctx);
1✔
5344

5345
    FAIL_IF_NOT(de_ctx->max_uniq_toclient_groups == 23);
1✔
5346
    FAIL_IF_NOT(de_ctx->max_uniq_toserver_groups == 27);
1✔
5347

5348
    DetectEngineCtxFree(de_ctx);
1✔
5349

5350
    DetectEngineDeInitYamlConf();
1✔
5351

5352
    PASS;
1✔
5353
}
1✔
5354

5355
/** \test bug 892 bad values */
5356
static int DetectEngineTest09(void)
5357
{
1✔
5358
    const char *conf =
1✔
5359
        "%YAML 1.1\n"
1✔
5360
        "---\n"
1✔
5361
        "detect-engine:\n"
1✔
5362
        "  - profile: custom\n"
1✔
5363
        "  - custom-values:\n"
1✔
5364
        "      toclient-groups: BA\n"
1✔
5365
        "      toserver-groups: BA\n"
1✔
5366
        "  - inspection-recursion-limit: 10\n";
1✔
5367

5368
    FAIL_IF(DetectEngineInitYamlConf(conf) == -1);
1✔
5369

5370
    DetectEngineCtx *de_ctx = DetectEngineCtxInit();
1✔
5371
    FAIL_IF_NULL(de_ctx);
1✔
5372

5373
    FAIL_IF_NOT(de_ctx->max_uniq_toclient_groups == 20);
1✔
5374
    FAIL_IF_NOT(de_ctx->max_uniq_toserver_groups == 40);
1✔
5375

5376
    DetectEngineCtxFree(de_ctx);
1✔
5377

5378
    DetectEngineDeInitYamlConf();
1✔
5379

5380
    PASS;
1✔
5381
}
1✔
5382

5383
#endif
5384

5385
void DetectEngineRegisterTests(void)
5386
{
1✔
5387
#ifdef UNITTESTS
1✔
5388
    UtRegisterTest("DetectEngineTest01", DetectEngineTest01);
1✔
5389
    UtRegisterTest("DetectEngineTest02", DetectEngineTest02);
1✔
5390
    UtRegisterTest("DetectEngineTest03", DetectEngineTest03);
1✔
5391
    UtRegisterTest("DetectEngineTest04", DetectEngineTest04);
1✔
5392
    UtRegisterTest("DetectEngineTest08", DetectEngineTest08);
1✔
5393
    UtRegisterTest("DetectEngineTest09", DetectEngineTest09);
1✔
5394
#endif
1✔
5395
}
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc