Coverage Report

Created: 2026-12-04 07:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/yara/libyara/atoms.c
Line
Count
Source
1
/*
2
Copyright (c) 2013-2018. The YARA Authors. All Rights Reserved.
3
4
Redistribution and use in source and binary forms, with or without modification,
5
are permitted provided that the following conditions are met:
6
7
1. Redistributions of source code must retain the above copyright notice, this
8
list of conditions and the following disclaimer.
9
10
2. Redistributions in binary form must reproduce the above copyright notice,
11
this list of conditions and the following disclaimer in the documentation and/or
12
other materials provided with the distribution.
13
14
3. Neither the name of the copyright holder nor the names of its contributors
15
may be used to endorse or promote products derived from this software without
16
specific prior written permission.
17
18
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
22
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
*/
29
30
/*
31
32
This module handles atom extraction from regexps and hex strings. Atoms are
33
undivided substrings found in a regexps and hex strings. Let's consider this
34
hex string:
35
36
{ 01 02 03 04 05 ?? 06 07 08 [1-2] 09 0A }
37
38
In the above string, byte sequences 0102030405, 060708 and 090A are atoms.
39
Similarly, in this regexp:
40
41
/abc.*ed[0-9]+fgh/
42
43
The strings "abc", "ed" and "fgh" are atoms.
44
45
When searching for regexps/hex strings matching a file, YARA uses these
46
atoms to find locations inside the file where the regexp/hex string could
47
match. If the atom "abc" is found somewhere inside the file, there is a chance
48
for /abc.*ed[0-9]+fgh/ to match the file, if "abc" doesn't appear in the file
49
there's no chance for the regexp to match. When the atom is found in the file
50
YARA proceeds to fully evaluate the regexp/hex string to determine if it's
51
actually a match.
52
53
For each regexp/hex string YARA extracts one or more atoms. Sometimes a
54
single atom is enough (like in the previous example "abc" is enough for finding
55
/abc.*ed[0-9]+fgh/), but sometimes a single atom isn't enough like in the
56
regexp /(abc|efg)/. In this case YARA must search for both "abc" AND "efg" and
57
fully evaluate the regexp whenever one of these atoms is found.
58
59
In the regexp /Look(at|into)this/ YARA can search for "Look", or search for
60
"this", or search for both "at" and "into". This is what we call an atoms tree,
61
because it can be represented by the following tree structure:
62
63
-OR
64
  |- "Look"
65
  |
66
  |- AND
67
  |   |
68
  |   |- "at"
69
  |    - "into"
70
  |
71
   - "this"
72
73
From an atom tree YARA chooses the best combination, trying to minimize the
74
number of required atoms, but also using high quality atoms (long atoms with
75
not too many zeroes and a bit of byte diversity). In the previous example YARA
76
will end up using the "Look" atom alone, but in /a(bcd|efg)h/ atoms "bcd" and
77
"efg" will be used because "a" and "h" are too short.
78
*/
79
80
#include <assert.h>
81
#include <string.h>
82
#include <yara/atoms.h>
83
#include <yara/error.h>
84
#include <yara/globals.h>
85
#include <yara/limits.h>
86
#include <yara/mem.h>
87
#include <yara/stack.h>
88
#include <yara/types.h>
89
#include <yara/utils.h>
90
91
////////////////////////////////////////////////////////////////////////////////
92
// Returns a numeric value indicating the quality of an atom. The quality
93
// depends on some characteristics of the atom, including its length, number
94
// of very common bytes like 00 and FF and number of unique distinct bytes.
95
// Atom 00 00 has a very low quality, because it's only two bytes long and
96
// both bytes are zeroes. Atom 01 01 01 01 is better but still not optimal,
97
// because the same byte is repeated. Atom 01 02 03 04 is an optimal one.
98
//
99
// Args:
100
//    config: Pointer to YR_ATOMS_CONFIG struct.
101
//    atom: Pointer to YR_ATOM struct.
102
//
103
// Returns:
104
//    An integer indicating the atom's quality
105
//
106
int yr_atoms_heuristic_quality(YR_ATOMS_CONFIG* config, YR_ATOM* atom)
107
1.28M
{
108
1.28M
  YR_BITMASK seen_bytes[YR_BITMASK_SIZE(256)];
109
110
1.28M
  int quality = 0;
111
1.28M
  int unique_bytes = 0;
112
113
1.28M
  assert(atom->length <= YR_MAX_ATOM_LENGTH);
114
115
1.28M
  yr_bitmask_clear_all(seen_bytes);
116
117
  // Each byte in the atom contributes a certain amount of points to the
118
  // quality. Bytes [a-zA-Z] contribute 18 points each, common bytes like
119
  // 0x00, 0x20 and 0xFF contribute only 12 points, and the rest of the
120
  // bytes contribute 20 points. The ?? mask substracts 10 points, and masks
121
  // X? and ?X contribute 4 points. An additional boost consisting in 2x the
122
  // number of unique bytes in the atom is added to the quality. This are
123
  // some examples of the quality of atoms:
124
  //
125
  //   01 02 03 04   quality = 20 + 20 + 20 + 20 + 8 = 88
126
  //   01 ?? 03 04   quality = 20 - 10 + 20 + 20 + 6 = 56
127
  //   01 0? 03      quality = 20 +  4 + 20      + 4 = 48
128
  //   01 02         quality = 20 + 20           + 4 = 44
129
  //   01 ?? ?3 04   quality = 20 - 10 +  2 + 20 + 4 = 36
130
  //   61 62         quality = 18 + 18           + 4 = 40
131
  //   61 61         quality = 18 + 18           + 2 = 38  <- warning threshold
132
  //   00 01         quality = 12 + 20           + 4 = 36
133
  //   01 ?? 02      quality = 20 - 10 + 20      + 4 = 34
134
  //   01            quality = 20                + 1 = 21
135
136
5.90M
  for (int i = 0; i < atom->length; i++)
137
4.62M
  {
138
4.62M
    switch (atom->mask[i])
139
4.62M
    {
140
23.1k
    case 0x00:
141
23.1k
      quality -= 10;
142
23.1k
      break;
143
1.71k
    case 0x0F:
144
1.71k
      quality += 4;
145
1.71k
      break;
146
2.47k
    case 0xF0:
147
2.47k
      quality += 4;
148
2.47k
      break;
149
4.60M
    case 0xFF:
150
4.60M
      switch (atom->bytes[i])
151
4.60M
      {
152
1.48M
      case 0x00:
153
1.49M
      case 0x20:
154
1.50M
      case 0xCC:
155
1.61M
      case 0xFF:
156
        // Common bytes contribute less to the quality than the rest.
157
1.61M
        quality += 12;
158
1.61M
        break;
159
2.98M
      default:
160
        // Bytes in the a-z and A-Z ranges have a slightly lower quality
161
        // than the rest. We want to favor atoms that contain bytes outside
162
        // those ranges because they generate less additional atoms during
163
        // calls to _yr_atoms_case_combinations.
164
2.98M
        if (yr_lowercase[atom->bytes[i]] >= 'a' &&
165
2.48M
            yr_lowercase[atom->bytes[i]] <= 'z')
166
2.04M
          quality += 18;
167
939k
        else
168
939k
          quality += 20;
169
4.60M
      }
170
171
4.60M
      if (!yr_bitmask_is_set(seen_bytes, atom->bytes[i]))
172
3.41M
      {
173
3.41M
        yr_bitmask_set(seen_bytes, atom->bytes[i]);
174
3.41M
        unique_bytes++;
175
3.41M
      }
176
4.62M
    }
177
4.62M
  }
178
179
  // If all the bytes in the atom are equal and very common, let's penalize
180
  // it heavily.
181
1.28M
  if (unique_bytes == 1 && (yr_bitmask_is_set(seen_bytes, 0x00) ||
182
212k
                            yr_bitmask_is_set(seen_bytes, 0x20) ||
183
211k
                            yr_bitmask_is_set(seen_bytes, 0x90) ||
184
209k
                            yr_bitmask_is_set(seen_bytes, 0xCC) ||
185
207k
                            yr_bitmask_is_set(seen_bytes, 0xFF)))
186
30.3k
  {
187
30.3k
    quality -= 10 * atom->length;
188
30.3k
  }
189
  // In general atoms with more unique bytes have a better quality, so let's
190
  // boost the quality in the amount of unique bytes.
191
1.25M
  else
192
1.25M
  {
193
1.25M
    quality += 2 * unique_bytes;
194
1.25M
  }
195
196
  // The final quality is not zero-based, we start at YR_MAX_ATOM_QUALITY
197
  // for the best possible atom and substract from there. The best possible
198
  // quality is 21 * YR_MAX_ATOM_LENGTH (20 points per byte + 2 additional point
199
  // per unique byte, with a maximum of 2*YR_MAX_ATOM_LENGTH unique bytes).
200
201
1.28M
  return YR_MAX_ATOM_QUALITY - 22 * YR_MAX_ATOM_LENGTH + quality;
202
1.28M
}
203
204
////////////////////////////////////////////////////////////////////////////////
205
// Compares the byte sequence in a1 with the YR_ATOM in a2, taking atom's mask
206
// into account.
207
//
208
// Returns:
209
//   < 0 if the first byte that does not match has a lower value in a1 than
210
//       in a2.
211
//   > 0 if the first byte that does not match has a greater value in a1 than
212
//       in a2.
213
//   = 0 if a1 is equal or matches a2.
214
//
215
static int _yr_atoms_cmp(const uint8_t* a1, YR_ATOM* a2)
216
0
{
217
0
  int result = 0;
218
0
  int i = 0;
219
220
0
  while (result == 0 && i < a2->length)
221
0
  {
222
0
    switch (a2->mask[i])
223
0
    {
224
0
    case 0xFF:
225
0
    case 0x0F:
226
0
    case 0xF0:
227
0
    case 0x00:
228
0
      result = (a1[i] & a2->mask[i]) - a2->bytes[i];
229
0
      break;
230
0
    default:
231
0
      assert(false);
232
0
    }
233
234
0
    i++;
235
0
  }
236
237
0
  return result;
238
0
}
239
240
////////////////////////////////////////////////////////////////////////////////
241
// Returns a numeric value indicating the quality of an atom. The quality is
242
// based in the atom quality table passed in "config". Very common atoms
243
// (i.e: those with greater quality) have lower quality than those that are
244
// uncommon. See the comment for yr_compiler_set_atom_quality_table for
245
// details about the quality table's format.
246
//
247
// Args:
248
//    YR_ATOMS_CONFIG* config   - Pointer to YR_ATOMS_CONFIG struct.
249
//    YR_ATOM* atom             - Pointer to YR_ATOM struct.
250
//
251
// Returns:
252
//    An integer indicating the atom's quality
253
//
254
int yr_atoms_table_quality(YR_ATOMS_CONFIG* config, YR_ATOM* atom)
255
0
{
256
0
  YR_ATOM_QUALITY_TABLE_ENTRY* table = config->quality_table;
257
258
0
  int begin = 0;
259
0
  int end = config->quality_table_entries;
260
261
0
  assert(atom->length <= YR_MAX_ATOM_LENGTH);
262
263
0
  while (end > begin)
264
0
  {
265
0
    int middle = begin + (end - begin) / 2;
266
0
    int c = _yr_atoms_cmp(table[middle].atom, atom);
267
268
0
    if (c < 0)
269
0
    {
270
0
      begin = middle + 1;
271
0
    }
272
0
    else if (c > 0)
273
0
    {
274
0
      end = middle;
275
0
    }
276
0
    else
277
0
    {
278
0
      int i = middle + 1;
279
0
      int quality = table[middle].quality;
280
0
      int min_quality = quality;
281
282
0
      while (i < end && _yr_atoms_cmp(table[i].atom, atom) == 0)
283
0
      {
284
0
        if (min_quality > table[i].quality)
285
0
          min_quality = table[i].quality;
286
287
0
        i++;
288
0
      }
289
290
0
      i = middle - 1;
291
292
0
      while (i >= begin && _yr_atoms_cmp(table[i].atom, atom) == 0)
293
0
      {
294
0
        if (min_quality > table[i].quality)
295
0
          min_quality = table[i].quality;
296
297
0
        i--;
298
0
      }
299
300
0
      return min_quality >> (YR_MAX_ATOM_LENGTH - atom->length);
301
0
    }
302
0
  }
303
304
0
  return YR_MAX_ATOM_QUALITY;
305
0
}
306
307
////////////////////////////////////////////////////////////////////////////////
308
// Returns the quality for the worst quality atom in a list.
309
//
310
int yr_atoms_min_quality(YR_ATOMS_CONFIG* config, YR_ATOM_LIST_ITEM* atom_list)
311
0
{
312
0
  YR_ATOM_LIST_ITEM* atom;
313
314
0
  int quality;
315
0
  int min_quality = YR_MAX_ATOM_QUALITY;
316
317
0
  if (atom_list == NULL)
318
0
    return YR_MIN_ATOM_QUALITY;
319
320
0
  atom = atom_list;
321
322
0
  while (atom != NULL)
323
0
  {
324
0
    quality = config->get_atom_quality(config, &atom->atom);
325
326
0
    if (quality < min_quality)
327
0
      min_quality = quality;
328
329
0
    atom = atom->next;
330
0
  }
331
332
0
  return min_quality;
333
0
}
334
335
////////////////////////////////////////////////////////////////////////////////
336
// Creates a new node for an atoms tree.
337
//
338
static YR_ATOM_TREE_NODE* _yr_atoms_tree_node_create(uint8_t type)
339
120k
{
340
120k
  YR_ATOM_TREE_NODE* new_node = (YR_ATOM_TREE_NODE*) yr_malloc(
341
120k
      sizeof(YR_ATOM_TREE_NODE));
342
343
120k
  if (new_node != NULL)
344
120k
  {
345
120k
    new_node->type = type;
346
120k
    new_node->atom.length = 0;
347
120k
    new_node->next_sibling = NULL;
348
120k
    new_node->children_head = NULL;
349
120k
    new_node->children_tail = NULL;
350
120k
  }
351
352
120k
  return new_node;
353
120k
}
354
355
////////////////////////////////////////////////////////////////////////////////
356
// Destroys a node from an atoms tree and all its descendants iteratively.
357
//
358
// Instead of recursing, this flattens the subtree in-place into a FIFO queue
359
// linked through `next_sibling`, where `current` is the queue head and `tail`
360
// is the queue tail.
361
//
362
static void _yr_atoms_tree_node_destroy(YR_ATOM_TREE_NODE* node)
363
12.4k
{
364
12.4k
  YR_ATOM_TREE_NODE* current = node;
365
12.4k
  YR_ATOM_TREE_NODE* tail = node;
366
12.4k
  YR_ATOM_TREE_NODE* next;
367
368
12.4k
  if (node == NULL)
369
0
    return;
370
371
  // Initialize the queue with `node` as its only element. Clearing
372
  // `node->next_sibling` ensures we only destroy the subtree rooted at `node`
373
  // (and not any siblings `node` might have). If `node` has children, the
374
  // first iteration below will overwrite `node->next_sibling` (via `tail`) to
375
  // point to `node->children_head` before `current->next_sibling` is read.
376
12.4k
  node->next_sibling = NULL;
377
378
132k
  while (current != NULL)
379
120k
  {
380
    // If the current node has children, append its entire child list
381
    // (`children_head` .. `children_tail`) to the end of the queue.
382
120k
    if ((current->type == ATOM_TREE_OR || current->type == ATOM_TREE_AND) &&
383
72.9k
        current->children_head != NULL)
384
67.9k
    {
385
67.9k
      tail->next_sibling = current->children_head;
386
67.9k
      tail = current->children_tail;
387
67.9k
    }
388
389
120k
    next = current->next_sibling;
390
120k
    yr_free(current);
391
120k
    current = next;
392
120k
  }
393
12.4k
}
394
395
////////////////////////////////////////////////////////////////////////////////
396
// Appends a new child node to another atoms tree node.
397
//
398
static void _yr_atoms_tree_node_append(
399
    YR_ATOM_TREE_NODE* dest,
400
    YR_ATOM_TREE_NODE* node)
401
67.3k
{
402
67.3k
  if (dest->children_head == NULL)
403
47.8k
    dest->children_head = node;
404
405
67.3k
  if (dest->children_tail != NULL)
406
19.5k
    dest->children_tail->next_sibling = node;
407
408
67.3k
  dest->children_tail = node;
409
67.3k
}
410
411
////////////////////////////////////////////////////////////////////////////////
412
// Destroys an atoms tree.
413
//
414
static void _yr_atoms_tree_destroy(YR_ATOM_TREE* atom_tree)
415
12.4k
{
416
12.4k
  _yr_atoms_tree_node_destroy(atom_tree->root_node);
417
12.4k
  yr_free(atom_tree);
418
12.4k
}
419
420
////////////////////////////////////////////////////////////////////////////////
421
// Destroys an atoms list.
422
//
423
void yr_atoms_list_destroy(YR_ATOM_LIST_ITEM* list_head)
424
123k
{
425
123k
  YR_ATOM_LIST_ITEM* item = list_head;
426
123k
  YR_ATOM_LIST_ITEM* next;
427
428
14.8M
  while (item != NULL)
429
14.7M
  {
430
14.7M
    next = item->next;
431
14.7M
    yr_free(item);
432
14.7M
    item = next;
433
14.7M
  }
434
123k
}
435
436
////////////////////////////////////////////////////////////////////////////////
437
// Concats two atoms lists.
438
//
439
static YR_ATOM_LIST_ITEM* _yr_atoms_list_concat(
440
    YR_ATOM_LIST_ITEM* list1,
441
    YR_ATOM_LIST_ITEM* list2)
442
9.95k
{
443
9.95k
  YR_ATOM_LIST_ITEM* item;
444
445
9.95k
  if (list1 == NULL)
446
1.11k
    return list2;
447
448
8.83k
  item = list1;
449
450
2.17M
  while (item->next != NULL)
451
2.16M
  {
452
2.16M
    item = item->next;
453
2.16M
  }
454
455
8.83k
  item->next = list2;
456
8.83k
  return list1;
457
9.95k
}
458
459
////////////////////////////////////////////////////////////////////////////////
460
// If the atom starts or ends with an unknown byte (mask == 0x00), trim
461
// those bytes out of the atom. We don't want to expand an atom like
462
// { ?? 01 02 } into { 00 01 02 }, { 01 01 02}, { 02 01 02} .. { FF 01 02}
463
// in those cases it's better to simply have a shorter atom { 01 02 }.
464
//
465
// Args:
466
//   atom: Pointer to the YR_ATOM to be trimmed.
467
//
468
// Returns:
469
//   The number of bytes that were trimmed from the beginning of the atom.
470
//
471
int _yr_atoms_trim(YR_ATOM* atom)
472
997k
{
473
997k
  int mask_00 = 0;
474
997k
  int mask_ff = 0;
475
476
997k
  int trim_left = 0;
477
478
1.01M
  while (trim_left < atom->length && atom->mask[trim_left] == 0) trim_left++;
479
480
1.01M
  while (atom->length > trim_left && atom->mask[atom->length - 1] == 0)
481
12.5k
    atom->length--;
482
483
997k
  atom->length -= trim_left;
484
485
997k
  if (atom->length == 0)
486
5.37k
    return 0;
487
488
  // The trimmed atom goes from trim_left to trim_left + atom->length and the
489
  // first and last byte in the atom are known (mask == 0xFF). Now count the
490
  // number of known and unknown bytes in the atom (mask == 0xFF and
491
  // mask == 0x00 respectively).
492
493
4.83M
  for (int i = 0; i < atom->length; i++)
494
3.84M
  {
495
3.84M
    if (atom->mask[trim_left + i] == 0xFF)
496
3.80M
      mask_ff++;
497
32.6k
    else if (atom->mask[trim_left + i] == 0x00)
498
26.6k
      mask_00++;
499
3.84M
  }
500
501
  // If the number of unknown bytes is >= than the number of known bytes
502
  // it doesn't make sense the to use this atom, so we use a single byte atom
503
  // containing the first known byte. If YR_MAX_ATOM_LENGTH == 4 this happens
504
  // only when the atom is like { XX ?? ?? YY }, so using the first known
505
  // byte is good enough. For larger values of YR_MAX_ATOM_LENGTH this is not
506
  // the most efficient solution, as better atoms could be choosen. For
507
  // example, in { XX ?? ?? ?? YY ZZ } the best atom is { YY ZZ } not { XX }.
508
  // But let's keep it like this for simplicity.
509
510
992k
  if (mask_00 >= mask_ff)
511
4.15k
    atom->length = 1;
512
513
992k
  if (trim_left == 0)
514
984k
    return 0;
515
516
  // Shift bytes and mask trim_left positions to the left.
517
518
30.3k
  for (int i = 0; i < YR_MAX_ATOM_LENGTH - trim_left; i++)
519
22.0k
  {
520
22.0k
    atom->bytes[i] = atom->bytes[trim_left + i];
521
22.0k
    atom->mask[i] = atom->mask[trim_left + i];
522
22.0k
  }
523
524
8.34k
  return trim_left;
525
992k
}
526
527
////////////////////////////////////////////////////////////////////////////////
528
// This function receives an atom tree and returns a list of atoms to be added
529
// to the Aho-Corasick automaton.
530
//
531
static int _yr_atoms_choose(
532
    YR_ATOMS_CONFIG* config,
533
    YR_ATOM_TREE_NODE* node,
534
    YR_ATOM_LIST_ITEM** chosen_atoms,
535
    int* atoms_quality)
536
115k
{
537
115k
  YR_ATOM_TREE_NODE* child;
538
115k
  YR_ATOM_LIST_ITEM* item;
539
115k
  YR_ATOM_LIST_ITEM* tail;
540
541
115k
  int shift, quality;
542
543
115k
  int max_quality = YR_MIN_ATOM_QUALITY;
544
115k
  int min_quality = YR_MAX_ATOM_QUALITY;
545
546
115k
  *chosen_atoms = NULL;
547
115k
  *atoms_quality = YR_MIN_ATOM_QUALITY;
548
549
115k
  switch (node->type)
550
115k
  {
551
42.4k
  case ATOM_TREE_LEAF:
552
553
42.4k
    item = (YR_ATOM_LIST_ITEM*) yr_malloc(sizeof(YR_ATOM_LIST_ITEM));
554
555
42.4k
    if (item == NULL)
556
0
      return ERROR_INSUFFICIENT_MEMORY;
557
558
42.4k
    memcpy(&item->atom, &node->atom, sizeof(YR_ATOM));
559
560
42.4k
    shift = _yr_atoms_trim(&item->atom);
561
562
42.4k
    if (item->atom.length > 0)
563
40.2k
    {
564
40.2k
      item->forward_code_ref = node->re_nodes[shift]->forward_code_ref;
565
40.2k
      item->backward_code_ref = node->re_nodes[shift]->backward_code_ref;
566
40.2k
      item->backtrack = 0;
567
40.2k
      item->next = NULL;
568
569
40.2k
      *chosen_atoms = item;
570
40.2k
      *atoms_quality = config->get_atom_quality(config, &item->atom);
571
40.2k
    }
572
2.19k
    else
573
2.19k
    {
574
2.19k
      yr_free(item);
575
2.19k
    }
576
577
42.4k
    break;
578
579
52.7k
  case ATOM_TREE_OR:
580
581
    // The choosen nodes are those coming from the highest quality child.
582
583
52.7k
    child = node->children_head;
584
585
114k
    while (child != NULL)
586
62.6k
    {
587
62.6k
      FAIL_ON_ERROR(_yr_atoms_choose(config, child, &item, &quality));
588
589
62.6k
      if (quality > max_quality)
590
45.1k
      {
591
45.1k
        max_quality = quality;
592
45.1k
        yr_atoms_list_destroy(*chosen_atoms);
593
45.1k
        *chosen_atoms = item;
594
45.1k
      }
595
17.5k
      else
596
17.5k
      {
597
17.5k
        yr_atoms_list_destroy(item);
598
17.5k
      }
599
600
62.6k
      if (max_quality == YR_MAX_ATOM_QUALITY)
601
1.08k
        break;
602
603
61.5k
      child = child->next_sibling;
604
61.5k
    }
605
606
52.7k
    *atoms_quality = max_quality;
607
52.7k
    break;
608
609
20.1k
  case ATOM_TREE_AND:
610
611
    // The choosen nodes are the concatenation of the the nodes choosen from
612
    // all the children.
613
614
20.1k
    child = node->children_head;
615
616
60.4k
    while (child != NULL)
617
40.3k
    {
618
40.3k
      FAIL_ON_ERROR(_yr_atoms_choose(config, child, &item, &quality));
619
620
40.3k
      if (quality < min_quality)
621
22.1k
        min_quality = quality;
622
623
40.3k
      if (item != NULL)
624
33.4k
      {
625
33.4k
        tail = item;
626
265k
        while (tail->next != NULL) tail = tail->next;
627
628
33.4k
        tail->next = *chosen_atoms;
629
33.4k
        *chosen_atoms = item;
630
33.4k
      }
631
632
40.3k
      child = child->next_sibling;
633
40.3k
    }
634
635
20.1k
    *atoms_quality = min_quality;
636
20.1k
    break;
637
115k
  }
638
639
115k
  return ERROR_SUCCESS;
640
115k
}
641
642
////////////////////////////////////////////////////////////////////////////////
643
// Returns all combinations of lower and upper cases for a given atom. For
644
// atom "abc" the output would be "abc" "abC" "aBC" and so on. Resulting
645
// atoms are written into the output buffer in this format:
646
//
647
//  [size of atom 1] [atom 1]  ... [size of atom N] [atom N] [0]
648
//
649
// Notice the zero at the end to indicate where the output ends.
650
//
651
// The caller is responsible of providing a buffer large enough to hold the
652
// returned atoms.
653
//
654
static uint8_t* _yr_atoms_case_combinations(
655
    uint8_t* atom,
656
    int atom_length,
657
    int atom_offset,
658
    uint8_t* output_buffer)
659
17.8M
{
660
17.8M
  uint8_t c;
661
17.8M
  uint8_t* new_atom;
662
663
17.8M
  if (atom_offset + 1 < atom_length)
664
10.0M
    output_buffer = _yr_atoms_case_combinations(
665
10.0M
        atom, atom_length, atom_offset + 1, output_buffer);
666
667
17.8M
  c = atom[atom_offset];
668
669
17.8M
  if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
670
12.3M
  {
671
    // Write atom length.
672
12.3M
    *output_buffer = atom_length;
673
12.3M
    output_buffer++;
674
675
12.3M
    memcpy(output_buffer, atom, atom_length);
676
677
12.3M
    new_atom = output_buffer;
678
12.3M
    output_buffer += atom_length;
679
680
    // Swap character case.
681
12.3M
    if (c >= 'a' && c <= 'z')
682
10.8M
      new_atom[atom_offset] -= 32;
683
1.52M
    else
684
1.52M
      new_atom[atom_offset] += 32;
685
686
12.3M
    if (atom_offset + 1 < atom_length)
687
6.00M
      output_buffer = _yr_atoms_case_combinations(
688
6.00M
          new_atom, atom_length, atom_offset + 1, output_buffer);
689
12.3M
  }
690
691
17.8M
  if (atom_offset == 0)
692
1.80M
    *output_buffer = 0;
693
694
17.8M
  return output_buffer;
695
17.8M
}
696
697
// Size of buffer used in _yr_atoms_case_insensitive for storing the all
698
// the possible combinations for an atom. Each atom has up to YR_MAX_ATOM_LENGTH
699
// characters and each character has two possible values (upper and lower case).
700
// That means 2 ^ YR_MAX_ATOM_LENGTH combinations for an atom, where each atom
701
// occupies YR_MAX_ATOM_LENGTH + 1 bytes (the atom itself +1 byte for its
702
// length). One extra bytes is allocated for the zero value indicating the end.
703
704
#define CASE_COMBINATIONS_BUFFER_SIZE \
705
  (1 << YR_MAX_ATOM_LENGTH) * (YR_MAX_ATOM_LENGTH + 1) + 1
706
707
////////////////////////////////////////////////////////////////////////////////
708
// For a given list of atoms returns another list of atoms
709
// with every case combination.
710
//
711
static int _yr_atoms_case_insensitive(
712
    YR_ATOM_LIST_ITEM* atoms,
713
    YR_ATOM_LIST_ITEM** case_insensitive_atoms)
714
8.00k
{
715
8.00k
  YR_ATOM_LIST_ITEM* atom;
716
8.00k
  YR_ATOM_LIST_ITEM* new_atom;
717
718
8.00k
  uint8_t buffer[CASE_COMBINATIONS_BUFFER_SIZE];
719
8.00k
  uint8_t atom_length;
720
8.00k
  uint8_t* atoms_cursor;
721
722
8.00k
  int i;
723
724
8.00k
  *case_insensitive_atoms = NULL;
725
8.00k
  atom = atoms;
726
727
1.81M
  while (atom != NULL)
728
1.80M
  {
729
1.80M
    _yr_atoms_case_combinations(atom->atom.bytes, atom->atom.length, 0, buffer);
730
731
1.80M
    atoms_cursor = buffer;
732
1.80M
    atom_length = *atoms_cursor;
733
1.80M
    atoms_cursor++;
734
735
14.1M
    while (atom_length != 0)
736
12.3M
    {
737
12.3M
      new_atom = (YR_ATOM_LIST_ITEM*) yr_malloc(sizeof(YR_ATOM_LIST_ITEM));
738
739
12.3M
      if (new_atom == NULL)
740
0
        return ERROR_INSUFFICIENT_MEMORY;
741
742
61.2M
      for (i = 0; i < atom_length; i++)
743
48.9M
      {
744
48.9M
        new_atom->atom.bytes[i] = atoms_cursor[i];
745
48.9M
        new_atom->atom.mask[i] = 0xFF;
746
48.9M
      }
747
748
12.3M
      new_atom->atom.length = atom_length;
749
12.3M
      new_atom->forward_code_ref = atom->forward_code_ref;
750
12.3M
      new_atom->backward_code_ref = atom->backward_code_ref;
751
12.3M
      new_atom->backtrack = atom->backtrack;
752
12.3M
      new_atom->next = *case_insensitive_atoms;
753
754
12.3M
      *case_insensitive_atoms = new_atom;
755
756
12.3M
      atoms_cursor += atom_length;
757
12.3M
      atom_length = *atoms_cursor;
758
12.3M
      atoms_cursor++;
759
12.3M
    }
760
761
1.80M
    atom = atom->next;
762
1.80M
  }
763
764
8.00k
  return ERROR_SUCCESS;
765
8.00k
}
766
767
////////////////////////////////////////////////////////////////////////////////
768
// For a given list of atoms returns another list after a single byte xor
769
// has been applied to it.
770
//
771
static int _yr_atoms_xor(
772
    YR_ATOM_LIST_ITEM* atoms,
773
    uint8_t min,
774
    uint8_t max,
775
    YR_ATOM_LIST_ITEM** xor_atoms)
776
637
{
777
637
  YR_ATOM_LIST_ITEM* atom;
778
637
  YR_ATOM_LIST_ITEM* new_atom;
779
780
637
  int i, j;
781
637
  *xor_atoms = NULL;
782
637
  atom = atoms;
783
784
1.41k
  while (atom != NULL)
785
774
  {
786
98.2k
    for (j = min; j <= max; j++)
787
97.4k
    {
788
97.4k
      new_atom = (YR_ATOM_LIST_ITEM*) yr_malloc(sizeof(YR_ATOM_LIST_ITEM));
789
790
97.4k
      if (new_atom == NULL)
791
0
        return ERROR_INSUFFICIENT_MEMORY;
792
793
354k
      for (i = 0; i < atom->atom.length; i++)
794
257k
      {
795
257k
        new_atom->atom.bytes[i] = atom->atom.bytes[i] ^ j;
796
257k
        new_atom->atom.mask[i] = 0xFF;
797
257k
      }
798
799
97.4k
      new_atom->atom.length = yr_min(atom->atom.length, YR_MAX_ATOM_LENGTH);
800
97.4k
      new_atom->forward_code_ref = atom->forward_code_ref;
801
97.4k
      new_atom->backward_code_ref = atom->backward_code_ref;
802
97.4k
      new_atom->backtrack = atom->backtrack;
803
97.4k
      new_atom->next = *xor_atoms;
804
805
97.4k
      *xor_atoms = new_atom;
806
97.4k
    }
807
808
774
    atom = atom->next;
809
774
  }
810
637
  return ERROR_SUCCESS;
811
637
}
812
813
////////////////////////////////////////////////////////////////////////////////
814
// For a given list of atoms returns another list with the corresponding
815
// wide atoms. Wide atoms are just the original atoms with interleaved zeroes,
816
// for example: 01 02 -> 01 00 02 00
817
//
818
static int _yr_atoms_wide(
819
    YR_ATOM_LIST_ITEM* atoms,
820
    YR_ATOM_LIST_ITEM** wide_atoms)
821
3.80k
{
822
3.80k
  YR_ATOM_LIST_ITEM* atom;
823
3.80k
  YR_ATOM_LIST_ITEM* new_atom;
824
825
3.80k
  int i;
826
827
3.80k
  *wide_atoms = NULL;
828
3.80k
  atom = atoms;
829
830
377k
  while (atom != NULL)
831
373k
  {
832
373k
    new_atom = (YR_ATOM_LIST_ITEM*) yr_malloc(sizeof(YR_ATOM_LIST_ITEM));
833
834
373k
    if (new_atom == NULL)
835
0
      return ERROR_INSUFFICIENT_MEMORY;
836
837
1.86M
    for (i = 0; i < YR_MAX_ATOM_LENGTH; i++)
838
1.49M
    {
839
1.49M
      new_atom->atom.bytes[i] = 0;
840
1.49M
      new_atom->atom.mask[i] = 0xFF;
841
1.49M
    }
842
843
1.11M
    for (i = 0; i < atom->atom.length; i++)
844
1.11M
    {
845
1.11M
      if (i * 2 < YR_MAX_ATOM_LENGTH)
846
744k
        new_atom->atom.bytes[i * 2] = atom->atom.bytes[i];
847
370k
      else
848
370k
        break;
849
1.11M
    }
850
851
373k
    new_atom->atom.length = yr_min(atom->atom.length * 2, YR_MAX_ATOM_LENGTH);
852
373k
    new_atom->forward_code_ref = atom->forward_code_ref;
853
373k
    new_atom->backward_code_ref = atom->backward_code_ref;
854
373k
    new_atom->backtrack = atom->backtrack * 2;
855
373k
    new_atom->next = *wide_atoms;
856
857
373k
    *wide_atoms = new_atom;
858
859
373k
    atom = atom->next;
860
373k
  }
861
862
3.80k
  return ERROR_SUCCESS;
863
3.80k
}
864
865
struct STACK_ITEM
866
{
867
  RE_NODE* re_node;
868
  YR_ATOM_TREE_NODE* new_appending_node;
869
};
870
871
#define make_atom_from_re_nodes(atom, nodes_length, nodes)   \
872
955k
  {                                                          \
873
955k
    atom.length = nodes_length;                              \
874
4.71M
    for (i = 0; i < atom.length; i++)                        \
875
3.76M
    {                                                        \
876
3.76M
      atom.bytes[i] = (uint8_t) (recent_re_nodes)[i]->value; \
877
3.76M
      atom.mask[i] = (uint8_t) (recent_re_nodes)[i]->mask;   \
878
3.76M
    }                                                        \
879
955k
  }
880
881
////////////////////////////////////////////////////////////////////////////////
882
// Extract atoms from a regular expression. This is a helper function used by
883
// yr_atoms_extract_from_re that receives the abstract syntax tree for a regexp
884
// (or hex pattern) and builds an atom tree. The appending_node argument is a
885
// pointer to the ATOM_TREE_OR node at the root of the atom tree. This function
886
// creates the tree by appending new nodes to it.
887
//
888
static int _yr_atoms_extract_from_re(
889
    YR_ATOMS_CONFIG* config,
890
    RE_AST* re_ast,
891
    YR_ATOM_TREE_NODE* appending_node)
892
12.4k
{
893
12.4k
  YR_STACK* stack;
894
12.4k
  RE_NODE* re_node;
895
896
12.4k
  YR_ATOM atom = {0};
897
12.4k
  YR_ATOM best_atom = {0};
898
899
12.4k
  struct STACK_ITEM si;
900
901
12.4k
  int i, max_iters, shift;
902
12.4k
  int quality;
903
12.4k
  int best_quality = -1;
904
12.4k
  int n = 0;
905
12.4k
  int remaining_range_unrolls = RE_MAX_RANGE_UNROLL;
906
907
12.4k
  YR_ATOM_TREE_NODE* and_node;
908
12.4k
  YR_ATOM_TREE_NODE* left_node;
909
12.4k
  YR_ATOM_TREE_NODE* right_node;
910
911
  // The RE_NODEs most recently visited that can conform an atom (ie:
912
  // RE_NODE_LITERAL, RE_NODE_MASKED_LITERAL and RE_NODE_ANY). The number of
913
  // items in this array is n.
914
12.4k
  RE_NODE* recent_re_nodes[YR_MAX_ATOM_LENGTH];
915
916
  // The RE_NODEs corresponding to the best atom found so far for the current
917
  // appending node.
918
12.4k
  RE_NODE* best_atom_re_nodes[YR_MAX_ATOM_LENGTH];
919
920
  // This holds the ATOM_TREE_OR node where leaves (ATOM_TREE_LEAF) are
921
  // currently being appended.
922
12.4k
  YR_ATOM_TREE_NODE* current_appending_node = NULL;
923
924
  // This holds the ATOM_TREE_LEAF node whose atom is currently being updated.
925
12.4k
  YR_ATOM_TREE_NODE* leaf = NULL;
926
927
12.4k
  FAIL_ON_ERROR(yr_stack_create(1024, sizeof(si), &stack));
928
929
  // This first item pushed in the stack is the last one to be poped out, the
930
  // sole purpose of this item is forcing that any pending leaf is appended to
931
  // appending_node during the last iteration of the loop.
932
12.4k
  si.re_node = NULL;
933
12.4k
  si.new_appending_node = appending_node;
934
935
12.4k
  FAIL_ON_ERROR_WITH_CLEANUP(
936
12.4k
      yr_stack_push(stack, (void*) &si), yr_stack_destroy(stack));
937
938
  // Start processing the root node.
939
12.4k
  si.re_node = re_ast->root_node;
940
941
  // Leaf nodes are initially appended to the node passed in the appending_node,
942
  // argument which is the root ATOM_TREE_OR node that is empty at this point.
943
12.4k
  si.new_appending_node = appending_node;
944
945
12.4k
  FAIL_ON_ERROR_WITH_CLEANUP(
946
12.4k
      yr_stack_push(stack, (void*) &si), yr_stack_destroy(stack));
947
948
1.27M
  while (yr_stack_pop(stack, (void*) &si))
949
1.25M
  {
950
    // Change the appending node if the item poped from the stack says so.
951
1.25M
    if (si.new_appending_node != NULL)
952
129k
    {
953
      // Before changing the appending node let's append any pending leaf to
954
      // the current appending node.
955
129k
      if (n > 0)
956
47.2k
      {
957
47.2k
        make_atom_from_re_nodes(atom, n, recent_re_nodes);
958
47.2k
        shift = _yr_atoms_trim(&atom);
959
47.2k
        quality = config->get_atom_quality(config, &atom);
960
961
47.2k
        FAIL_ON_NULL_WITH_CLEANUP(
962
47.2k
            leaf = _yr_atoms_tree_node_create(ATOM_TREE_LEAF),
963
47.2k
            yr_stack_destroy(stack));
964
965
47.2k
        if (quality > best_quality)
966
36.2k
        {
967
36.2k
          memcpy(&leaf->atom, &atom, sizeof(atom));
968
36.2k
          memcpy(
969
36.2k
              &leaf->re_nodes,
970
36.2k
              &recent_re_nodes[shift],
971
36.2k
              sizeof(recent_re_nodes) - shift * sizeof(recent_re_nodes[0]));
972
36.2k
        }
973
11.0k
        else
974
11.0k
        {
975
11.0k
          memcpy(&leaf->atom, &best_atom, sizeof(best_atom));
976
11.0k
          memcpy(
977
11.0k
              &leaf->re_nodes, &best_atom_re_nodes, sizeof(best_atom_re_nodes));
978
11.0k
        }
979
980
47.2k
        _yr_atoms_tree_node_append(current_appending_node, leaf);
981
47.2k
        n = 0;
982
47.2k
      }
983
984
129k
      current_appending_node = si.new_appending_node;
985
129k
      best_quality = -1;
986
129k
    }
987
988
1.25M
    if (si.re_node != NULL)
989
1.18M
    {
990
1.18M
      switch (si.re_node->type)
991
1.18M
      {
992
1.02M
      case RE_NODE_LITERAL:
993
1.02M
      case RE_NODE_MASKED_LITERAL:
994
1.05M
      case RE_NODE_ANY:
995
996
1.05M
        if (n < YR_MAX_ATOM_LENGTH)
997
130k
        {
998
130k
          recent_re_nodes[n] = si.re_node;
999
130k
          best_atom_re_nodes[n] = si.re_node;
1000
130k
          best_atom.bytes[n] = (uint8_t) si.re_node->value;
1001
130k
          best_atom.mask[n] = (uint8_t) si.re_node->mask;
1002
130k
          best_atom.length = ++n;
1003
130k
        }
1004
921k
        else if (best_quality < YR_MAX_ATOM_QUALITY)
1005
908k
        {
1006
908k
          make_atom_from_re_nodes(atom, n, recent_re_nodes);
1007
908k
          shift = _yr_atoms_trim(&atom);
1008
908k
          quality = config->get_atom_quality(config, &atom);
1009
1010
908k
          if (quality > best_quality)
1011
22.6k
          {
1012
105k
            for (i = 0; i < atom.length; i++)
1013
82.6k
            {
1014
82.6k
              best_atom.bytes[i] = atom.bytes[i];
1015
82.6k
              best_atom.mask[i] = atom.mask[i];
1016
82.6k
              best_atom_re_nodes[i] = recent_re_nodes[i + shift];
1017
82.6k
            }
1018
1019
22.6k
            best_atom.length = atom.length;
1020
22.6k
            best_quality = quality;
1021
22.6k
          }
1022
1023
3.63M
          for (i = 1; i < YR_MAX_ATOM_LENGTH; i++)
1024
2.72M
            recent_re_nodes[i - 1] = recent_re_nodes[i];
1025
1026
908k
          recent_re_nodes[YR_MAX_ATOM_LENGTH - 1] = si.re_node;
1027
908k
        }
1028
1029
1.05M
        break;
1030
1031
67.5k
      case RE_NODE_CONCAT:
1032
1033
67.5k
        re_node = si.re_node->children_tail;
1034
1035
        // Push children right to left, they are poped left to right.
1036
1.16M
        while (re_node != NULL)
1037
1.09M
        {
1038
1.09M
          si.new_appending_node = NULL;
1039
1.09M
          si.re_node = re_node;
1040
1041
1.09M
          FAIL_ON_ERROR_WITH_CLEANUP(
1042
1.09M
              yr_stack_push(stack, &si), yr_stack_destroy(stack));
1043
1044
1.09M
          re_node = re_node->prev_sibling;
1045
1.09M
        }
1046
1047
67.5k
        break;
1048
1049
67.5k
      case RE_NODE_ALT:
1050
1051
        // Create ATOM_TREE_AND node with two ATOM_TREE_OR children nodes.
1052
20.1k
        and_node = _yr_atoms_tree_node_create(ATOM_TREE_AND);
1053
20.1k
        left_node = _yr_atoms_tree_node_create(ATOM_TREE_OR);
1054
20.1k
        right_node = _yr_atoms_tree_node_create(ATOM_TREE_OR);
1055
1056
20.1k
        if (and_node == NULL || left_node == NULL || right_node == NULL)
1057
0
        {
1058
0
          _yr_atoms_tree_node_destroy(and_node);
1059
0
          _yr_atoms_tree_node_destroy(left_node);
1060
0
          _yr_atoms_tree_node_destroy(right_node);
1061
1062
0
          yr_stack_destroy(stack);
1063
1064
0
          return ERROR_INSUFFICIENT_MEMORY;
1065
0
        }
1066
1067
20.1k
        and_node->children_head = left_node;
1068
20.1k
        and_node->children_tail = right_node;
1069
20.1k
        left_node->next_sibling = right_node;
1070
1071
        // Add the ATOM_TREE_AND as children of the current node.
1072
20.1k
        _yr_atoms_tree_node_append(current_appending_node, and_node);
1073
1074
20.1k
        re_node = si.re_node;
1075
1076
20.1k
        si.new_appending_node = current_appending_node;
1077
20.1k
        si.re_node = NULL;
1078
1079
20.1k
        FAIL_ON_ERROR_WITH_CLEANUP(
1080
20.1k
            yr_stack_push(stack, &si), yr_stack_destroy(stack));
1081
1082
        // RE_NODE_ALT nodes has only two children, so children_head is the
1083
        // left one, and children_tail is right one.
1084
20.1k
        si.new_appending_node = right_node;
1085
20.1k
        si.re_node = re_node->children_tail;
1086
1087
20.1k
        FAIL_ON_ERROR_WITH_CLEANUP(
1088
20.1k
            yr_stack_push(stack, &si), yr_stack_destroy(stack));
1089
1090
20.1k
        si.new_appending_node = left_node;
1091
20.1k
        si.re_node = re_node->children_head;
1092
1093
20.1k
        FAIL_ON_ERROR_WITH_CLEANUP(
1094
20.1k
            yr_stack_push(stack, &si), yr_stack_destroy(stack));
1095
1096
20.1k
        break;
1097
1098
1.22k
      case RE_NODE_PLUS:
1099
1100
1.22k
        re_node = si.re_node;
1101
1102
1.22k
        si.new_appending_node = current_appending_node;
1103
1.22k
        si.re_node = NULL;
1104
1105
1.22k
        FAIL_ON_ERROR_WITH_CLEANUP(
1106
1.22k
            yr_stack_push(stack, &si), yr_stack_destroy(stack));
1107
1108
1.22k
        si.new_appending_node = NULL;
1109
        // RE_NODE_PLUS nodes has a single child, which is children_head.
1110
1.22k
        si.re_node = re_node->children_head;
1111
1112
1.22k
        FAIL_ON_ERROR_WITH_CLEANUP(
1113
1.22k
            yr_stack_push(stack, &si), yr_stack_destroy(stack));
1114
1115
1.22k
        break;
1116
1117
22.3k
      case RE_NODE_RANGE:
1118
1119
22.3k
        re_node = si.re_node;
1120
1121
22.3k
        si.new_appending_node = current_appending_node;
1122
22.3k
        si.re_node = NULL;
1123
1124
22.3k
        FAIL_ON_ERROR_WITH_CLEANUP(
1125
22.3k
            yr_stack_push(stack, &si), yr_stack_destroy(stack));
1126
1127
22.3k
        si.new_appending_node = NULL;
1128
1129
        // RE_NODE_RANGE nodes has a single child, which is children_head.
1130
22.3k
        si.re_node = re_node->children_head;
1131
1132
        // In a regexp like /a{10,20}/ the optimal atom is 'aaaa' (assuming
1133
        // that YR_MAX_ATOM_LENGTH = 4) because the 'a' character must appear
1134
        // at least 10 times in the matching string. Each call in the loop
1135
        // will append one 'a' to the atom, so YR_MAX_ATOM_LENGTH iterations
1136
        // are enough. However, if the child node itself appends a pending leaf
1137
        // on exit (e.g. another RE_NODE_RANGE in /((a){4}){4}/), each
1138
        // repetition after that leaf is appended starts with n = 0 and produces
1139
        // identical atoms, so at most 1 iteration (if n == 0) or 2 iterations
1140
        // (if n > 0) are needed.
1141
22.3k
        max_iters = yr_min(re_node->start, YR_MAX_ATOM_LENGTH);
1142
1143
22.3k
        re_node = re_node->children_head;
1144
1145
36.2k
        while (re_node != NULL && re_node->type == RE_NODE_CONCAT)
1146
13.9k
          re_node = re_node->children_tail;
1147
1148
22.3k
        if (re_node != NULL &&
1149
22.3k
            re_node->type != RE_NODE_LITERAL &&
1150
12.4k
            re_node->type != RE_NODE_MASKED_LITERAL &&
1151
12.4k
            re_node->type != RE_NODE_ANY)
1152
11.4k
        {
1153
11.4k
          max_iters = yr_min(max_iters, n > 0 ? 2 : 1);
1154
11.4k
        }
1155
1156
22.3k
        if (max_iters > 1)
1157
7.90k
        {
1158
7.90k
          int extra_iters = yr_min(max_iters - 1, remaining_range_unrolls);
1159
7.90k
          remaining_range_unrolls -= extra_iters;
1160
7.90k
          max_iters = 1 + extra_iters;
1161
7.90k
        }
1162
1163
55.4k
        for (i = 0; i < max_iters; i++)
1164
33.0k
        {
1165
33.0k
          FAIL_ON_ERROR_WITH_CLEANUP(
1166
33.0k
              yr_stack_push(stack, &si), yr_stack_destroy(stack));
1167
33.0k
        }
1168
1169
22.3k
        break;
1170
1171
22.3k
      case RE_NODE_RANGE_ANY:
1172
5.73k
      case RE_NODE_STAR:
1173
7.38k
      case RE_NODE_CLASS:
1174
7.87k
      case RE_NODE_WORD_CHAR:
1175
8.70k
      case RE_NODE_NON_WORD_CHAR:
1176
11.1k
      case RE_NODE_SPACE:
1177
11.6k
      case RE_NODE_NON_SPACE:
1178
12.0k
      case RE_NODE_DIGIT:
1179
12.4k
      case RE_NODE_NON_DIGIT:
1180
15.8k
      case RE_NODE_EMPTY:
1181
16.4k
      case RE_NODE_ANCHOR_START:
1182
18.9k
      case RE_NODE_ANCHOR_END:
1183
19.4k
      case RE_NODE_WORD_BOUNDARY:
1184
19.8k
      case RE_NODE_NON_WORD_BOUNDARY:
1185
20.0k
      case RE_NODE_NOT_LITERAL:
1186
20.5k
      case RE_NODE_MASKED_NOT_LITERAL:
1187
1188
20.5k
        si.new_appending_node = current_appending_node;
1189
20.5k
        si.re_node = NULL;
1190
1191
20.5k
        FAIL_ON_ERROR_WITH_CLEANUP(
1192
20.5k
            yr_stack_push(stack, &si), yr_stack_destroy(stack));
1193
1194
20.5k
        break;
1195
1196
0
      default:
1197
0
        assert(false);
1198
1.18M
      }
1199
1.18M
    }
1200
1.25M
  }
1201
1202
12.4k
  yr_stack_destroy(stack);
1203
1204
12.4k
  return ERROR_SUCCESS;
1205
12.4k
}
1206
1207
////////////////////////////////////////////////////////////////////////////////
1208
// Makes an exact copy of an YR_ATOM_LIST_ITEM.
1209
//
1210
static YR_ATOM_LIST_ITEM* _yr_atoms_clone_list_item(YR_ATOM_LIST_ITEM* item)
1211
1.83M
{
1212
1.83M
  YR_ATOM_LIST_ITEM* clone = (YR_ATOM_LIST_ITEM*) yr_malloc(
1213
1.83M
      sizeof(YR_ATOM_LIST_ITEM));
1214
1215
1.83M
  if (clone == NULL)
1216
0
    return NULL;
1217
1218
1.83M
  memcpy(clone, item, sizeof(YR_ATOM_LIST_ITEM));
1219
1220
1.83M
  return clone;
1221
1.83M
}
1222
1223
////////////////////////////////////////////////////////////////////////////////
1224
// Given list of atoms that may contain wildcards, replace those wildcarded
1225
// atoms with a list of non-wildcarded atoms covering all the combinations
1226
// allowed by the wildcarded atom. For example, the atom {01 ?2 03} will be
1227
// replaced by {01 02 03}, {01 12 03}, {01 22 03} .. {01 F2 03}. The list
1228
// is modified in-place.
1229
//
1230
// Args:
1231
//   atoms: Pointer to first element of the list.
1232
//
1233
// Returns:
1234
//   ERROR_SUCCESS or ERROR_INSUFFICIENT_MEMORY.
1235
//
1236
static int _yr_atoms_expand_wildcards(YR_ATOM_LIST_ITEM* atoms)
1237
12.4k
{
1238
12.4k
  int i;
1239
1240
12.4k
  YR_ATOM_LIST_ITEM* atom = atoms;
1241
12.4k
  YR_ATOM_LIST_ITEM* new_atom;
1242
12.4k
  YR_ATOM_LIST_ITEM* prev_atom;
1243
12.4k
  YR_ATOM_LIST_ITEM* next_atom;
1244
1245
1.88M
  while (atom != NULL)
1246
1.87M
  {
1247
1.87M
    bool expanded = false;
1248
1249
9.12M
    for (i = 0; i < atom->atom.length; i++)
1250
7.25M
    {
1251
7.25M
      uint16_t a, s, e, incr = 1;
1252
1253
7.25M
      switch (atom->atom.mask[i])
1254
7.25M
      {
1255
6.56k
      case 0x00:
1256
6.56k
        expanded = true;
1257
6.56k
        s = 0x00;
1258
6.56k
        e = 0xFF;
1259
6.56k
        break;
1260
1261
6.68k
      case 0x0F:
1262
6.68k
        expanded = true;
1263
6.68k
        s = atom->atom.bytes[i];
1264
6.68k
        e = atom->atom.bytes[i] | 0xF0;
1265
6.68k
        incr = 0x10;
1266
6.68k
        break;
1267
1268
3.95k
      case 0xF0:
1269
3.95k
        expanded = true;
1270
3.95k
        s = atom->atom.bytes[i];
1271
3.95k
        e = atom->atom.bytes[i] | 0x0F;
1272
3.95k
        break;
1273
1274
7.23M
      default:
1275
7.23M
        s = 0;
1276
7.23M
        e = 0;
1277
7.25M
      }
1278
1279
7.25M
      if (s != e)
1280
17.2k
      {
1281
17.2k
        atom->atom.bytes[i] = (uint8_t) s;
1282
17.2k
        atom->atom.mask[i] = 0xFF;
1283
17.2k
      }
1284
1285
7.25M
      prev_atom = atom;
1286
7.25M
      next_atom = atom->next;
1287
1288
9.08M
      for (a = s + incr; a <= e; a += incr)
1289
1.83M
      {
1290
1.83M
        new_atom = _yr_atoms_clone_list_item(atom);
1291
1292
1.83M
        if (new_atom == NULL)
1293
0
          return ERROR_INSUFFICIENT_MEMORY;
1294
1295
1.83M
        new_atom->atom.bytes[i] = (uint8_t) a;
1296
1.83M
        new_atom->atom.mask[i] = 0xFF;
1297
1.83M
        new_atom->next = next_atom;
1298
1.83M
        prev_atom->next = new_atom;
1299
1.83M
        prev_atom = new_atom;
1300
1.83M
      }
1301
7.25M
    }
1302
1303
1.87M
    if (!expanded)
1304
1.85M
      atom = atom->next;
1305
1.87M
  }
1306
1307
12.4k
  return ERROR_SUCCESS;
1308
12.4k
}
1309
1310
////////////////////////////////////////////////////////////////////////////////
1311
// Extract atoms from a regular expression. This function receives the abstract
1312
// syntax tree for a regexp (or hex pattern) and returns a list of atoms that
1313
// should be added to the Aho-Corasick automaton.
1314
//
1315
int yr_atoms_extract_from_re(
1316
    YR_ATOMS_CONFIG* config,
1317
    RE_AST* re_ast,
1318
    YR_MODIFIER modifier,
1319
    YR_ATOM_LIST_ITEM** atoms,
1320
    int* min_atom_quality)
1321
12.4k
{
1322
12.4k
  YR_ATOM_TREE* atom_tree = (YR_ATOM_TREE*) yr_malloc(sizeof(YR_ATOM_TREE));
1323
1324
12.4k
  YR_ATOM_LIST_ITEM* wide_atoms;
1325
12.4k
  YR_ATOM_LIST_ITEM* case_insensitive_atoms;
1326
1327
12.4k
  if (atom_tree == NULL)
1328
0
    return ERROR_INSUFFICIENT_MEMORY;
1329
1330
12.4k
  atom_tree->root_node = _yr_atoms_tree_node_create(ATOM_TREE_OR);
1331
1332
12.4k
  if (atom_tree->root_node == NULL)
1333
0
  {
1334
0
    _yr_atoms_tree_destroy(atom_tree);
1335
0
    return ERROR_INSUFFICIENT_MEMORY;
1336
0
  }
1337
1338
12.4k
  FAIL_ON_ERROR_WITH_CLEANUP(
1339
12.4k
      _yr_atoms_extract_from_re(config, re_ast, atom_tree->root_node),
1340
12.4k
      _yr_atoms_tree_destroy(atom_tree));
1341
1342
  // Initialize atom list
1343
12.4k
  *atoms = NULL;
1344
1345
  // Choose the atoms that will be used.
1346
12.4k
  FAIL_ON_ERROR_WITH_CLEANUP(
1347
12.4k
      _yr_atoms_choose(config, atom_tree->root_node, atoms, min_atom_quality),
1348
12.4k
      _yr_atoms_tree_destroy(atom_tree));
1349
1350
12.4k
  _yr_atoms_tree_destroy(atom_tree);
1351
1352
12.4k
  FAIL_ON_ERROR_WITH_CLEANUP(
1353
12.4k
      _yr_atoms_expand_wildcards(*atoms),
1354
12.4k
      {  // Cleanup
1355
12.4k
        yr_atoms_list_destroy(*atoms);
1356
12.4k
        *atoms = NULL;
1357
12.4k
      });
1358
1359
  // Don't do convert atoms to wide here if either base64 modifier is used.
1360
  // This is to avoid the situation where we have "base64 wide" because
1361
  // the wide has already been applied BEFORE the base64 encoding.
1362
12.4k
  if (modifier.flags & STRING_FLAGS_WIDE &&
1363
2.37k
      !(modifier.flags & STRING_FLAGS_BASE64 ||
1364
2.10k
        modifier.flags & STRING_FLAGS_BASE64_WIDE))
1365
1.48k
  {
1366
1.48k
    FAIL_ON_ERROR_WITH_CLEANUP(
1367
1.48k
        _yr_atoms_wide(*atoms, &wide_atoms),
1368
1.48k
        {  // Cleanup
1369
1.48k
          yr_atoms_list_destroy(*atoms);
1370
1.48k
          yr_atoms_list_destroy(wide_atoms);
1371
1.48k
          *atoms = NULL;
1372
1.48k
        });
1373
1374
1.48k
    if (modifier.flags & STRING_FLAGS_ASCII)
1375
598
    {
1376
598
      *atoms = _yr_atoms_list_concat(*atoms, wide_atoms);
1377
598
    }
1378
891
    else
1379
891
    {
1380
891
      yr_atoms_list_destroy(*atoms);
1381
891
      *atoms = wide_atoms;
1382
891
    }
1383
1.48k
  }
1384
1385
12.4k
  if (modifier.flags & STRING_FLAGS_NO_CASE)
1386
2.30k
  {
1387
2.30k
    FAIL_ON_ERROR_WITH_CLEANUP(
1388
2.30k
        _yr_atoms_case_insensitive(*atoms, &case_insensitive_atoms),
1389
2.30k
        {  // Cleanup
1390
2.30k
          yr_atoms_list_destroy(*atoms);
1391
2.30k
          yr_atoms_list_destroy(case_insensitive_atoms);
1392
2.30k
          *atoms = NULL;
1393
2.30k
        });
1394
1395
2.30k
    *atoms = _yr_atoms_list_concat(*atoms, case_insensitive_atoms);
1396
2.30k
  }
1397
1398
12.4k
  return ERROR_SUCCESS;
1399
12.4k
}
1400
1401
////////////////////////////////////////////////////////////////////////////////
1402
// Extract atoms from a string.
1403
//
1404
int yr_atoms_extract_from_string(
1405
    YR_ATOMS_CONFIG* config,
1406
    uint8_t* string,
1407
    int32_t string_length,
1408
    YR_MODIFIER modifier,
1409
    YR_ATOM_LIST_ITEM** atoms,
1410
    int* min_atom_quality)
1411
46.2k
{
1412
46.2k
  YR_ATOM_LIST_ITEM* item;
1413
46.2k
  YR_ATOM_LIST_ITEM* case_insensitive_atoms;
1414
46.2k
  YR_ATOM_LIST_ITEM* xor_atoms;
1415
46.2k
  YR_ATOM_LIST_ITEM* wide_atoms;
1416
1417
46.2k
  YR_ATOM atom;
1418
1419
46.2k
  int quality, max_quality;
1420
46.2k
  int i;
1421
1422
46.2k
  item = (YR_ATOM_LIST_ITEM*) yr_malloc(sizeof(YR_ATOM_LIST_ITEM));
1423
1424
46.2k
  if (item == NULL)
1425
0
    return ERROR_INSUFFICIENT_MEMORY;
1426
1427
46.2k
  item->forward_code_ref = YR_ARENA_NULL_REF;
1428
46.2k
  item->backward_code_ref = YR_ARENA_NULL_REF;
1429
46.2k
  item->next = NULL;
1430
46.2k
  item->backtrack = 0;
1431
1432
46.2k
  item->atom.length = yr_min(string_length, YR_MAX_ATOM_LENGTH);
1433
1434
127k
  for (i = 0; i < item->atom.length; i++)
1435
81.6k
  {
1436
81.6k
    item->atom.bytes[i] = string[i];
1437
81.6k
    item->atom.mask[i] = 0xFF;
1438
81.6k
  }
1439
1440
46.2k
  max_quality = config->get_atom_quality(config, &item->atom);
1441
1442
46.2k
  atom.length = YR_MAX_ATOM_LENGTH;
1443
46.2k
  memset(atom.mask, 0xFF, atom.length);
1444
1445
46.2k
  for (i = YR_MAX_ATOM_LENGTH;
1446
133k
       i < string_length && max_quality < YR_MAX_ATOM_QUALITY;
1447
86.8k
       i++)
1448
86.8k
  {
1449
86.8k
    atom.length = YR_MAX_ATOM_LENGTH;
1450
86.8k
    memcpy(atom.bytes, string + i - YR_MAX_ATOM_LENGTH + 1, atom.length);
1451
1452
86.8k
    quality = config->get_atom_quality(config, &atom);
1453
1454
86.8k
    if (quality > max_quality)
1455
4.93k
    {
1456
4.93k
      memcpy(&item->atom, &atom, sizeof(atom));
1457
4.93k
      item->backtrack = i - YR_MAX_ATOM_LENGTH + 1;
1458
4.93k
      max_quality = quality;
1459
4.93k
    }
1460
86.8k
  }
1461
1462
46.2k
  *atoms = item;
1463
46.2k
  *min_atom_quality = max_quality;
1464
1465
46.2k
  if (modifier.flags & STRING_FLAGS_WIDE)
1466
2.31k
  {
1467
2.31k
    FAIL_ON_ERROR_WITH_CLEANUP(
1468
2.31k
        _yr_atoms_wide(*atoms, &wide_atoms),
1469
2.31k
        {  // Cleanup
1470
2.31k
          yr_atoms_list_destroy(*atoms);
1471
2.31k
          yr_atoms_list_destroy(wide_atoms);
1472
2.31k
          *atoms = NULL;
1473
2.31k
        });
1474
1475
2.31k
    if (modifier.flags & STRING_FLAGS_ASCII)
1476
1.35k
    {
1477
1.35k
      *atoms = _yr_atoms_list_concat(*atoms, wide_atoms);
1478
1.35k
    }
1479
965
    else
1480
965
    {
1481
965
      yr_atoms_list_destroy(*atoms);
1482
965
      *atoms = wide_atoms;
1483
965
    }
1484
2.31k
  }
1485
1486
46.2k
  if (modifier.flags & STRING_FLAGS_NO_CASE)
1487
5.69k
  {
1488
5.69k
    FAIL_ON_ERROR_WITH_CLEANUP(
1489
5.69k
        _yr_atoms_case_insensitive(*atoms, &case_insensitive_atoms),
1490
5.69k
        {  // Cleanup
1491
5.69k
          yr_atoms_list_destroy(*atoms);
1492
5.69k
          yr_atoms_list_destroy(case_insensitive_atoms);
1493
5.69k
          *atoms = NULL;
1494
5.69k
        });
1495
1496
5.69k
    *atoms = _yr_atoms_list_concat(*atoms, case_insensitive_atoms);
1497
5.69k
  }
1498
1499
46.2k
  if (modifier.flags & STRING_FLAGS_XOR)
1500
637
  {
1501
637
    FAIL_ON_ERROR_WITH_CLEANUP(
1502
637
        _yr_atoms_xor(*atoms, modifier.xor_min, modifier.xor_max, &xor_atoms),
1503
637
        {  // Cleanup
1504
637
          yr_atoms_list_destroy(*atoms);
1505
637
          yr_atoms_list_destroy(xor_atoms);
1506
637
          *atoms = NULL;
1507
637
        });
1508
1509
637
    yr_atoms_list_destroy(*atoms);
1510
637
    *atoms = xor_atoms;
1511
637
  }
1512
1513
  // Recheck the atom quality, in case we have just generated some poor atoms.
1514
  // https://github.com/VirusTotal/yara/issues/1172
1515
198k
  for (item = *atoms; item != NULL; item = item->next)
1516
152k
  {
1517
152k
    quality = config->get_atom_quality(config, &item->atom);
1518
152k
    if (quality < *min_atom_quality)
1519
1.11k
      *min_atom_quality = quality;
1520
152k
  }
1521
1522
46.2k
  return ERROR_SUCCESS;
1523
46.2k
}
1524
1525
////////////////////////////////////////////////////////////////////////////////
1526
// Prints an atom tree node. Used only for debugging purposes.
1527
//
1528
void yr_atoms_tree_node_print(YR_ATOM_TREE_NODE* node)
1529
0
{
1530
0
  YR_ATOM_TREE_NODE* child;
1531
1532
0
  if (node == NULL)
1533
0
  {
1534
0
    printf("Empty tree node\n");
1535
0
    return;
1536
0
  }
1537
1538
0
  switch (node->type)
1539
0
  {
1540
0
  case ATOM_TREE_LEAF:
1541
0
    for (int i = 0; i < node->atom.length; i++)
1542
0
      printf("%02X", node->atom.bytes[i]);
1543
0
    break;
1544
1545
0
  case ATOM_TREE_AND:
1546
0
  case ATOM_TREE_OR:
1547
0
    if (node->type == ATOM_TREE_AND)
1548
0
      printf("AND");
1549
0
    else
1550
0
      printf("OR");
1551
0
    printf("(");
1552
0
    child = node->children_head;
1553
0
    while (child != NULL)
1554
0
    {
1555
0
      yr_atoms_tree_node_print(child);
1556
0
      child = child->next_sibling;
1557
0
      if (child != NULL)
1558
0
        printf(",");
1559
0
    }
1560
0
    printf(")");
1561
0
    break;
1562
0
  }
1563
0
}