Coverage Report

Created: 2026-12-01 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/yara/libyara/modules/pe/pe.c
Line
Count
Source
1
/*
2
Copyright (c) 2014. 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
#include <ctype.h>
31
#include <stdio.h>
32
#include <time.h>
33
34
#include "../crypto.h"
35
#if defined(HAVE_LIBCRYPTO)
36
#include <authenticode-parser/authenticode.h>
37
#include <openssl/evp.h>
38
#endif
39
40
#include <yara/dotnet.h>
41
#include <yara/endian.h>
42
#include <yara/limits.h>
43
#include <yara/mem.h>
44
#include <yara/modules.h>
45
#include <yara/pe.h>
46
#include <yara/pe_utils.h>
47
#include <yara/strutils.h>
48
#include <yara/unaligned.h>
49
#include <yara/utils.h>
50
51
#define MODULE_NAME pe
52
53
0
#define IMPORT_STANDARD 1
54
0
#define IMPORT_DELAYED  2
55
#define IMPORT_ANY      (~0)
56
57
// http://msdn.microsoft.com/en-us/library/ms648009(v=vs.85).aspx
58
#define RESOURCE_TYPE_CURSOR       1
59
#define RESOURCE_TYPE_BITMAP       2
60
#define RESOURCE_TYPE_ICON         3
61
#define RESOURCE_TYPE_MENU         4
62
#define RESOURCE_TYPE_DIALOG       5
63
#define RESOURCE_TYPE_STRING       6
64
#define RESOURCE_TYPE_FONTDIR      7
65
#define RESOURCE_TYPE_FONT         8
66
#define RESOURCE_TYPE_ACCELERATOR  9
67
#define RESOURCE_TYPE_RCDATA       10
68
#define RESOURCE_TYPE_MESSAGETABLE 11
69
#define RESOURCE_TYPE_GROUP_CURSOR \
70
  12  // MAKEINTRESOURCE((ULONG_PTR)(RT_CURSOR) + 11)
71
#define RESOURCE_TYPE_GROUP_ICON \
72
  14  // MAKEINTRESOURCE((ULONG_PTR)(RT_ICON) + 11)
73
347k
#define RESOURCE_TYPE_VERSION    16
74
#define RESOURCE_TYPE_DLGINCLUDE 17
75
#define RESOURCE_TYPE_PLUGPLAY   19
76
#define RESOURCE_TYPE_VXD        20
77
#define RESOURCE_TYPE_ANICURSOR  21
78
#define RESOURCE_TYPE_ANIICON    22
79
#define RESOURCE_TYPE_HTML       23
80
#define RESOURCE_TYPE_MANIFEST   24
81
82
347k
#define RESOURCE_CALLBACK_CONTINUE 0
83
347k
#define RESOURCE_CALLBACK_ABORT    1
84
85
16.0k
#define RESOURCE_ITERATOR_FINISHED 0
86
2.19M
#define RESOURCE_ITERATOR_ABORTED  1
87
88
1.09G
#define MAX_PE_IMPORTS             16384
89
#define MAX_PE_EXPORTS             16384
90
#define MAX_EXPORT_NAME_LENGTH     512
91
#define MAX_IMPORT_DLL_NAME_LENGTH 256
92
347k
#define MAX_RESOURCES              65536
93
94
#define IS_RESOURCE_SUBDIRECTORY(entry) \
95
4.39M
  (yr_le32toh((entry)->OffsetToData) & 0x80000000)
96
97
2.19M
#define RESOURCE_OFFSET(entry) (yr_le32toh((entry)->OffsetToData) & 0x7FFFFFFF)
98
99
typedef int (*RESOURCE_CALLBACK_FUNC)(
100
    PIMAGE_RESOURCE_DATA_ENTRY rsrc_data,
101
    int rsrc_type,
102
    int rsrc_id,
103
    int rsrc_language,
104
    const IMAGE_RESOURCE_DIR_STRING_U* type_string,
105
    const IMAGE_RESOURCE_DIR_STRING_U* name_string,
106
    const IMAGE_RESOURCE_DIR_STRING_U* lang_string,
107
    void* cb_data);
108
109
static size_t available_space(PE* pe, void* pointer)
110
3.68M
{
111
3.68M
  if ((uint8_t*) pointer < pe->data)
112
0
    return 0;
113
114
3.68M
  if ((uint8_t*) pointer >= pe->data + pe->data_size)
115
923
    return 0;
116
117
3.68M
  return pe->data + pe->data_size - (uint8_t*) pointer;
118
3.68M
}
119
120
static int wide_string_fits_in_pe(PE* pe, char* data)
121
18.5k
{
122
18.5k
  size_t i = 0;
123
18.5k
  size_t space_left = available_space(pe, data);
124
125
992k
  while (space_left >= 2)
126
990k
  {
127
990k
    if (data[i] == 0 && data[i + 1] == 0)
128
16.5k
      return 1;
129
974k
    space_left -= 2;
130
974k
    i += 2;
131
974k
  }
132
133
2.09k
  return 0;
134
18.5k
}
135
136
// Parse the rich signature.
137
// http://www.ntcore.com/files/richsign.htm
138
139
static void pe_parse_rich_signature(PE* pe, uint64_t base_address)
140
6.89k
{
141
6.89k
  PIMAGE_DOS_HEADER mz_header;
142
6.89k
  PRICH_SIGNATURE rich_signature = NULL;
143
144
6.89k
  DWORD* rich_ptr = NULL;
145
6.89k
  BYTE* raw_data = NULL;
146
6.89k
  BYTE* clear_data = NULL;
147
6.89k
  BYTE* version_data = NULL;
148
6.89k
  DWORD* p = NULL;
149
6.89k
  uint32_t nthdr_offset = 0;
150
6.89k
  uint32_t key = 0;
151
6.89k
  size_t rich_len = 0;
152
6.89k
  int64_t rich_count = 0;
153
154
6.89k
  if (pe->data_size < sizeof(IMAGE_DOS_HEADER))
155
0
    return;
156
157
6.89k
  mz_header = (PIMAGE_DOS_HEADER) pe->data;
158
159
6.89k
  if (yr_le16toh(mz_header->e_magic) != IMAGE_DOS_SIGNATURE)
160
0
    return;
161
162
  // To find the Rich marker we start at the NT header and work backwards, so
163
  // make sure we have at least enough data to get to the NT header.
164
6.89k
  nthdr_offset = yr_le32toh(mz_header->e_lfanew);
165
6.89k
  if (nthdr_offset > pe->data_size + sizeof(uint32_t) || nthdr_offset < 4)
166
2.33k
    return;
167
168
  // Most files have the Rich header at offset 0x80, but that is not always
169
  // true. 582ce3eea9c97d5e89f7d83953a6d518b16770e635a19a456c0225449c6967a4 is
170
  // one sample which has a Rich header starting at offset 0x200. To properly
171
  // find the Rich header we need to start at the NT header and work backwards.
172
4.56k
  p = (DWORD*) (pe->data + nthdr_offset - 4);
173
174
182k
  while (p >= (DWORD*) (pe->data + sizeof(IMAGE_DOS_HEADER)))
175
178k
  {
176
178k
    if (yr_le32toh(*p) == RICH_RICH)
177
433
    {
178
      // The XOR key is the dword following the Rich value. We  use this to find
179
      // DanS header only.
180
433
      key = *(p + 1);
181
433
      rich_ptr = p;
182
433
      --p;
183
433
      break;
184
433
    }
185
186
    // The NT header is 8 byte aligned so we can move back in 4 byte increments.
187
178k
    --p;
188
178k
  }
189
190
  // If we haven't found a key we can skip processing the rest.
191
4.56k
  if (key == 0)
192
4.13k
    return;
193
194
  // If we have found the key we need to now find the start (DanS).
195
130k
  while (p >= (DWORD*) (pe->data + sizeof(IMAGE_DOS_HEADER)))
196
130k
  {
197
130k
    if (yr_le32toh((*(p) ^ key)) == RICH_DANS)
198
298
    {
199
298
      rich_signature = (PRICH_SIGNATURE) p;
200
298
      break;
201
298
    }
202
203
130k
    --p;
204
130k
  }
205
206
433
  if (rich_signature == NULL)
207
135
    return;
208
209
  // Multiply by 4 because we are counting in DWORDs.
210
298
  rich_len = (rich_ptr - (DWORD*) rich_signature) * 4;
211
298
  raw_data = (BYTE*) yr_malloc(rich_len);
212
213
298
  if (!raw_data)
214
0
    return;
215
216
298
  memcpy(raw_data, rich_signature, rich_len);
217
218
298
  yr_set_integer(
219
298
      base_address + ((uint8_t*) rich_signature - pe->data),
220
298
      pe->object,
221
298
      "rich_signature.offset");
222
223
298
  yr_set_integer(rich_len, pe->object, "rich_signature.length");
224
298
  yr_set_integer(yr_le32toh(key), pe->object, "rich_signature.key");
225
226
298
  clear_data = (BYTE*) yr_malloc(rich_len);
227
228
298
  if (!clear_data)
229
0
  {
230
0
    yr_free(raw_data);
231
0
    return;
232
0
  }
233
234
  // Copy the entire block here to be XORed.
235
298
  memcpy(clear_data, raw_data, rich_len);
236
237
298
  for (rich_ptr = (DWORD*) clear_data;
238
128k
       rich_ptr < (DWORD*) (clear_data + rich_len);
239
127k
       rich_ptr++)
240
127k
  {
241
127k
    *rich_ptr ^= key;
242
127k
  }
243
244
298
  yr_set_sized_string(
245
298
      (char*) raw_data, rich_len, pe->object, "rich_signature.raw_data");
246
247
298
  yr_free(raw_data);
248
249
298
  yr_set_sized_string(
250
298
      (char*) clear_data, rich_len, pe->object, "rich_signature.clear_data");
251
252
  // A Rich header shorter than RICH_SIGNATURE makes the unsigned subtraction
253
  // below wrap around, producing a bogus rich_count. _rich_version guards the
254
  // same computation, do it here too.
255
298
  if (rich_len < sizeof(RICH_SIGNATURE))
256
2
  {
257
2
    yr_free(clear_data);
258
2
    return;
259
2
  }
260
261
  // Allocate space for just the version data. This is a series of every other
262
  // dword from the clear data. This is useful to be able to hash alone.
263
  // We need to skip the first 3 DWORDs of the RICH_SIGNATURE, which are DanS
264
  // and XOR keys.
265
296
  rich_count = (rich_len - sizeof(RICH_SIGNATURE)) / sizeof(RICH_VERSION_INFO);
266
296
  version_data = (BYTE*) yr_malloc(rich_count * sizeof(DWORD));
267
296
  if (!version_data)
268
0
  {
269
0
    yr_free(clear_data);
270
0
    return;
271
0
  }
272
273
296
  rich_signature = (PRICH_SIGNATURE) clear_data;
274
63.6k
  for (int i = 0; i < rich_count; i++)
275
63.3k
  {
276
63.3k
    memcpy(
277
63.3k
        version_data + (i * sizeof(DWORD)),
278
63.3k
        &rich_signature->versions[i],
279
63.3k
        sizeof(DWORD));
280
63.3k
  }
281
282
296
  yr_set_sized_string(
283
296
      (char*) version_data,
284
296
      rich_count * sizeof(DWORD),
285
296
      pe->object,
286
296
      "rich_signature.version_data");
287
288
296
  yr_free(clear_data);
289
296
  yr_free(version_data);
290
296
}
291
292
static void pe_parse_debug_directory(PE* pe)
293
6.89k
{
294
6.89k
  PIMAGE_DATA_DIRECTORY data_dir;
295
6.89k
  PIMAGE_DEBUG_DIRECTORY debug_dir;
296
6.89k
  int64_t debug_dir_offset;
297
6.89k
  int i, dcount;
298
6.89k
  size_t pdb_path_len;
299
6.89k
  char* pdb_path = NULL;
300
301
6.89k
  data_dir = pe_get_directory_entry(pe, IMAGE_DIRECTORY_ENTRY_DEBUG);
302
303
6.89k
  if (data_dir == NULL)
304
0
    return;
305
306
6.89k
  if (yr_le32toh(data_dir->Size) == 0)
307
743
    return;
308
309
6.15k
  if (yr_le32toh(data_dir->VirtualAddress) == 0)
310
147
    return;
311
312
6.00k
  debug_dir_offset = pe_rva_to_offset(pe, yr_le32toh(data_dir->VirtualAddress));
313
314
6.00k
  if (debug_dir_offset < 0)
315
4.76k
    return;
316
317
1.24k
  dcount = yr_le32toh(data_dir->Size) / sizeof(IMAGE_DEBUG_DIRECTORY);
318
319
2.29M
  for (i = 0; i < dcount; i++)
320
2.29M
  {
321
2.29M
    int64_t pcv_hdr_offset = 0;
322
323
2.29M
    debug_dir = (PIMAGE_DEBUG_DIRECTORY) (pe->data + debug_dir_offset +
324
2.29M
                                          i * sizeof(IMAGE_DEBUG_DIRECTORY));
325
326
2.29M
    if (!struct_fits_in_pe(pe, debug_dir, IMAGE_DEBUG_DIRECTORY))
327
1.11k
      break;
328
329
2.29M
    if (yr_le32toh(debug_dir->Type) != IMAGE_DEBUG_TYPE_CODEVIEW)
330
2.28M
      continue;
331
332
    // The debug info offset may be present either as RVA or as raw offset
333
    // Sample: 0249e00b6d46bee5a17096559f18e671cd0ceee36373e8708f614a9a6c7c079e
334
7.74k
    if (debug_dir->AddressOfRawData != 0)
335
6.03k
    {
336
6.03k
      pcv_hdr_offset = pe_rva_to_offset(
337
6.03k
          pe, yr_le32toh(debug_dir->AddressOfRawData));
338
6.03k
    }
339
340
    // Give it chance to read it from the RAW offset
341
    // Sample: 735f72b3fcd72789f01e923c9de2a9ab5b5ffbece23633da81d976ad0ad159e3
342
7.74k
    if (pcv_hdr_offset <= 0 && debug_dir->PointerToRawData != 0)
343
2.99k
    {
344
2.99k
      pcv_hdr_offset = yr_le32toh(debug_dir->PointerToRawData);
345
2.99k
    }
346
347
7.74k
    if (pcv_hdr_offset <= 0)
348
956
      continue;
349
350
6.78k
    PCV_HEADER cv_hdr = (PCV_HEADER) (pe->data + pcv_hdr_offset);
351
352
6.78k
    if (!struct_fits_in_pe(pe, cv_hdr, CV_HEADER))
353
2.37k
      continue;
354
355
4.41k
    if (yr_le32toh(cv_hdr->dwSignature) == CVINFO_PDB20_CVSIGNATURE)
356
266
    {
357
266
      PCV_INFO_PDB20 pdb20 = (PCV_INFO_PDB20) cv_hdr;
358
359
266
      if (struct_fits_in_pe(pe, pdb20, CV_INFO_PDB20))
360
254
        pdb_path = (char*) (pdb20->PdbFileName);
361
266
    }
362
4.15k
    else if (yr_le32toh(cv_hdr->dwSignature) == CVINFO_PDB70_CVSIGNATURE)
363
255
    {
364
255
      PCV_INFO_PDB70 pdb70 = (PCV_INFO_PDB70) cv_hdr;
365
366
255
      if (struct_fits_in_pe(pe, pdb70, CV_INFO_PDB70))
367
234
        pdb_path = (char*) (pdb70->PdbFileName);
368
255
    }
369
3.89k
    else if (yr_le32toh(cv_hdr->dwSignature) == CODEVIEW_SIGNATURE_MTOC)
370
217
    {
371
217
      PMTOC_ENTRY mtoc = (PMTOC_ENTRY) cv_hdr;
372
373
217
      if (struct_fits_in_pe(pe, mtoc, MTOC_ENTRY))
374
203
        pdb_path = (char*) (mtoc->PdbFileName);
375
217
    }
376
377
4.41k
    if (pdb_path != NULL)
378
716
    {
379
716
      pdb_path_len = strnlen(
380
716
          pdb_path, yr_min(available_space(pe, pdb_path), YR_MAX_PATH));
381
382
716
      if (pdb_path_len >= 0 && pdb_path_len < YR_MAX_PATH)
383
90
      {
384
90
        yr_set_sized_string(pdb_path, pdb_path_len, pe->object, "pdb_path");
385
90
        break;
386
90
      }
387
716
    }
388
4.41k
  }
389
1.24k
}
390
391
// Return a pointer to the resource directory string or NULL.
392
// The callback function will parse this and call yr_set_sized_string().
393
// The pointer is guaranteed to have enough space to contain the entire string.
394
static const PIMAGE_RESOURCE_DIR_STRING_U parse_resource_name(
395
    PE* pe,
396
    const uint8_t* rsrc_data,
397
    PIMAGE_RESOURCE_DIRECTORY_ENTRY entry)
398
2.19M
{
399
  // If high bit is set it is an offset relative to rsrc_data, which contains
400
  // a resource directory string.
401
402
2.19M
  if (yr_le32toh(entry->Name) & 0x80000000)
403
711k
  {
404
711k
    const PIMAGE_RESOURCE_DIR_STRING_U pNameString =
405
711k
        (PIMAGE_RESOURCE_DIR_STRING_U) (rsrc_data +
406
711k
                                        (yr_le32toh(entry->Name) & 0x7FFFFFFF));
407
408
    // A resource directory string is 2 bytes for the length and then a variable
409
    // length Unicode string. Make sure we have at least 2 bytes.
410
711k
    if (!fits_in_pe(pe, pNameString, 2))
411
506k
      return NULL;
412
413
    // Sanity check for strings that are excesively large.
414
205k
    if (yr_le16toh(pNameString->Length) > 1000)
415
56.2k
      return NULL;
416
417
    // Move past the length and make sure we have enough bytes for the string.
418
149k
    if (!fits_in_pe(
419
149k
            pe,
420
149k
            pNameString,
421
149k
            sizeof(uint16_t) + yr_le16toh(pNameString->Length) * 2))
422
4.28k
      return NULL;
423
424
144k
    return pNameString;
425
149k
  }
426
427
1.48M
  return NULL;
428
2.19M
}
429
430
static int _pe_iterate_resources(
431
    PE* pe,
432
    PIMAGE_RESOURCE_DIRECTORY resource_dir,
433
    const uint8_t* rsrc_data,
434
    int rsrc_tree_level,
435
    int* type,
436
    int* id,
437
    int* language,
438
    const IMAGE_RESOURCE_DIR_STRING_U* type_string,
439
    const IMAGE_RESOURCE_DIR_STRING_U* name_string,
440
    const IMAGE_RESOURCE_DIR_STRING_U* lang_string,
441
    RESOURCE_CALLBACK_FUNC callback,
442
    void* callback_data)
443
16.0k
{
444
16.0k
  int i, result = RESOURCE_ITERATOR_FINISHED;
445
16.0k
  int total_entries;
446
447
16.0k
  PIMAGE_RESOURCE_DIRECTORY_ENTRY entry;
448
449
  // A few sanity checks to avoid corrupt files
450
451
16.0k
  if (yr_le32toh(resource_dir->Characteristics) != 0 ||
452
10.1k
      yr_le16toh(resource_dir->NumberOfNamedEntries) > 32768 ||
453
9.86k
      yr_le16toh(resource_dir->NumberOfIdEntries) > 32768)
454
6.52k
  {
455
6.52k
    return result;
456
6.52k
  }
457
458
9.55k
  total_entries = yr_le16toh(resource_dir->NumberOfNamedEntries) +
459
9.55k
                  yr_le16toh(resource_dir->NumberOfIdEntries);
460
461
  // The first directory entry is just after the resource directory,
462
  // by incrementing resource_dir we skip sizeof(resource_dir) bytes
463
  // and get a pointer to the end of the resource directory.
464
465
9.55k
  entry = (PIMAGE_RESOURCE_DIRECTORY_ENTRY) (resource_dir + 1);
466
467
9.55k
  if (!fits_in_pe(
468
9.55k
          pe, entry, total_entries * sizeof(IMAGE_RESOURCE_DIRECTORY_ENTRY)))
469
764
    return result;
470
471
11.1M
  for (i = 0; i < total_entries; i++)
472
11.1M
  {
473
11.1M
    if (yr_le32toh(entry->OffsetToData) == 0)
474
8.96M
      continue;
475
476
2.19M
    switch (rsrc_tree_level)
477
2.19M
    {
478
58.5k
    case 0:
479
58.5k
      *type = yr_le32toh(entry->Name);
480
58.5k
      type_string = parse_resource_name(pe, rsrc_data, entry);
481
58.5k
      break;
482
247k
    case 1:
483
247k
      *id = yr_le32toh(entry->Name);
484
247k
      name_string = parse_resource_name(pe, rsrc_data, entry);
485
247k
      break;
486
1.88M
    case 2:
487
1.88M
      *language = yr_le32toh(entry->Name);
488
1.88M
      lang_string = parse_resource_name(pe, rsrc_data, entry);
489
1.88M
      break;
490
2.19M
    }
491
492
2.19M
    if (IS_RESOURCE_SUBDIRECTORY(entry) && rsrc_tree_level < 2)
493
81.9k
    {
494
81.9k
      PIMAGE_RESOURCE_DIRECTORY directory =
495
81.9k
          (PIMAGE_RESOURCE_DIRECTORY) (rsrc_data + RESOURCE_OFFSET(entry));
496
497
      // Don't allow descending into a directory that is already being processed.
498
      // While this does not prevent potential cyclical infinite loops, it is good
499
      // enough to handle all known problematic cases.
500
81.9k
      if (directory != resource_dir &&
501
76.3k
          struct_fits_in_pe(pe, directory, IMAGE_RESOURCE_DIRECTORY))
502
14.5k
      {
503
14.5k
        result = _pe_iterate_resources(
504
14.5k
            pe,
505
14.5k
            directory,
506
14.5k
            rsrc_data,
507
14.5k
            rsrc_tree_level + 1,
508
14.5k
            type,
509
14.5k
            id,
510
14.5k
            language,
511
14.5k
            type_string,
512
14.5k
            name_string,
513
14.5k
            lang_string,
514
14.5k
            callback,
515
14.5k
            callback_data);
516
14.5k
      }
517
81.9k
    }
518
2.11M
    else
519
2.11M
    {
520
2.11M
      PIMAGE_RESOURCE_DATA_ENTRY data_entry =
521
2.11M
          (PIMAGE_RESOURCE_DATA_ENTRY) (rsrc_data + RESOURCE_OFFSET(entry));
522
523
2.11M
      if (struct_fits_in_pe(pe, data_entry, IMAGE_RESOURCE_DATA_ENTRY))
524
459k
      {
525
459k
        if (yr_le32toh(data_entry->Size) > 0 &&
526
            // We could use the PE's size as an upper bound for the entry size,
527
            // but there are some truncated files where the PE size is lower.
528
            // Use a reasonably large value as the upper bound and avoid some
529
            // completely corrupt entries with random values.
530
453k
            yr_le32toh(data_entry->Size) <= 0x3FFFFFFF)
531
347k
        {
532
347k
          if (callback(
533
347k
                  data_entry,
534
347k
                  *type,
535
347k
                  *id,
536
347k
                  *language,
537
347k
                  type_string,
538
347k
                  name_string,
539
347k
                  lang_string,
540
347k
                  callback_data) == RESOURCE_CALLBACK_ABORT)
541
3
          {
542
3
            result = RESOURCE_ITERATOR_ABORTED;
543
3
          }
544
347k
        }
545
459k
      }
546
2.11M
    }
547
548
2.19M
    if (result == RESOURCE_ITERATOR_ABORTED)
549
6
      break;
550
551
2.19M
    entry++;
552
2.19M
  }
553
554
8.78k
  return result;
555
8.78k
}
556
557
static int pe_iterate_resources(
558
    PE* pe,
559
    RESOURCE_CALLBACK_FUNC callback,
560
    void* callback_data)
561
6.89k
{
562
6.89k
  int64_t offset;
563
564
6.89k
  int type = -1;
565
6.89k
  int id = -1;
566
6.89k
  int language = -1;
567
568
6.89k
  IMAGE_RESOURCE_DIR_STRING_U* type_string = NULL;
569
6.89k
  IMAGE_RESOURCE_DIR_STRING_U* name_string = NULL;
570
6.89k
  IMAGE_RESOURCE_DIR_STRING_U* lang_string = NULL;
571
572
6.89k
  PIMAGE_DATA_DIRECTORY directory = pe_get_directory_entry(
573
6.89k
      pe, IMAGE_DIRECTORY_ENTRY_RESOURCE);
574
575
6.89k
  if (directory == NULL)
576
0
    return 0;
577
578
6.89k
  if (yr_le32toh(directory->VirtualAddress) != 0)
579
6.52k
  {
580
6.52k
    PIMAGE_RESOURCE_DIRECTORY rsrc_dir;
581
582
6.52k
    offset = pe_rva_to_offset(pe, yr_le32toh(directory->VirtualAddress));
583
584
6.52k
    if (offset < 0)
585
4.93k
      return 0;
586
587
1.59k
    rsrc_dir = (PIMAGE_RESOURCE_DIRECTORY) (pe->data + offset);
588
589
1.59k
    if (struct_fits_in_pe(pe, rsrc_dir, IMAGE_RESOURCE_DIRECTORY))
590
1.56k
    {
591
1.56k
      yr_set_integer(
592
1.56k
          yr_le32toh(rsrc_dir->TimeDateStamp),
593
1.56k
          pe->object,
594
1.56k
          "resource_timestamp");
595
596
1.56k
      yr_set_integer(
597
1.56k
          yr_le16toh(rsrc_dir->MajorVersion),
598
1.56k
          pe->object,
599
1.56k
          "resource_version.major");
600
601
1.56k
      yr_set_integer(
602
1.56k
          yr_le16toh(rsrc_dir->MinorVersion),
603
1.56k
          pe->object,
604
1.56k
          "resource_version.minor");
605
606
1.56k
      _pe_iterate_resources(
607
1.56k
          pe,
608
1.56k
          rsrc_dir,
609
1.56k
          pe->data + offset,
610
1.56k
          0,
611
1.56k
          &type,
612
1.56k
          &id,
613
1.56k
          &language,
614
1.56k
          type_string,
615
1.56k
          name_string,
616
1.56k
          lang_string,
617
1.56k
          callback,
618
1.56k
          callback_data);
619
620
1.56k
      return 1;
621
1.56k
    }
622
1.59k
  }
623
624
393
  return 0;
625
6.89k
}
626
627
// Align offset to a 32-bit boundary and add it to a pointer
628
629
#define ADD_OFFSET(ptr, offset) \
630
29.5k
  (PVERSION_INFO)((uint8_t*) (ptr) + ((offset + 3) & ~3))
631
632
static void pe_parse_version_info(PIMAGE_RESOURCE_DATA_ENTRY rsrc_data, PE* pe)
633
85.1k
{
634
85.1k
  PVERSION_INFO version_info;
635
636
85.1k
  int64_t version_info_offset = pe_rva_to_offset(
637
85.1k
      pe, yr_le32toh(rsrc_data->OffsetToData));
638
639
85.1k
  if (version_info_offset < 0)
640
42.5k
    return;
641
642
42.5k
  version_info = (PVERSION_INFO) (pe->data + version_info_offset);
643
644
42.5k
  if (!struct_fits_in_pe(pe, version_info, VERSION_INFO))
645
911
    return;
646
647
41.6k
  if (!fits_in_pe(pe, version_info->Key, sizeof("VS_VERSION_INFO") * 2))
648
566
    return;
649
650
41.0k
  if (strcmp_w(version_info->Key, "VS_VERSION_INFO") != 0)
651
36.6k
    return;
652
653
4.41k
  version_info = ADD_OFFSET(version_info, sizeof(VERSION_INFO) + 86);
654
655
4.53k
  while (fits_in_pe(pe, version_info->Key, sizeof("VarFileInfo") * 2) &&
656
4.22k
         strcmp_w(version_info->Key, "VarFileInfo") == 0 &&
657
187
         yr_le16toh(version_info->Length) != 0)
658
120
  {
659
120
    version_info = ADD_OFFSET(version_info, yr_le16toh(version_info->Length));
660
120
  }
661
662
7.74k
  while (fits_in_pe(pe, version_info->Key, sizeof("StringFileInfo") * 2) &&
663
4.37k
         strcmp_w(version_info->Key, "StringFileInfo") == 0 &&
664
3.54k
         yr_le16toh(version_info->Length) != 0)
665
3.33k
  {
666
3.33k
    PVERSION_INFO string_table = ADD_OFFSET(
667
3.33k
        version_info, sizeof(VERSION_INFO) + 30);
668
669
3.33k
    version_info = ADD_OFFSET(version_info, yr_le16toh(version_info->Length));
670
671
6.55k
    while (struct_fits_in_pe(pe, string_table, VERSION_INFO) &&
672
5.02k
           wide_string_fits_in_pe(pe, string_table->Key) &&
673
4.21k
           yr_le16toh(string_table->Length) != 0 && string_table < version_info)
674
3.21k
    {
675
3.21k
      PVERSION_INFO string = ADD_OFFSET(
676
3.21k
          string_table,
677
3.21k
          sizeof(VERSION_INFO) + 2 * (strnlen_w(string_table->Key) + 1));
678
679
3.21k
      string_table = ADD_OFFSET(string_table, yr_le16toh(string_table->Length));
680
681
9.15k
      while (struct_fits_in_pe(pe, string, VERSION_INFO) &&
682
7.63k
             wide_string_fits_in_pe(pe, string->Key) &&
683
6.86k
             yr_le16toh(string->Length) != 0 && string < string_table)
684
5.94k
      {
685
5.94k
        char* string_value = (char*) ADD_OFFSET(
686
5.94k
            string, sizeof(VERSION_INFO) + 2 * (strnlen_w(string->Key) + 1));
687
688
5.94k
        if (wide_string_fits_in_pe(pe, string_value))
689
5.42k
        {
690
5.42k
          char key[64];
691
5.42k
          char value[256];
692
693
5.42k
          strlcpy_w(key, string->Key, sizeof(key));
694
5.42k
          strlcpy_w(value, string_value, sizeof(value));
695
696
          // null terminator of string is not included in version value when
697
          // ValueLength is zero
698
5.42k
          if (yr_le16toh(string->ValueLength) == 0)
699
381
            value[yr_le16toh(string->ValueLength)] = '\0';
700
701
5.42k
          yr_set_string(value, pe->object, "version_info[%s]", key);
702
703
5.42k
          yr_set_string(
704
5.42k
              key, pe->object, "version_info_list[%i].key", pe->version_infos);
705
706
5.42k
          yr_set_string(
707
5.42k
              value,
708
5.42k
              pe->object,
709
5.42k
              "version_info_list[%i].value",
710
5.42k
              pe->version_infos);
711
712
5.42k
          pe->version_infos += 1;
713
5.42k
        }
714
715
5.94k
        string = ADD_OFFSET(string, yr_le16toh(string->Length));
716
5.94k
      }
717
3.21k
    }
718
3.33k
  }
719
4.41k
}
720
721
static void pe_set_resource_string_or_id(
722
    IMAGE_RESOURCE_DIR_STRING_U* rsrc_string,
723
    int rsrc_int,
724
    const char* string_description,
725
    const char* int_description,
726
    PE* pe)
727
1.04M
{
728
1.04M
  if (rsrc_string)
729
184k
  {
730
    // Multiply by 2 because it is a Unicode string.
731
184k
    size_t length = yr_le16toh(rsrc_string->Length) * 2;
732
733
    // Check if the whole string fits in the PE image.
734
    // If not, the name becomes UNDEFINED by default.
735
184k
    if (fits_in_pe(pe, rsrc_string->NameString, length))
736
184k
    {
737
184k
      yr_set_sized_string(
738
184k
          (char*) rsrc_string->NameString,
739
184k
          length,
740
184k
          pe->object,
741
184k
          string_description,
742
184k
          pe->resources);
743
184k
    }
744
184k
  }
745
858k
  else
746
858k
  {
747
858k
    if (rsrc_int != -1)
748
850k
      yr_set_integer(rsrc_int, pe->object, int_description, pe->resources);
749
858k
  }
750
1.04M
}
751
752
static int pe_collect_resources(
753
    PIMAGE_RESOURCE_DATA_ENTRY rsrc_data,
754
    int rsrc_type,
755
    int rsrc_id,
756
    int rsrc_language,
757
    IMAGE_RESOURCE_DIR_STRING_U* type_string,
758
    IMAGE_RESOURCE_DIR_STRING_U* name_string,
759
    IMAGE_RESOURCE_DIR_STRING_U* lang_string,
760
    PE* pe)
761
347k
{
762
  // Don't collect too many resources.
763
347k
  if (pe->resources >= MAX_RESOURCES)
764
3
    return RESOURCE_CALLBACK_ABORT;
765
766
347k
  yr_set_integer(
767
347k
      yr_le32toh(rsrc_data->OffsetToData),
768
347k
      pe->object,
769
347k
      "resources[%i].rva",
770
347k
      pe->resources);
771
772
347k
  int64_t offset = pe_rva_to_offset(pe, yr_le32toh(rsrc_data->OffsetToData));
773
774
347k
  if (offset < 0)
775
110k
    offset = YR_UNDEFINED;
776
777
347k
  yr_set_integer(offset, pe->object, "resources[%i].offset", pe->resources);
778
779
347k
  yr_set_integer(
780
347k
      yr_le32toh(rsrc_data->Size),
781
347k
      pe->object,
782
347k
      "resources[%i].length",
783
347k
      pe->resources);
784
785
347k
  pe_set_resource_string_or_id(
786
347k
      type_string,
787
347k
      rsrc_type,
788
347k
      "resources[%i].type_string",
789
347k
      "resources[%i].type",
790
347k
      pe);
791
792
347k
  pe_set_resource_string_or_id(
793
347k
      name_string,
794
347k
      rsrc_id,
795
347k
      "resources[%i].name_string",
796
347k
      "resources[%i].id",
797
347k
      pe);
798
799
347k
  pe_set_resource_string_or_id(
800
347k
      lang_string,
801
347k
      rsrc_language,
802
347k
      "resources[%i].language_string",
803
347k
      "resources[%i].language",
804
347k
      pe);
805
806
  // Resources we do extra parsing on
807
347k
  if (rsrc_type == RESOURCE_TYPE_VERSION)
808
85.1k
    pe_parse_version_info(rsrc_data, pe);
809
810
347k
  pe->resources += 1;
811
347k
  return RESOURCE_CALLBACK_CONTINUE;
812
347k
}
813
814
// Function names should have only lowercase, uppercase, digits and a small
815
// subset of special characters. This is to match behavior of pefile. See
816
// https://github.com/erocarrera/pefile/blob/593d094e35198dad92aaf040bef17eb800c8a373/pefile.py#L2326-L2348
817
static int valid_function_name(char* name)
818
4.03M
{
819
4.03M
  if (!strcmp(name, ""))
820
771k
    return 0;
821
822
3.26M
  size_t i = 0;
823
27.3M
  for (char c = name[i]; c != '\x00'; c = name[++i])
824
26.3M
  {
825
26.3M
    if (!(c >= 'a' && c <= 'z') && !(c >= 'A' && c <= 'Z') &&
826
3.85M
        !(c >= '0' && c <= '9') && c != '.' && c != '_' && c != '?' &&
827
2.40M
        c != '@' && c != '$' && c != '(' && c != ')' && c != '<' && c != '>')
828
2.31M
      return 0;
829
26.3M
  }
830
943k
  return 1;
831
3.26M
}
832
833
static IMPORT_FUNCTION* pe_parse_import_descriptor(
834
    PE* pe,
835
    PIMAGE_IMPORT_DESCRIPTOR import_descriptor,
836
    char* dll_name,
837
    int* num_function_imports)
838
66.2k
{
839
66.2k
  IMPORT_FUNCTION* head = NULL;
840
66.2k
  IMPORT_FUNCTION* tail = NULL;
841
  // This is tracked separately from num_function_imports because that is the
842
  // number of successfully parsed imports, while this is the number of imports
843
  // attempted to be parsed. This allows us to stop parsing on too many imports
844
  // while still accurately recording the number of successfully parsed imports.
845
66.2k
  int parsed_imports = 0;
846
847
66.2k
  int64_t offset = pe_rva_to_offset(
848
66.2k
      pe, yr_le32toh(import_descriptor->OriginalFirstThunk));
849
850
  // I've seen binaries where OriginalFirstThunk is zero. In this case
851
  // use FirstThunk.
852
853
66.2k
  if (offset <= 0)
854
50.1k
    offset = pe_rva_to_offset(pe, yr_le32toh(import_descriptor->FirstThunk));
855
856
66.2k
  if (offset < 0)
857
10.4k
    return NULL;
858
859
55.8k
  if (IS_64BITS_PE(pe))
860
9.32k
  {
861
9.32k
    PIMAGE_THUNK_DATA64 thunks64 = (PIMAGE_THUNK_DATA64) (pe->data + offset);
862
9.32k
    uint64_t func_idx = 0;
863
864
70.5M
    while (struct_fits_in_pe(pe, thunks64, IMAGE_THUNK_DATA64) &&
865
70.5M
           yr_le64toh(thunks64->u1.Ordinal) != 0 &&
866
70.5M
           parsed_imports < MAX_PE_IMPORTS &&
867
70.5M
           *num_function_imports < MAX_PE_IMPORTS)
868
70.5M
    {
869
70.5M
      char* name = NULL;
870
70.5M
      uint16_t ordinal = 0;
871
70.5M
      uint8_t has_ordinal = 0;
872
70.5M
      uint64_t rva_address = 0;
873
874
70.5M
      parsed_imports++;
875
876
70.5M
      if (!(yr_le64toh(thunks64->u1.Ordinal) & IMAGE_ORDINAL_FLAG64))
877
45.4M
      {
878
        // If imported by name
879
45.4M
        offset = pe_rva_to_offset(pe, yr_le64toh(thunks64->u1.Function));
880
881
45.4M
        if (offset >= 0)
882
87.7k
        {
883
87.7k
          PIMAGE_IMPORT_BY_NAME import = (PIMAGE_IMPORT_BY_NAME) (pe->data +
884
87.7k
                                                                  offset);
885
886
87.7k
          if (struct_fits_in_pe(pe, import, IMAGE_IMPORT_BY_NAME))
887
87.4k
          {
888
87.4k
            name = (char*) yr_strndup(
889
87.4k
                (char*) import->Name,
890
87.4k
                yr_min(available_space(pe, import->Name), 512));
891
87.4k
          }
892
87.7k
        }
893
45.4M
      }
894
25.0M
      else
895
25.0M
      {
896
        // The maximum possible value for the ordinal is when the high
897
        // bit is set (indicating import by ordinal) and the low bits
898
        // are FFFF. The maximum number of ordinal exports is 65536.
899
25.0M
        if (yr_le64toh(thunks64->u1.Ordinal) <= 0x800000000000ffff)
900
1.25k
        {
901
1.25k
          ordinal = yr_le64toh(thunks64->u1.Ordinal) & 0xFFFF;
902
1.25k
          name = ord_lookup(dll_name, ordinal);
903
1.25k
          has_ordinal = 1;
904
1.25k
        }
905
25.0M
      }
906
907
70.5M
      rva_address = yr_le32toh(import_descriptor->FirstThunk) +
908
70.5M
                    (sizeof(uint64_t) * func_idx);
909
910
70.5M
      if (name != NULL && !valid_function_name(name))
911
23.8k
      {
912
23.8k
        yr_free(name);
913
23.8k
        thunks64++;
914
23.8k
        func_idx++;
915
23.8k
        continue;
916
23.8k
      }
917
918
70.4M
      if (name != NULL || has_ordinal == 1)
919
64.8k
      {
920
64.8k
        IMPORT_FUNCTION* imported_func = (IMPORT_FUNCTION*) yr_calloc(
921
64.8k
            1, sizeof(IMPORT_FUNCTION));
922
923
64.8k
        if (imported_func == NULL)
924
0
        {
925
0
          yr_free(name);
926
0
        }
927
64.8k
        else
928
64.8k
        {
929
64.8k
          imported_func->name = name;
930
64.8k
          imported_func->ordinal = ordinal;
931
64.8k
          imported_func->has_ordinal = has_ordinal;
932
64.8k
          imported_func->rva = rva_address;
933
64.8k
          imported_func->next = NULL;
934
935
64.8k
          if (head == NULL)
936
4.74k
            head = imported_func;
937
938
64.8k
          if (tail != NULL)
939
60.0k
            tail->next = imported_func;
940
941
64.8k
          tail = imported_func;
942
64.8k
          (*num_function_imports)++;
943
64.8k
        }
944
64.8k
      }
945
946
70.4M
      thunks64++;
947
70.4M
      func_idx++;
948
70.4M
    }
949
9.32k
  }
950
46.5k
  else
951
46.5k
  {
952
46.5k
    PIMAGE_THUNK_DATA32 thunks32 = (PIMAGE_THUNK_DATA32) (pe->data + offset);
953
46.5k
    uint32_t func_idx = 0;
954
955
291M
    while (struct_fits_in_pe(pe, thunks32, IMAGE_THUNK_DATA32) &&
956
291M
           yr_le32toh(thunks32->u1.Ordinal) != 0 &&
957
291M
           parsed_imports < MAX_PE_IMPORTS &&
958
291M
           *num_function_imports < MAX_PE_IMPORTS)
959
291M
    {
960
291M
      char* name = NULL;
961
291M
      uint16_t ordinal = 0;
962
291M
      uint8_t has_ordinal = 0;
963
291M
      uint32_t rva_address = 0;
964
965
291M
      parsed_imports++;
966
967
291M
      if (!(yr_le32toh(thunks32->u1.Ordinal) & IMAGE_ORDINAL_FLAG32))
968
16.8M
      {
969
        // If imported by name
970
16.8M
        offset = pe_rva_to_offset(pe, yr_le32toh(thunks32->u1.Function));
971
972
16.8M
        if (offset >= 0)
973
3.47M
        {
974
3.47M
          PIMAGE_IMPORT_BY_NAME import = (PIMAGE_IMPORT_BY_NAME) (pe->data +
975
3.47M
                                                                  offset);
976
977
3.47M
          if (struct_fits_in_pe(pe, import, IMAGE_IMPORT_BY_NAME))
978
3.47M
          {
979
3.47M
            name = (char*) yr_strndup(
980
3.47M
                (char*) import->Name,
981
3.47M
                yr_min(available_space(pe, import->Name), 512));
982
3.47M
          }
983
3.47M
        }
984
16.8M
      }
985
274M
      else
986
274M
      {
987
        // The maximum possible value for the ordinal is when the high
988
        // bit is set (indicating import by ordinal) and the low bits
989
        // are FFFF. The maximum number of ordinal exports is 65536.
990
274M
        if (yr_le32toh(thunks32->u1.Ordinal) <= 0x8000ffff)
991
473k
        {
992
473k
          ordinal = yr_le32toh(thunks32->u1.Ordinal) & 0xFFFF;
993
473k
          name = ord_lookup(dll_name, ordinal);
994
473k
          has_ordinal = 1;
995
473k
        }
996
274M
      }
997
998
291M
      rva_address = yr_le32toh(import_descriptor->FirstThunk) +
999
291M
                    (sizeof(uint32_t) * func_idx);
1000
1001
291M
      if (name != NULL && !valid_function_name(name))
1002
3.06M
      {
1003
3.06M
        yr_free(name);
1004
3.06M
        thunks32++;
1005
3.06M
        func_idx++;
1006
3.06M
        continue;
1007
3.06M
      }
1008
1009
288M
      if (name != NULL || has_ordinal == 1)
1010
878k
      {
1011
878k
        IMPORT_FUNCTION* imported_func = (IMPORT_FUNCTION*) yr_calloc(
1012
878k
            1, sizeof(IMPORT_FUNCTION));
1013
1014
878k
        if (imported_func == NULL)
1015
0
        {
1016
0
          yr_free(name);
1017
0
        }
1018
878k
        else
1019
878k
        {
1020
878k
          imported_func->name = name;
1021
878k
          imported_func->ordinal = ordinal;
1022
878k
          imported_func->has_ordinal = has_ordinal;
1023
878k
          imported_func->rva = rva_address;
1024
878k
          imported_func->next = NULL;
1025
1026
878k
          if (head == NULL)
1027
43.9k
            head = imported_func;
1028
1029
878k
          if (tail != NULL)
1030
834k
            tail->next = imported_func;
1031
1032
878k
          tail = imported_func;
1033
878k
          (*num_function_imports)++;
1034
878k
        }
1035
878k
      }
1036
1037
288M
      thunks32++;
1038
288M
      func_idx++;
1039
288M
    }
1040
46.5k
  }
1041
1042
55.8k
  return head;
1043
66.2k
}
1044
1045
//
1046
// In Windows PE files, any printable character including 0x20 and above is
1047
// allowed. The only exceptions are characters that are invalid for file names
1048
// in Windows, which are "*<>?|. While they still can be present in the import
1049
// directory, such module can never be present in Windows, so we can treat them
1050
// as invalid.
1051
//
1052
// Explicit: The above also applies to slash, backslash (these form a relative
1053
// path in a subdirectory, which is allowed in the import directory) and colon
1054
// (which forms a file name with an Alternate Data Stream "test:file.dll" - also
1055
// allowed).
1056
//
1057
// Proof of concept: https://github.com/ladislav-zezula/ImportTest
1058
//
1059
// Samples
1060
// -------
1061
// f561d60bff4342e529b2c793e216b73a72e6256f90ab24c3cc460646371130ca (imports
1062
// "test/file.dll")
1063
// b7f7b8a001769eb0f9c36cb27626b62cabdca9a716a222066028fcd206244b40 (imports
1064
// "test\file.dll")
1065
// 94cfb8223132da0a76f9dfbd35a29ab78e5806651758650292ab9c7baf2c0bc2 (imports
1066
// "test:file.dll")
1067
// eb2e2c443840276afe095fff05a3a24c00e610ac0e020233d6cd7a0b0b340fb1 (the
1068
// imported DLL)
1069
//
1070
1071
static int pe_valid_dll_name(const char* dll_name, size_t n)
1072
139k
{
1073
139k
  const unsigned char* c = (const unsigned char*) dll_name;
1074
139k
  size_t l = 0;
1075
1076
6.72M
  while (l < n && *c != '\0')
1077
6.62M
  {
1078
6.62M
    if (*c < ' ' || *c > 0x7e || *c == '\"' || *c == '*' || *c == '<' ||
1079
6.58M
        *c == '>' || *c == '?' || *c == '|')
1080
37.8k
    {
1081
37.8k
      return false;
1082
37.8k
    }
1083
1084
6.58M
    c++;
1085
6.58M
    l++;
1086
6.58M
  }
1087
1088
101k
  return (l > 0 && l < n);
1089
139k
}
1090
1091
void pe_set_imports(
1092
    PE* pe,
1093
    IMPORTED_DLL* dll,
1094
    const char* dll_name,
1095
    const char* dll_number_of_functions,
1096
    const char* fun_name,
1097
    const char* fun_ordinal,
1098
    const char* rva)
1099
6.08k
{
1100
6.08k
  int dll_cnt = 0;
1101
1102
60.2k
  for (; dll != NULL; dll = dll->next, dll_cnt++)
1103
54.1k
  {
1104
54.1k
    int fun_cnt = 0;
1105
1106
1.83M
    for (IMPORT_FUNCTION* func = dll->functions; func != NULL;
1107
1.78M
         func = func->next, fun_cnt++)
1108
1.78M
    {
1109
1.78M
      yr_set_string(func->name, pe->object, fun_name, dll_cnt, fun_cnt);
1110
1111
1.78M
      if (func->has_ordinal)
1112
1.26M
        yr_set_integer(
1113
1.78M
            func->ordinal, pe->object, fun_ordinal, dll_cnt, fun_cnt);
1114
516k
      else
1115
516k
        yr_set_integer(YR_UNDEFINED, pe->object, fun_ordinal, dll_cnt, fun_cnt);
1116
1117
1.78M
      if (func->rva)
1118
1.78M
        yr_set_integer(func->rva, pe->object, rva, dll_cnt, fun_cnt);
1119
83
      else
1120
83
        yr_set_integer(YR_UNDEFINED, pe->object, rva, dll_cnt, fun_cnt);
1121
1.78M
    }
1122
54.1k
    yr_set_string(dll->name, pe->object, dll_name, dll_cnt);
1123
54.1k
    yr_set_integer(fun_cnt, pe->object, dll_number_of_functions, dll_cnt);
1124
54.1k
  }
1125
6.08k
}
1126
1127
//
1128
// Walk the imports and collect relevant information. It is used in the
1129
// "imports" function for comparison and in the "imphash" function for
1130
// calculation.
1131
//
1132
1133
static IMPORTED_DLL* pe_parse_imports(PE* pe)
1134
6.89k
{
1135
6.89k
  int64_t offset;
1136
6.89k
  int parsed_imports = 0;        // Number of parsed DLLs
1137
6.89k
  int num_imports = 0;           // Number of imported DLLs
1138
6.89k
  int num_function_imports = 0;  // Total number of functions imported
1139
1140
6.89k
  IMPORTED_DLL* head = NULL;
1141
6.89k
  IMPORTED_DLL* tail = NULL;
1142
1143
6.89k
  PIMAGE_IMPORT_DESCRIPTOR imports;
1144
6.89k
  PIMAGE_DATA_DIRECTORY directory;
1145
1146
  // Default to 0 imports until we know there are any
1147
6.89k
  yr_set_integer(0, pe->object, "number_of_imports");
1148
6.89k
  yr_set_integer(0, pe->object, "number_of_imported_functions");
1149
1150
6.89k
  directory = pe_get_directory_entry(pe, IMAGE_DIRECTORY_ENTRY_IMPORT);
1151
1152
6.89k
  if (directory == NULL)
1153
0
    return NULL;
1154
1155
6.89k
  if (yr_le32toh(directory->VirtualAddress) == 0)
1156
567
    return NULL;
1157
1158
6.32k
  offset = pe_rva_to_offset(pe, yr_le32toh(directory->VirtualAddress));
1159
1160
6.32k
  if (offset < 0)
1161
1.73k
    return NULL;
1162
1163
4.59k
  imports = (PIMAGE_IMPORT_DESCRIPTOR) (pe->data + offset);
1164
1165
348k
  while (struct_fits_in_pe(pe, imports, IMAGE_IMPORT_DESCRIPTOR) &&
1166
345k
         yr_le32toh(imports->Name) != 0 && parsed_imports < MAX_PE_IMPORTS)
1167
344k
  {
1168
344k
    parsed_imports++;
1169
1170
344k
    int64_t offset = pe_rva_to_offset(pe, yr_le32toh(imports->Name));
1171
1172
344k
    if (offset >= 0)
1173
130k
    {
1174
130k
      IMPORTED_DLL* imported_dll;
1175
1176
130k
      char* dll_name = (char*) (pe->data + offset);
1177
1178
130k
      if (!pe_valid_dll_name(
1179
130k
              dll_name,
1180
130k
              yr_min(
1181
                  // DLL names longer than MAX_IMPORT_DLL_NAME_LENGTH
1182
                  // are considered invalid.
1183
130k
                  pe->data_size - (size_t) offset,
1184
130k
                  MAX_IMPORT_DLL_NAME_LENGTH)))
1185
64.4k
      {
1186
64.4k
        imports++;
1187
64.4k
        continue;
1188
64.4k
      }
1189
1190
66.2k
      imported_dll = (IMPORTED_DLL*) yr_calloc(1, sizeof(IMPORTED_DLL));
1191
1192
66.2k
      if (imported_dll != NULL)
1193
66.2k
      {
1194
66.2k
        IMPORT_FUNCTION* functions = pe_parse_import_descriptor(
1195
66.2k
            pe, imports, dll_name, &num_function_imports);
1196
1197
66.2k
        if (functions != NULL)
1198
48.7k
        {
1199
48.7k
          imported_dll->name = yr_strdup(dll_name);
1200
48.7k
          imported_dll->functions = functions;
1201
48.7k
          imported_dll->next = NULL;
1202
1203
48.7k
          if (head == NULL)
1204
3.83k
            head = imported_dll;
1205
1206
48.7k
          if (tail != NULL)
1207
44.8k
            tail->next = imported_dll;
1208
1209
48.7k
          tail = imported_dll;
1210
48.7k
          num_imports++;
1211
48.7k
        }
1212
17.5k
        else
1213
17.5k
        {
1214
17.5k
          yr_free(imported_dll);
1215
17.5k
        }
1216
66.2k
      }
1217
66.2k
    }
1218
1219
279k
    imports++;
1220
279k
  }
1221
1222
4.59k
  yr_set_integer(num_imports, pe->object, "number_of_imports");
1223
4.59k
  yr_set_integer(
1224
4.59k
      num_function_imports, pe->object, "number_of_imported_functions");
1225
4.59k
  pe_set_imports(
1226
4.59k
      pe,
1227
4.59k
      head,
1228
4.59k
      "import_details[%i].library_name",
1229
4.59k
      "import_details[%i].number_of_functions",
1230
4.59k
      "import_details[%i].functions[%i].name",
1231
4.59k
      "import_details[%i].functions[%i].ordinal",
1232
4.59k
      "import_details[%i].functions[%i].rva");
1233
1234
4.59k
  return head;
1235
6.32k
}
1236
1237
// Delay-import descriptors made by MS Visual C++ 6.0 have old format
1238
// of delay import directory, where all entries are VAs (as opposite to RVAs
1239
// from newer MS compilers). We convert the delay-import directory entries to
1240
// RVAs by checking the lowest bit in the delay-import descriptor's Attributes
1241
// value
1242
uint64_t pe_normalize_delay_import_value(
1243
    uint64_t image_base,
1244
    uint64_t virtual_address)
1245
2.38M
{
1246
  // Ignore zero items
1247
2.38M
  if (virtual_address != 0)
1248
2.38M
  {
1249
    // Sample: 0fc4cb0620f95bdd624f2c78eea4d2b59594244c6671cf249526adf2f2cb71ec
1250
    // Contains artificially created delay import directory with incorrect
1251
    // values:
1252
    //
1253
    //  Attributes                      0x00000000 <-- Old MS delay import
1254
    //  record, contains VAs NameRva                         0x004010e6
1255
    //  ModuleHandleRva                 0x00000000
1256
    //  DelayImportAddressTableRva      0x00001140 <-- WRONG! This is an RVA
1257
    //  DelayImportNameTableRva         0x004010c0
1258
    //  BoundDelayImportTableRva        0x00000000
1259
    //  ...
1260
1261
2.38M
    if (virtual_address > image_base)
1262
747k
    {
1263
747k
      virtual_address = virtual_address - image_base;
1264
747k
    }
1265
2.38M
  }
1266
1267
2.38M
  return virtual_address;
1268
2.38M
}
1269
1270
int pe_is_termination_delay_import_entry(
1271
    PIMAGE_DELAYLOAD_DESCRIPTOR importDescriptor)
1272
10.9k
{
1273
10.9k
  return (
1274
10.9k
      importDescriptor->Attributes.AllAttributes == 0 &&
1275
9.66k
      importDescriptor->DllNameRVA == 0 &&
1276
285
      importDescriptor->ModuleHandleRVA == 0 &&
1277
225
      importDescriptor->ImportAddressTableRVA == 0 &&
1278
181
      importDescriptor->ImportNameTableRVA == 0 &&
1279
134
      importDescriptor->BoundImportAddressTableRVA == 0 &&
1280
89
      importDescriptor->UnloadInformationTableRVA == 0 &&
1281
46
      importDescriptor->TimeDateStamp == 0);
1282
10.9k
}
1283
1284
char* pe_parse_delay_import_dll_name(PE* pe, uint64_t rva)
1285
9.66k
{
1286
9.66k
  const int64_t offset = pe_rva_to_offset(pe, rva);
1287
1288
9.66k
  if (offset < 0)
1289
1.15k
    return NULL;
1290
1291
8.51k
  char* dll_name = (char*) (pe->data + offset);
1292
1293
8.51k
  if (!pe_valid_dll_name(dll_name, pe->data_size - (size_t) offset))
1294
3.07k
    return NULL;
1295
1296
5.43k
  return yr_strdup(dll_name);
1297
8.51k
}
1298
1299
uint64_t pe_parse_delay_import_pointer(
1300
    PE* pe,
1301
    uint64_t pointerSize,
1302
    uint64_t rva)
1303
6.30M
{
1304
6.30M
  const int64_t offset = pe_rva_to_offset(pe, rva);
1305
1306
6.30M
  if (offset < 0)
1307
2.28k
    return YR_UNDEFINED;
1308
1309
6.30M
  const uint8_t* data = pe->data + offset;
1310
1311
6.30M
  if (!fits_in_pe(pe, data, pointerSize))
1312
1.35k
    return YR_UNDEFINED;
1313
1314
6.30M
  if (IS_64BITS_PE(pe))
1315
4.67M
    return yr_le64toh(yr_unaligned_u64(data));
1316
1.62M
  else
1317
1.62M
    return yr_le32toh(yr_unaligned_u32(data));
1318
6.30M
}
1319
1320
static void* pe_parse_delayed_imports(PE* pe)
1321
6.89k
{
1322
6.89k
  int64_t offset;
1323
6.89k
  uint64_t num_imports = 0;           // Number of imported DLLs
1324
6.89k
  uint64_t num_function_imports = 0;  // Total number of functions imported
1325
6.89k
  uint64_t image_base = OptionalHeader(pe, ImageBase);
1326
6.89k
  uint64_t size_of_image = OptionalHeader(pe, SizeOfImage);
1327
6.89k
  uint64_t pointer_size = (IS_64BITS_PE(pe)) ? 8 : 4;
1328
6.89k
  uint64_t ordinal_mask = (IS_64BITS_PE(pe)) ? IMAGE_ORDINAL_FLAG64
1329
6.89k
                                             : IMAGE_ORDINAL_FLAG32;
1330
1331
6.89k
  IMPORTED_DLL* head_dll = NULL;
1332
6.89k
  IMPORTED_DLL* tail_dll = NULL;
1333
1334
6.89k
  IMPORT_FUNCTION* head_fun = NULL;
1335
6.89k
  IMPORT_FUNCTION* tail_fun = NULL;
1336
1337
6.89k
  PIMAGE_DELAYLOAD_DESCRIPTOR import_descriptor = NULL;
1338
6.89k
  PIMAGE_DATA_DIRECTORY directory = NULL;
1339
1340
  // Default to 0 imports until we know there are any
1341
6.89k
  yr_set_integer(0, pe->object, "number_of_delayed_imports");
1342
6.89k
  yr_set_integer(0, pe->object, "number_of_delayed_imported_functions");
1343
1344
6.89k
  directory = pe_get_directory_entry(pe, IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT);
1345
1346
6.89k
  if (directory == NULL)
1347
0
    return NULL;
1348
1349
6.89k
  if (yr_le32toh(directory->VirtualAddress) == 0)
1350
533
    return NULL;
1351
1352
6.36k
  offset = pe_rva_to_offset(pe, yr_le32toh(directory->VirtualAddress));
1353
1354
6.36k
  if (offset < 0)
1355
4.87k
    return NULL;
1356
1357
1.49k
  import_descriptor = (PIMAGE_DELAYLOAD_DESCRIPTOR) (pe->data + offset);
1358
1359
11.1k
  for (; struct_fits_in_pe(pe, import_descriptor, IMAGE_DELAYLOAD_DESCRIPTOR) &&
1360
10.9k
           num_imports < MAX_PE_IMPORTS;
1361
9.66k
       import_descriptor++)
1362
10.9k
  {
1363
    // Check for the termination entry
1364
10.9k
    if (pe_is_termination_delay_import_entry(import_descriptor))
1365
3
      break;
1366
1367
10.9k
    DWORD Attributes = yr_le32toh(import_descriptor->Attributes.AllAttributes);
1368
10.9k
    DWORD DllNameRVA = yr_le32toh(import_descriptor->DllNameRVA);
1369
10.9k
    DWORD ModuleHandleRVA = yr_le32toh(import_descriptor->ModuleHandleRVA);
1370
10.9k
    DWORD ImportAddressTableRVA = yr_le32toh(
1371
10.9k
        import_descriptor->ImportAddressTableRVA);
1372
10.9k
    DWORD ImportNameTableRVA = yr_le32toh(
1373
10.9k
        import_descriptor->ImportNameTableRVA);
1374
10.9k
    DWORD BoundImportAddressTableRVA = yr_le32toh(
1375
10.9k
        import_descriptor->BoundImportAddressTableRVA);
1376
10.9k
    DWORD UnloadInformationTableRVA = yr_le32toh(
1377
10.9k
        import_descriptor->UnloadInformationTableRVA);
1378
1379
    // Valid delayed import entry starts either with 0 or 0x01.
1380
    // We strict require one of the valid values here
1381
10.9k
    if (Attributes > 0x1)
1382
865
      break;
1383
1384
    // Convert older (MS Visual C++ 6.0) delay-import descriptor to newer one.
1385
    // These delay-import descriptors are distinguishable by lowest bit in
1386
    // rec.Attributes to be zero. Sample:
1387
    // 2775d97f8bdb3311ace960a42eee35dbec84b9d71a6abbacb26c14e83f5897e4
1388
10.0k
    if (!IS_64BITS_PE(pe) && !Attributes)
1389
5.30k
    {
1390
5.30k
      DllNameRVA = (DWORD) pe_normalize_delay_import_value(
1391
5.30k
          image_base, DllNameRVA);
1392
5.30k
      ModuleHandleRVA = (DWORD) pe_normalize_delay_import_value(
1393
5.30k
          image_base, ModuleHandleRVA);
1394
5.30k
      ImportAddressTableRVA = (DWORD) pe_normalize_delay_import_value(
1395
5.30k
          image_base, ImportAddressTableRVA);
1396
5.30k
      ImportNameTableRVA = (DWORD) pe_normalize_delay_import_value(
1397
5.30k
          image_base, ImportNameTableRVA);
1398
5.30k
      BoundImportAddressTableRVA = (DWORD) pe_normalize_delay_import_value(
1399
5.30k
          image_base, BoundImportAddressTableRVA);
1400
5.30k
      UnloadInformationTableRVA = (DWORD) pe_normalize_delay_import_value(
1401
5.30k
          image_base, UnloadInformationTableRVA);
1402
5.30k
    }
1403
1404
    // Stop on blatantly invalid delay import entries (old PELIB behavior)
1405
10.0k
    if (ImportNameTableRVA >= size_of_image ||
1406
9.91k
        ImportAddressTableRVA >= size_of_image ||
1407
9.87k
        DllNameRVA < sizeof(IMAGE_DOS_HEADER) ||
1408
9.68k
        ImportNameTableRVA < sizeof(IMAGE_DOS_HEADER))
1409
431
      break;
1410
1411
9.66k
    char* dll_name = pe_parse_delay_import_dll_name(pe, DllNameRVA);
1412
1413
9.66k
    if (dll_name == NULL)
1414
4.23k
      continue;
1415
1416
5.43k
    IMPORTED_DLL* imported_dll = (IMPORTED_DLL*) yr_calloc(
1417
5.43k
        1, sizeof(IMPORTED_DLL));
1418
1419
5.43k
    if (imported_dll == NULL)
1420
0
    {
1421
0
      yr_free(dll_name);
1422
0
      continue;
1423
0
    }
1424
1425
5.43k
    imported_dll->name = dll_name;
1426
5.43k
    imported_dll->next = NULL;
1427
5.43k
    imported_dll->functions = NULL;
1428
1429
5.43k
    head_fun = tail_fun = NULL;
1430
1431
5.43k
    uint64_t name_rva = ImportNameTableRVA;
1432
5.43k
    uint64_t func_rva = ImportAddressTableRVA;
1433
1434
3.15M
    for (;num_function_imports < MAX_PE_IMPORTS;)
1435
3.15M
    {
1436
3.15M
      uint64_t nameAddress = pe_parse_delay_import_pointer(
1437
3.15M
          pe, pointer_size, name_rva);
1438
1439
3.15M
      uint64_t funcAddress = pe_parse_delay_import_pointer(
1440
3.15M
          pe, pointer_size, func_rva);
1441
1442
      // Value of YR_UNDEFINED means that value is outside of pe->data
1443
3.15M
      if (nameAddress == YR_UNDEFINED || funcAddress == YR_UNDEFINED)
1444
2.83k
        break;
1445
1446
      // Value of zero means that this is the end of the bound import name table
1447
3.15M
      if (nameAddress == 0 || funcAddress == 0)
1448
1.94k
        break;
1449
1450
3.14M
      char* func_name;
1451
3.14M
      uint8_t has_ordinal = 0;
1452
1453
      // Check name address. It could be ordinal, VA or RVA
1454
3.14M
      if (!(nameAddress & ordinal_mask))
1455
2.35M
      {
1456
        // Convert name address to RVA, if needed
1457
2.35M
        if (!Attributes)
1458
2.35M
          nameAddress = pe_normalize_delay_import_value(
1459
2.35M
              image_base, nameAddress);
1460
1461
2.35M
        offset = pe_rva_to_offset(pe, nameAddress + sizeof(uint16_t));
1462
1463
2.35M
        if (offset < 0)
1464
2.30M
        {
1465
2.30M
          name_rva += pointer_size;
1466
2.30M
          func_rva += pointer_size;
1467
2.30M
          continue;
1468
2.30M
        }
1469
1470
47.9k
        func_name = (char*) yr_strndup(
1471
47.9k
            (char*) (pe->data + offset),
1472
47.9k
            yr_min(available_space(pe, (char*) (pe->data + offset)), 512));
1473
47.9k
      }
1474
791k
      else
1475
791k
      {
1476
        // If imported by ordinal. Lookup the ordinal.
1477
791k
        func_name = ord_lookup(dll_name, nameAddress & 0xFFFF);
1478
791k
        has_ordinal = 1;
1479
791k
      }
1480
1481
839k
      IMPORT_FUNCTION* imported_func = (IMPORT_FUNCTION*) yr_malloc(
1482
839k
          sizeof(IMPORT_FUNCTION));
1483
1484
839k
      if (imported_func == NULL)
1485
0
        break;
1486
1487
839k
      imported_func->name = func_name;
1488
839k
      imported_func->rva = func_rva;
1489
839k
      imported_func->has_ordinal = has_ordinal;
1490
839k
      imported_func->ordinal = (has_ordinal) ? nameAddress & 0xFFFF : 0;
1491
839k
      imported_func->next = NULL;
1492
1493
839k
      num_function_imports++;
1494
839k
      name_rva += pointer_size;
1495
839k
      func_rva += pointer_size;
1496
1497
839k
      if (head_fun == NULL)
1498
2.59k
        head_fun = imported_func;
1499
1500
839k
      if (tail_fun != NULL)
1501
837k
        tail_fun->next = imported_func;
1502
1503
839k
      tail_fun = imported_func;
1504
839k
    }
1505
1506
5.43k
    num_imports++;
1507
1508
5.43k
    imported_dll->functions = head_fun;
1509
1510
5.43k
    if (head_dll == NULL)
1511
456
      head_dll = imported_dll;
1512
1513
5.43k
    if (tail_dll != NULL)
1514
4.97k
      tail_dll->next = imported_dll;
1515
1516
5.43k
    tail_dll = imported_dll;
1517
5.43k
  }
1518
1519
1.49k
  yr_set_integer(num_imports, pe->object, "number_of_delayed_imports");
1520
1.49k
  yr_set_integer(
1521
1.49k
      num_function_imports, pe->object, "number_of_delayed_imported_functions");
1522
1523
1.49k
  pe_set_imports(
1524
1.49k
      pe,
1525
1.49k
      head_dll,
1526
1.49k
      "delayed_import_details[%i].library_name",
1527
1.49k
      "delayed_import_details[%i].number_of_functions",
1528
1.49k
      "delayed_import_details[%i].functions[%i].name",
1529
1.49k
      "delayed_import_details[%i].functions[%i].ordinal",
1530
1.49k
      "delayed_import_details[%i].functions[%i].rva");
1531
1532
1.49k
  return head_dll;
1533
6.36k
}
1534
1535
//
1536
// Walk the exports and collect relevant information. It is used in the
1537
// "exports" function for comparison.
1538
//
1539
1540
static void pe_parse_exports(PE* pe)
1541
6.89k
{
1542
6.89k
  PIMAGE_DATA_DIRECTORY directory;
1543
6.89k
  PIMAGE_EXPORT_DIRECTORY exports;
1544
1545
6.89k
  int64_t offset;
1546
6.89k
  int64_t export_start;
1547
1548
6.89k
  uint32_t i, j;
1549
6.89k
  uint32_t number_of_exports;
1550
6.89k
  uint32_t number_of_names;
1551
6.89k
  uint32_t ordinal_base;
1552
1553
6.89k
  size_t export_size;
1554
6.89k
  size_t remaining;
1555
6.89k
  size_t name_len;
1556
1557
6.89k
  uint32_t exp_sz = 0;
1558
6.89k
  DWORD* names = NULL;
1559
6.89k
  WORD* ordinals = NULL;
1560
6.89k
  DWORD* function_addrs = NULL;
1561
1562
  // If not a PE file, return YR_UNDEFINED
1563
1564
6.89k
  if (pe == NULL)
1565
0
    return;
1566
1567
  // Default to 0 exports until we know there are any
1568
6.89k
  yr_set_integer(0, pe->object, "number_of_exports");
1569
1570
6.89k
  directory = pe_get_directory_entry(pe, IMAGE_DIRECTORY_ENTRY_EXPORT);
1571
1572
6.89k
  if (directory == NULL)
1573
0
    return;
1574
1575
6.89k
  if (yr_le32toh(directory->VirtualAddress) == 0)
1576
547
    return;
1577
1578
6.34k
  offset = pe_rva_to_offset(pe, yr_le32toh(directory->VirtualAddress));
1579
1580
6.34k
  if (offset < 0)
1581
5.44k
    return;
1582
1583
905
  export_start = offset;
1584
905
  export_size = yr_le32toh(directory->Size);
1585
1586
905
  exports = (PIMAGE_EXPORT_DIRECTORY) (pe->data + offset);
1587
1588
905
  if (!struct_fits_in_pe(pe, exports, IMAGE_EXPORT_DIRECTORY))
1589
25
    return;
1590
1591
880
  number_of_exports = yr_min(
1592
880
      yr_le32toh(exports->NumberOfFunctions), MAX_PE_EXPORTS);
1593
1594
880
  ordinal_base = yr_le32toh(exports->Base);
1595
1596
880
  yr_set_integer(
1597
880
      yr_le32toh(exports->TimeDateStamp), pe->object, "export_timestamp");
1598
1599
880
  offset = pe_rva_to_offset(pe, yr_le32toh(exports->Name));
1600
1601
880
  if (offset > 0)
1602
185
  {
1603
185
    remaining = pe->data_size - (size_t) offset;
1604
185
    name_len = strnlen((char*) (pe->data + offset), remaining);
1605
185
    yr_set_sized_string(
1606
185
        (char*) (pe->data + offset), name_len, pe->object, "dll_name");
1607
185
  }
1608
1609
880
  if (number_of_exports * sizeof(DWORD) > pe->data_size - offset)
1610
437
    return;
1611
1612
443
  if (yr_le32toh(exports->NumberOfNames) > 0)
1613
335
  {
1614
335
    offset = pe_rva_to_offset(pe, yr_le32toh(exports->AddressOfNames));
1615
1616
335
    if (offset < 0)
1617
86
      return;
1618
1619
249
    if (yr_le32toh(exports->NumberOfNames) >
1620
249
        (pe->data_size - offset) / sizeof(DWORD))
1621
120
      return;
1622
1623
129
    names = (DWORD*) (pe->data + offset);
1624
129
  }
1625
1626
237
  offset = pe_rva_to_offset(pe, yr_le32toh(exports->AddressOfNameOrdinals));
1627
1628
237
  if (offset < 0)
1629
12
    return;
1630
1631
225
  ordinals = (WORD*) (pe->data + offset);
1632
1633
225
  if (available_space(pe, ordinals) < sizeof(WORD) * number_of_exports)
1634
6
    return;
1635
1636
219
  offset = pe_rva_to_offset(pe, yr_le32toh(exports->AddressOfFunctions));
1637
1638
219
  if (offset < 0)
1639
17
    return;
1640
1641
202
  function_addrs = (DWORD*) (pe->data + offset);
1642
1643
202
  if (available_space(pe, function_addrs) < sizeof(DWORD) * number_of_exports)
1644
12
    return;
1645
1646
190
  number_of_names = yr_min(
1647
190
      yr_le32toh(exports->NumberOfNames), number_of_exports);
1648
1649
  // Mapping out the exports is a bit janky. We start with the export address
1650
  // array. The index from that array plus the ordinal base is the ordinal for
1651
  // that export. To find the name we walk the ordinal array looking for a value
1652
  // that matches our index. If one exists we look up the corresponding RVA from
1653
  // the names array and follow it to get the name. If one does not exist then
1654
  // the export has no name.
1655
  //
1656
  // Ordinal base: 5
1657
  //                       0            1            2
1658
  // Address array: [ 0x00000011 | 0x00000022 | 0x00000033 ]
1659
  //                     0        1        2
1660
  // Ordinal array: [ 0x0000 | 0x0002 | 0x0001 ]
1661
  //                       0            1
1662
  // Names array:   [ 0x00000044 | 0x00000055 ]
1663
  //
1664
  // The function at RVA 0x00000011 (index 0) has ordinal 5 (base + index). The
1665
  // index can be found in position 0 in the ordinal array. Using 0 to index
1666
  // into the name array gives us an RVA (0x00000044) which we can follow to get
1667
  // the name.
1668
  //
1669
  // The function at RVA 0x00000022 (index 1) has ordinal 6 (base + index). The
1670
  // index can be found in position 2 in the ordinal array. 2 is out of bounds
1671
  // for the names array so this function is exported without a name.
1672
  //
1673
  // The function at RVA 0x00000033 (index 2) has ordinal 7 (base + index). The
1674
  // index can be found in position 1 in the ordinal array. Using 1 to index
1675
  // into the name array gives us an RVA (0x00000055) which we can follow to get
1676
  // the name.
1677
  //
1678
  // If the RVA from the address array is within the export directory it is a
1679
  // forwarder RVA and points to a NULL terminated ASCII string.
1680
1681
335k
  for (i = 0; i < number_of_exports; i++)
1682
335k
  {
1683
335k
    yr_set_integer(
1684
335k
        ordinal_base + i, pe->object, "export_details[%i].ordinal", exp_sz);
1685
1686
335k
    yr_set_integer(
1687
335k
        yr_le32toh(function_addrs[i]),
1688
335k
        pe->object,
1689
335k
        "export_details[%i].rva",
1690
335k
        exp_sz);
1691
1692
    // Don't check for a failure here since some packers make this an invalid
1693
    // value.
1694
335k
    offset = pe_rva_to_offset(pe, yr_le32toh(function_addrs[i]));
1695
1696
335k
    if (offset > export_start && offset < export_start + export_size)
1697
14.8k
    {
1698
14.8k
      remaining = pe->data_size - (size_t) offset;
1699
14.8k
      name_len = strnlen((char*) (pe->data + offset), remaining);
1700
1701
14.8k
      yr_set_sized_string(
1702
14.8k
          (char*) (pe->data + offset),
1703
14.8k
          yr_min(name_len, MAX_EXPORT_NAME_LENGTH),
1704
14.8k
          pe->object,
1705
14.8k
          "export_details[%i].forward_name",
1706
14.8k
          exp_sz);
1707
14.8k
    }
1708
320k
    else
1709
320k
    {
1710
320k
      if (offset < 0)
1711
254k
        offset = YR_UNDEFINED;
1712
320k
      yr_set_integer(offset, pe->object, "export_details[%i].offset", exp_sz);
1713
320k
    }
1714
1715
335k
    if (names != NULL)
1716
192k
    {
1717
2.67G
      for (j = 0; j < number_of_exports; j++)
1718
2.67G
      {
1719
2.67G
        if (yr_le16toh(ordinals[j]) == i && j < number_of_names)
1720
9.76k
        {
1721
9.76k
          offset = pe_rva_to_offset(pe, yr_le32toh(names[j]));
1722
1723
9.76k
          if (offset > 0)
1724
1.30k
          {
1725
1.30k
            remaining = pe->data_size - (size_t) offset;
1726
1.30k
            name_len = strnlen((char*) (pe->data + offset), remaining);
1727
1728
1.30k
            yr_set_sized_string(
1729
1.30k
                (char*) (pe->data + offset),
1730
1.30k
                yr_min(name_len, MAX_EXPORT_NAME_LENGTH),
1731
1.30k
                pe->object,
1732
1.30k
                "export_details[%i].name",
1733
1.30k
                exp_sz);
1734
1.30k
          }
1735
9.76k
          break;
1736
9.76k
        }
1737
2.67G
      }
1738
192k
    }
1739
335k
    exp_sz++;
1740
335k
  }
1741
1742
190
  yr_set_integer(exp_sz, pe->object, "number_of_exports");
1743
190
}
1744
1745
// BoringSSL (https://boringssl.googlesource.com/boringssl/) doesn't support
1746
// some features used in pe_parse_certificates, if you are using BoringSSL
1747
// instead of OpenSSL you should define BORINGSSL for YARA to compile properly,
1748
// but you won't have signature-related features in the PE module.
1749
#if defined(HAVE_LIBCRYPTO) && !defined(BORINGSSL)
1750
1751
#define write_certificate(cert, pe, fmt, ...)                                  \
1752
  do                                                                           \
1753
  {                                                                            \
1754
    char thumbprint_ascii[YR_SHA1_LEN * 2 + 1];                                \
1755
    for (int j = 0; j < cert->sha1.len; ++j)                                   \
1756
      sprintf(thumbprint_ascii + (j * 2), "%02x", cert->sha1.data[j]);         \
1757
    thumbprint_ascii[cert->sha1.len * 2] = '\0';                               \
1758
                                                                               \
1759
    yr_set_string(                                                             \
1760
        (char*) thumbprint_ascii, pe->object, fmt ".thumbprint", __VA_ARGS__); \
1761
                                                                               \
1762
    yr_set_string(cert->issuer, pe->object, fmt ".issuer", __VA_ARGS__);       \
1763
    yr_set_string(cert->subject, pe->object, fmt ".subject", __VA_ARGS__);     \
1764
    /* Versions are zero based, so add one.  */                                \
1765
    yr_set_integer(                                                            \
1766
        cert->version + 1, pe->object, fmt ".version", __VA_ARGS__);           \
1767
    yr_set_string(cert->sig_alg, pe->object, fmt ".algorithm", __VA_ARGS__);   \
1768
    yr_set_string(                                                             \
1769
        cert->sig_alg_oid, pe->object, fmt ".algorithm_oid", __VA_ARGS__);     \
1770
    yr_set_string(cert->serial, pe->object, fmt ".serial", __VA_ARGS__);       \
1771
    yr_set_integer(                                                            \
1772
        cert->not_before, pe->object, fmt ".not_before", __VA_ARGS__);         \
1773
    yr_set_integer(                                                            \
1774
        cert->not_after, pe->object, fmt ".not_after", __VA_ARGS__);           \
1775
  } while (0)
1776
1777
static char* digest_to_ascii(const ByteArray* digest)
1778
{
1779
  if (digest == NULL || digest->data == NULL || digest->len <= 0 ||
1780
      digest->len > EVP_MAX_MD_SIZE)
1781
    return NULL;
1782
1783
  size_t digest_len = (size_t) digest->len;
1784
  char* digest_ascii = (char*) yr_malloc(digest_len * 2 + 1);
1785
  if (digest_ascii == NULL)
1786
    return NULL;
1787
1788
  for (size_t i = 0; i < digest_len; i++)
1789
    snprintf(digest_ascii + (i * 2), 3, "%02x", digest->data[i]);
1790
1791
  digest_ascii[digest_len * 2] = '\0';
1792
  return digest_ascii;
1793
}
1794
1795
void _process_authenticode(
1796
    PE* pe,
1797
    AuthenticodeArray* auth_array,
1798
    int* sig_count)
1799
{
1800
  if (!auth_array || !auth_array->count)
1801
    return;
1802
1803
  bool signature_valid = false;
1804
1805
  for (size_t i = 0; i < auth_array->count; ++i)
1806
  {
1807
    const Authenticode* authenticode = auth_array->signatures[i];
1808
1809
    if (authenticode->verify_flags == AUTHENTICODE_VFY_CANT_PARSE)
1810
      continue;
1811
1812
    if (authenticode->verify_flags == AUTHENTICODE_VFY_WRONG_PKCS7_TYPE)
1813
      continue;
1814
1815
    if (authenticode->verify_flags == AUTHENTICODE_VFY_NO_SIGNER_INFO)
1816
      continue;
1817
1818
    if (authenticode->verify_flags == AUTHENTICODE_VFY_NO_SIGNER_CERT)
1819
      continue;
1820
1821
    if (authenticode->verify_flags == AUTHENTICODE_VFY_INTERNAL_ERROR)
1822
      continue;
1823
1824
    bool verified = authenticode->verify_flags == AUTHENTICODE_VFY_VALID;
1825
1826
    /* If any signature is valid -> file is correctly signed */
1827
    signature_valid |= verified;
1828
1829
    yr_set_integer(verified, pe->object, "signatures[%i].verified", *sig_count);
1830
1831
    yr_set_string(
1832
        authenticode->digest_alg,
1833
        pe->object,
1834
        "signatures[%i].digest_alg",
1835
        *sig_count);
1836
1837
    char* digest_ascii = digest_to_ascii(&authenticode->digest);
1838
    if (digest_ascii != NULL)
1839
    {
1840
      yr_set_string(
1841
          digest_ascii, pe->object, "signatures[%i].digest", *sig_count);
1842
      yr_free(digest_ascii);
1843
    }
1844
1845
    digest_ascii = digest_to_ascii(&authenticode->file_digest);
1846
    if (digest_ascii != NULL)
1847
    {
1848
      yr_set_string(
1849
          digest_ascii, pe->object, "signatures[%i].file_digest", *sig_count);
1850
      yr_free(digest_ascii);
1851
    }
1852
1853
    yr_set_integer(
1854
        authenticode->certs ? authenticode->certs->count : 0,
1855
        pe->object,
1856
        "signatures[%i].number_of_certificates",
1857
        *sig_count);
1858
1859
    if (authenticode->certs)
1860
    {
1861
      for (int k = 0; k < authenticode->certs->count; ++k)
1862
      {
1863
        write_certificate(
1864
            authenticode->certs->certs[k],
1865
            pe,
1866
            "signatures[%i].certificates[%i]",
1867
            *sig_count,
1868
            k);
1869
      }
1870
    }
1871
1872
    const Signer* signer = authenticode->signer;
1873
    if (signer)
1874
    {
1875
      /* For compatibility with previous YARA rules, write information
1876
       * about signing certificate in the same way */
1877
      if (signer->chain && signer->chain->count >= 1)
1878
      {
1879
        const Certificate* sign_cert = signer->chain->certs[0];
1880
        write_certificate(sign_cert, pe, "signatures[%i]", *sig_count);
1881
      }
1882
1883
      yr_set_string(
1884
          signer->program_name,
1885
          pe->object,
1886
          "signatures[%i].signer_info.program_name",
1887
          *sig_count);
1888
      yr_set_string(
1889
          signer->digest_alg,
1890
          pe->object,
1891
          "signatures[%i].signer_info.digest_alg",
1892
          *sig_count);
1893
1894
      digest_ascii = digest_to_ascii(&signer->digest);
1895
      if (digest_ascii != NULL)
1896
      {
1897
        yr_set_string(
1898
            digest_ascii,
1899
            pe->object,
1900
            "signatures[%i].signer_info.digest",
1901
            *sig_count);
1902
        yr_free(digest_ascii);
1903
      }
1904
1905
      yr_set_integer(
1906
          signer->chain ? signer->chain->count : 0,
1907
          pe->object,
1908
          "signatures[%i].signer_info.length_of_chain",
1909
          *sig_count);
1910
1911
      if (signer->chain)
1912
      {
1913
        for (int k = 0; k < signer->chain->count; ++k)
1914
        {
1915
          write_certificate(
1916
              signer->chain->certs[k],
1917
              pe,
1918
              "signatures[%i].signer_info.chain[%i]",
1919
              *sig_count,
1920
              k);
1921
        }
1922
      }
1923
    }
1924
1925
    yr_set_integer(
1926
        authenticode->countersigs ? authenticode->countersigs->count : 0,
1927
        pe->object,
1928
        "signatures[%i].number_of_countersignatures",
1929
        *sig_count);
1930
1931
    if (authenticode->countersigs)
1932
    {
1933
      for (int j = 0; j < authenticode->countersigs->count; ++j)
1934
      {
1935
        const Countersignature* counter =
1936
            authenticode->countersigs->counters[j];
1937
1938
        yr_set_integer(
1939
            counter->verify_flags == COUNTERSIGNATURE_VFY_VALID,
1940
            pe->object,
1941
            "signatures[%i].countersignatures[%i].verified",
1942
            *sig_count,
1943
            j);
1944
        yr_set_string(
1945
            counter->digest_alg,
1946
            pe->object,
1947
            "signatures[%i].countersignatures[%i].digest_alg",
1948
            *sig_count,
1949
            j);
1950
        yr_set_integer(
1951
            counter->sign_time,
1952
            pe->object,
1953
            "signatures[%i].countersignatures[%i].sign_time",
1954
            *sig_count,
1955
            j);
1956
1957
        digest_ascii = digest_to_ascii(&counter->digest);
1958
        if (digest_ascii != NULL)
1959
        {
1960
          yr_set_string(
1961
              digest_ascii,
1962
              pe->object,
1963
              "signatures[%i].countersignatures[%i].digest",
1964
              *sig_count,
1965
              j);
1966
          yr_free(digest_ascii);
1967
        }
1968
1969
        yr_set_integer(
1970
            counter->chain ? counter->chain->count : 0,
1971
            pe->object,
1972
            "signatures[%i].countersignatures[%i].length_of_chain",
1973
            *sig_count,
1974
            j);
1975
1976
        if (counter->chain)
1977
        {
1978
          for (int k = 0; k < counter->chain->count; ++k)
1979
          {
1980
            write_certificate(
1981
                counter->chain->certs[k],
1982
                pe,
1983
                "signatures[%i].countersignatures[%i].chain[%i]",
1984
                *sig_count,
1985
                j,
1986
                k);
1987
          }
1988
        }
1989
      }
1990
    }
1991
1992
    (*sig_count)++;
1993
  }
1994
1995
  yr_set_integer(signature_valid, pe->object, "is_signed");
1996
}
1997
1998
static void pe_parse_certificates(PE* pe)
1999
{
2000
  int counter = 0;
2001
2002
  // Default to 0 signatures until we know otherwise.
2003
  yr_set_integer(0, pe->object, "number_of_signatures");
2004
  // Default to not signed until we know otherwise.
2005
  yr_set_integer(0, pe->object, "is_signed");
2006
2007
  PIMAGE_DATA_DIRECTORY directory = pe_get_directory_entry(
2008
      pe, IMAGE_DIRECTORY_ENTRY_SECURITY);
2009
2010
  if (directory == NULL)
2011
    return;
2012
2013
  // directory->VirtualAddress is a file offset. Don't call pe_rva_to_offset().
2014
  if (yr_le32toh(directory->VirtualAddress) == 0 ||
2015
      yr_le32toh(directory->VirtualAddress) > pe->data_size ||
2016
      yr_le32toh(directory->Size) > pe->data_size ||
2017
      yr_le32toh(directory->VirtualAddress) + yr_le32toh(directory->Size) >
2018
          pe->data_size)
2019
  {
2020
    return;
2021
  }
2022
2023
  AuthenticodeArray* auth_array = parse_authenticode(pe->data, pe->data_size);
2024
  _process_authenticode(pe, auth_array, &counter);
2025
  authenticode_array_free(auth_array);
2026
2027
  yr_set_integer(counter, pe->object, "number_of_signatures");
2028
}
2029
2030
#endif  // defined(HAVE_LIBCRYPTO)
2031
2032
const char* pe_get_section_full_name(
2033
    PE* pe,
2034
    const char* section_name,
2035
    uint64_t section_name_length,
2036
    uint64_t* section_full_name_length)
2037
11.4k
{
2038
  // section_name is an 8-byte, null-padded UTF-8 encoded string. If the string
2039
  // is exactly 8 characters long, there is no terminating null. For longer
2040
  // names, this field contains a slash (/) that is followed by an ASCII
2041
  // representation of a decimal number that is an offset into the string table.
2042
2043
  // Sample: 2e9c671b8a0411f2b397544b368c44d7f095eb395779de0ad1ac946914dfa34c
2044
2045
  // Check if any param is NULL
2046
11.4k
  if (pe == NULL || section_name == NULL || section_full_name_length == NULL)
2047
0
    return NULL;
2048
2049
  // Set length to zero
2050
11.4k
  *section_full_name_length = 0;
2051
2052
  // Offset and number of records in coff table
2053
11.4k
  uint64_t coff_offset = yr_le32toh(
2054
11.4k
      pe->header->FileHeader.PointerToSymbolTable);
2055
11.4k
  uint64_t coff_number = yr_le32toh(pe->header->FileHeader.NumberOfSymbols);
2056
2057
  // If section name start with '/' and file contain coff table then section
2058
  // name is stored in string table
2059
11.4k
  if (coff_offset == 0 || section_name[0] != '/')
2060
10.5k
  {
2061
10.5k
    *section_full_name_length = section_name_length;
2062
10.5k
    return section_name;
2063
10.5k
  }
2064
2065
  // Calculate offset of string table (String table is immediately after coff
2066
  // table)
2067
933
  uint64_t string_offset = coff_offset + coff_number * sizeof(IMAGE_SYMBOL);
2068
933
  uint64_t string_index = 0;
2069
2070
  // Calculate string index/offset in string table
2071
933
  for (int i = 1;
2072
1.84k
       i < IMAGE_SIZEOF_SHORT_NAME && isdigit((unsigned char) section_name[i]);
2073
933
       i++)
2074
913
    string_index = (string_index * 10) + (section_name[i] - '0');
2075
2076
  // Calculate string pointer
2077
933
  const char* string = (char*) (pe->data + string_offset + string_index);
2078
2079
  // Check string
2080
4.50M
  for (uint64_t len = 0; fits_in_pe(pe, string, len + 1); len++)
2081
4.50M
  {
2082
    // Prevent sign extension to 32-bits on bytes > 0x7F
2083
    // The result negative integer would cause assert in MSVC debug version of
2084
    // isprint()
2085
4.50M
    unsigned int one_char = (unsigned char) (string[len]);
2086
2087
    // Valid string
2088
4.50M
    if (one_char == 0)
2089
215
    {
2090
215
      *section_full_name_length = len;
2091
215
      return string;
2092
215
    }
2093
2094
    // string contain unprintable character
2095
4.50M
    if (!isprint(one_char))
2096
193
      return NULL;
2097
4.50M
  }
2098
2099
  // String do not fit into pe file
2100
525
  return NULL;
2101
933
}
2102
2103
static void pe_parse_header(PE* pe, uint64_t base_address, int flags)
2104
6.89k
{
2105
6.89k
  PIMAGE_SECTION_HEADER section;
2106
6.89k
  PIMAGE_DATA_DIRECTORY data_dir;
2107
2108
6.89k
  char section_name[IMAGE_SIZEOF_SHORT_NAME + 1];
2109
6.89k
  int sect_name_length;
2110
2111
6.89k
  uint16_t scount;
2112
6.89k
  uint32_t ddcount;
2113
2114
6.89k
  uint64_t highest_sec_siz = 0;
2115
6.89k
  uint64_t highest_sec_ofs = 0;
2116
6.89k
  uint64_t section_end;
2117
6.89k
  uint64_t last_section_end;
2118
2119
6.89k
  yr_set_integer(1, pe->object, "is_pe");
2120
2121
6.89k
  yr_set_integer(
2122
6.89k
      yr_le16toh(pe->header->FileHeader.Machine), pe->object, "machine");
2123
2124
6.89k
  yr_set_integer(
2125
6.89k
      yr_le16toh(pe->header->FileHeader.NumberOfSections),
2126
6.89k
      pe->object,
2127
6.89k
      "number_of_sections");
2128
2129
6.89k
  yr_set_integer(
2130
6.89k
      yr_le32toh(pe->header->FileHeader.TimeDateStamp),
2131
6.89k
      pe->object,
2132
6.89k
      "timestamp");
2133
2134
6.89k
  yr_set_integer(
2135
6.89k
      yr_le32toh(pe->header->FileHeader.PointerToSymbolTable),
2136
6.89k
      pe->object,
2137
6.89k
      "pointer_to_symbol_table");
2138
2139
6.89k
  yr_set_integer(
2140
6.89k
      yr_le32toh(pe->header->FileHeader.NumberOfSymbols),
2141
6.89k
      pe->object,
2142
6.89k
      "number_of_symbols");
2143
2144
6.89k
  yr_set_integer(
2145
6.89k
      yr_le16toh(pe->header->FileHeader.SizeOfOptionalHeader),
2146
6.89k
      pe->object,
2147
6.89k
      "size_of_optional_header");
2148
2149
6.89k
  yr_set_integer(
2150
6.89k
      yr_le16toh(pe->header->FileHeader.Characteristics),
2151
6.89k
      pe->object,
2152
6.89k
      "characteristics");
2153
2154
6.89k
  yr_set_integer(
2155
6.89k
      flags & SCAN_FLAGS_PROCESS_MEMORY
2156
6.89k
          ? base_address + yr_le32toh(OptionalHeader(pe, AddressOfEntryPoint))
2157
6.89k
          : pe_rva_to_offset(
2158
6.89k
                pe, yr_le32toh(OptionalHeader(pe, AddressOfEntryPoint))),
2159
6.89k
      pe->object,
2160
6.89k
      "entry_point");
2161
2162
6.89k
  yr_set_integer(
2163
6.89k
      yr_le32toh(OptionalHeader(pe, AddressOfEntryPoint)),
2164
6.89k
      pe->object,
2165
6.89k
      "entry_point_raw");
2166
2167
6.89k
  yr_set_integer(
2168
6.89k
      IS_64BITS_PE(pe) ? yr_le64toh(OptionalHeader(pe, ImageBase))
2169
6.89k
                       : yr_le32toh(OptionalHeader(pe, ImageBase)),
2170
6.89k
      pe->object,
2171
6.89k
      "image_base");
2172
2173
6.89k
  yr_set_integer(
2174
6.89k
      yr_le32toh(OptionalHeader(pe, NumberOfRvaAndSizes)),
2175
6.89k
      pe->object,
2176
6.89k
      "number_of_rva_and_sizes");
2177
2178
6.89k
  yr_set_integer(
2179
6.89k
      yr_le16toh(OptionalHeader(pe, Magic)), pe->object, "opthdr_magic");
2180
2181
6.89k
  yr_set_integer(
2182
6.89k
      OptionalHeader(pe, MajorLinkerVersion),
2183
6.89k
      pe->object,
2184
6.89k
      "linker_version.major");
2185
2186
6.89k
  yr_set_integer(
2187
6.89k
      OptionalHeader(pe, MinorLinkerVersion),
2188
6.89k
      pe->object,
2189
6.89k
      "linker_version.minor");
2190
2191
6.89k
  yr_set_integer(
2192
6.89k
      yr_le32toh(OptionalHeader(pe, SizeOfCode)), pe->object, "size_of_code");
2193
2194
6.89k
  yr_set_integer(
2195
6.89k
      yr_le32toh(OptionalHeader(pe, SizeOfInitializedData)),
2196
6.89k
      pe->object,
2197
6.89k
      "size_of_initialized_data");
2198
2199
6.89k
  yr_set_integer(
2200
6.89k
      yr_le32toh(OptionalHeader(pe, SizeOfUninitializedData)),
2201
6.89k
      pe->object,
2202
6.89k
      "size_of_uninitialized_data");
2203
2204
6.89k
  yr_set_integer(
2205
6.89k
      yr_le32toh(OptionalHeader(pe, BaseOfCode)), pe->object, "base_of_code");
2206
2207
6.89k
  if (!IS_64BITS_PE(pe))
2208
5.94k
  {
2209
5.94k
    yr_set_integer(
2210
5.94k
        yr_le32toh(pe->header->OptionalHeader.BaseOfData),
2211
5.94k
        pe->object,
2212
5.94k
        "base_of_data");
2213
5.94k
  }
2214
2215
6.89k
  yr_set_integer(
2216
6.89k
      yr_le32toh(OptionalHeader(pe, SectionAlignment)),
2217
6.89k
      pe->object,
2218
6.89k
      "section_alignment");
2219
2220
6.89k
  yr_set_integer(
2221
6.89k
      yr_le32toh(OptionalHeader(pe, FileAlignment)),
2222
6.89k
      pe->object,
2223
6.89k
      "file_alignment");
2224
2225
6.89k
  yr_set_integer(
2226
6.89k
      yr_le16toh(OptionalHeader(pe, MajorOperatingSystemVersion)),
2227
6.89k
      pe->object,
2228
6.89k
      "os_version.major");
2229
2230
6.89k
  yr_set_integer(
2231
6.89k
      yr_le16toh(OptionalHeader(pe, MinorOperatingSystemVersion)),
2232
6.89k
      pe->object,
2233
6.89k
      "os_version.minor");
2234
2235
6.89k
  yr_set_integer(
2236
6.89k
      yr_le16toh(OptionalHeader(pe, MajorImageVersion)),
2237
6.89k
      pe->object,
2238
6.89k
      "image_version.major");
2239
2240
6.89k
  yr_set_integer(
2241
6.89k
      yr_le16toh(OptionalHeader(pe, MinorImageVersion)),
2242
6.89k
      pe->object,
2243
6.89k
      "image_version.minor");
2244
2245
6.89k
  yr_set_integer(
2246
6.89k
      yr_le16toh(OptionalHeader(pe, MajorSubsystemVersion)),
2247
6.89k
      pe->object,
2248
6.89k
      "subsystem_version.major");
2249
2250
6.89k
  yr_set_integer(
2251
6.89k
      yr_le16toh(OptionalHeader(pe, MinorSubsystemVersion)),
2252
6.89k
      pe->object,
2253
6.89k
      "subsystem_version.minor");
2254
2255
6.89k
  yr_set_integer(
2256
6.89k
      yr_le32toh(OptionalHeader(pe, Win32VersionValue)),
2257
6.89k
      pe->object,
2258
6.89k
      "win32_version_value");
2259
2260
6.89k
  yr_set_integer(
2261
6.89k
      yr_le32toh(OptionalHeader(pe, SizeOfImage)), pe->object, "size_of_image");
2262
2263
6.89k
  yr_set_integer(
2264
6.89k
      yr_le32toh(OptionalHeader(pe, SizeOfHeaders)),
2265
6.89k
      pe->object,
2266
6.89k
      "size_of_headers");
2267
2268
6.89k
  yr_set_integer(
2269
6.89k
      yr_le32toh(OptionalHeader(pe, CheckSum)), pe->object, "checksum");
2270
2271
6.89k
  yr_set_integer(
2272
6.89k
      yr_le16toh(OptionalHeader(pe, Subsystem)), pe->object, "subsystem");
2273
2274
6.89k
  yr_set_integer(
2275
6.89k
      yr_le16toh(OptionalHeader(pe, DllCharacteristics)),
2276
6.89k
      pe->object,
2277
6.89k
      "dll_characteristics");
2278
2279
6.89k
  yr_set_integer(
2280
6.89k
      IS_64BITS_PE(pe) ? yr_le64toh(OptionalHeader(pe, SizeOfStackReserve))
2281
6.89k
                       : yr_le32toh(OptionalHeader(pe, SizeOfStackReserve)),
2282
6.89k
      pe->object,
2283
6.89k
      "size_of_stack_reserve");
2284
2285
6.89k
  yr_set_integer(
2286
6.89k
      IS_64BITS_PE(pe) ? yr_le64toh(OptionalHeader(pe, SizeOfStackCommit))
2287
6.89k
                       : yr_le32toh(OptionalHeader(pe, SizeOfStackCommit)),
2288
6.89k
      pe->object,
2289
6.89k
      "size_of_stack_commit");
2290
2291
6.89k
  yr_set_integer(
2292
6.89k
      IS_64BITS_PE(pe) ? yr_le64toh(OptionalHeader(pe, SizeOfHeapReserve))
2293
6.89k
                       : yr_le32toh(OptionalHeader(pe, SizeOfHeapReserve)),
2294
6.89k
      pe->object,
2295
6.89k
      "size_of_heap_reserve");
2296
2297
6.89k
  yr_set_integer(
2298
6.89k
      IS_64BITS_PE(pe) ? yr_le64toh(OptionalHeader(pe, SizeOfHeapCommit))
2299
6.89k
                       : yr_le32toh(OptionalHeader(pe, SizeOfHeapCommit)),
2300
6.89k
      pe->object,
2301
6.89k
      "size_of_heap_commit");
2302
2303
6.89k
  yr_set_integer(
2304
6.89k
      yr_le32toh(OptionalHeader(pe, LoaderFlags)), pe->object, "loader_flags");
2305
2306
6.89k
  data_dir = IS_64BITS_PE(pe) ? pe->header64->OptionalHeader.DataDirectory
2307
6.89k
                              : pe->header->OptionalHeader.DataDirectory;
2308
2309
6.89k
  ddcount = yr_le32toh(OptionalHeader(pe, NumberOfRvaAndSizes));
2310
6.89k
  ddcount = yr_min(ddcount, IMAGE_NUMBEROF_DIRECTORY_ENTRIES);
2311
2312
110k
  for (int i = 0; i < ddcount; i++)
2313
103k
  {
2314
103k
    if (!struct_fits_in_pe(pe, data_dir, IMAGE_DATA_DIRECTORY))
2315
0
      break;
2316
2317
103k
    yr_set_integer(
2318
103k
        yr_le32toh(data_dir->VirtualAddress),
2319
103k
        pe->object,
2320
103k
        "data_directories[%i].virtual_address",
2321
103k
        i);
2322
2323
103k
    yr_set_integer(
2324
103k
        yr_le32toh(data_dir->Size), pe->object, "data_directories[%i].size", i);
2325
2326
103k
    data_dir++;
2327
103k
  }
2328
2329
6.89k
  pe_iterate_resources(
2330
6.89k
      pe, (RESOURCE_CALLBACK_FUNC) pe_collect_resources, (void*) pe);
2331
2332
6.89k
  yr_set_integer(pe->resources, pe->object, "number_of_resources");
2333
6.89k
  yr_set_integer(pe->version_infos, pe->object, "number_of_version_infos");
2334
2335
6.89k
  section = IMAGE_FIRST_SECTION(pe->header);
2336
2337
6.89k
  scount = yr_min(
2338
6.89k
      yr_le16toh(pe->header->FileHeader.NumberOfSections), MAX_PE_SECTIONS);
2339
2340
18.3k
  for (int i = 0; i < scount; i++)
2341
11.8k
  {
2342
11.8k
    if (!struct_fits_in_pe(pe, section, IMAGE_SECTION_HEADER))
2343
337
      break;
2344
2345
11.4k
    memcpy(section_name, section->Name, IMAGE_SIZEOF_SHORT_NAME);
2346
11.4k
    section_name[IMAGE_SIZEOF_SHORT_NAME] = '\0';
2347
2348
    // Basically do rstrip('\0'), find the rightmost non-null character.
2349
    // Samples like
2350
    // 0043812838495a45449a0ac61a81b9c16eddca1ad249fb4f7fdb1c4505e9bb34 contain
2351
    // sections with additional characters after the first null.
2352
21.6k
    for (sect_name_length = IMAGE_SIZEOF_SHORT_NAME - 1; sect_name_length >= 0;
2353
11.4k
         --sect_name_length)
2354
21.1k
    {
2355
21.1k
      if (section_name[sect_name_length] != '\0')
2356
10.9k
        break;
2357
21.1k
    }
2358
2359
11.4k
    uint64_t sect_full_name_length = 0;
2360
11.4k
    const char* full_section_name = pe_get_section_full_name(
2361
11.4k
        pe, section_name, sect_name_length + 1, &sect_full_name_length);
2362
2363
11.4k
    yr_set_sized_string(
2364
11.4k
        (char*) section_name,
2365
11.4k
        sect_name_length + 1,
2366
11.4k
        pe->object,
2367
11.4k
        "sections[%i].name",
2368
11.4k
        i);
2369
2370
11.4k
    yr_set_sized_string(
2371
11.4k
        full_section_name,
2372
11.4k
        sect_full_name_length,
2373
11.4k
        pe->object,
2374
11.4k
        "sections[%i].full_name",
2375
11.4k
        i);
2376
2377
11.4k
    yr_set_integer(
2378
11.4k
        yr_le32toh(section->Characteristics),
2379
11.4k
        pe->object,
2380
11.4k
        "sections[%i].characteristics",
2381
11.4k
        i);
2382
2383
11.4k
    yr_set_integer(
2384
11.4k
        yr_le32toh(section->SizeOfRawData),
2385
11.4k
        pe->object,
2386
11.4k
        "sections[%i].raw_data_size",
2387
11.4k
        i);
2388
2389
11.4k
    yr_set_integer(
2390
11.4k
        yr_le32toh(section->PointerToRawData),
2391
11.4k
        pe->object,
2392
11.4k
        "sections[%i].raw_data_offset",
2393
11.4k
        i);
2394
2395
11.4k
    yr_set_integer(
2396
11.4k
        yr_le32toh(section->VirtualAddress),
2397
11.4k
        pe->object,
2398
11.4k
        "sections[%i].virtual_address",
2399
11.4k
        i);
2400
2401
11.4k
    yr_set_integer(
2402
11.4k
        yr_le32toh(section->Misc.VirtualSize),
2403
11.4k
        pe->object,
2404
11.4k
        "sections[%i].virtual_size",
2405
11.4k
        i);
2406
2407
11.4k
    yr_set_integer(
2408
11.4k
        yr_le32toh(section->PointerToRelocations),
2409
11.4k
        pe->object,
2410
11.4k
        "sections[%i].pointer_to_relocations",
2411
11.4k
        i);
2412
2413
11.4k
    yr_set_integer(
2414
11.4k
        yr_le32toh(section->PointerToLinenumbers),
2415
11.4k
        pe->object,
2416
11.4k
        "sections[%i].pointer_to_line_numbers",
2417
11.4k
        i);
2418
2419
11.4k
    yr_set_integer(
2420
11.4k
        yr_le32toh(section->NumberOfRelocations),
2421
11.4k
        pe->object,
2422
11.4k
        "sections[%i].number_of_relocations",
2423
11.4k
        i);
2424
2425
11.4k
    yr_set_integer(
2426
11.4k
        yr_le32toh(section->NumberOfLinenumbers),
2427
11.4k
        pe->object,
2428
11.4k
        "sections[%i].number_of_line_numbers",
2429
11.4k
        i);
2430
2431
    // This will catch the section with the highest raw offset to help checking
2432
    // if overlay data is present. If two sections have the same raw pointer
2433
    // but different raw sizes the largest one is used. An example of this case
2434
    // is file: cf62bf1815a93e68e6c5189f689286b66c4088b9507cf3ecf835e4ac3f9ededa
2435
2436
11.4k
    section_end = yr_le32toh(section->PointerToRawData) +
2437
11.4k
                  yr_le32toh(section->SizeOfRawData);
2438
2439
11.4k
    if (section_end > highest_sec_ofs + highest_sec_siz)
2440
2.96k
    {
2441
2.96k
      highest_sec_ofs = yr_le32toh(section->PointerToRawData);
2442
2.96k
      highest_sec_siz = yr_le32toh(section->SizeOfRawData);
2443
2.96k
    }
2444
2445
11.4k
    section++;
2446
11.4k
  }
2447
2448
  // An overlay is data appended to a PE file. Its location is at
2449
  // RawData + RawOffset of the last section on the physical file
2450
6.89k
  last_section_end = highest_sec_siz + highest_sec_ofs;
2451
2452
  // For PE files that have overlaid data overlay.offset contains the offset
2453
  // within the file where the overlay starts and overlay.size contains the
2454
  // size. If the PE file doesn't have an overlay both fields are 0, if the
2455
  // file is not a PE file (or is a malformed PE) both fields are YR_UNDEFINED.
2456
6.89k
  if (last_section_end && (pe->data_size > last_section_end))
2457
92
  {
2458
92
    yr_set_integer(last_section_end, pe->object, "overlay.offset");
2459
92
    yr_set_integer(
2460
92
        pe->data_size - last_section_end, pe->object, "overlay.size");
2461
92
  }
2462
6.80k
  else
2463
6.80k
  {
2464
6.80k
    yr_set_integer(0, pe->object, "overlay.offset");
2465
6.80k
    yr_set_integer(0, pe->object, "overlay.size");
2466
6.80k
  }
2467
6.89k
}
2468
2469
//
2470
// Given a posix timestamp argument, make sure not_before <= arg <= not_after
2471
//
2472
2473
define_function(valid_on)
2474
0
{
2475
0
  int64_t timestamp;
2476
0
  int64_t not_before;
2477
0
  int64_t not_after;
2478
2479
0
  if (yr_is_undefined(yr_parent(), "not_before") ||
2480
0
      yr_is_undefined(yr_parent(), "not_after"))
2481
0
  {
2482
0
    return_integer(YR_UNDEFINED);
2483
0
  }
2484
2485
0
  timestamp = integer_argument(1);
2486
2487
0
  not_before = yr_get_integer(yr_parent(), "not_before");
2488
0
  not_after = yr_get_integer(yr_parent(), "not_after");
2489
2490
0
  return_integer(timestamp >= not_before && timestamp <= not_after);
2491
0
}
2492
2493
define_function(section_index_addr)
2494
0
{
2495
0
  YR_OBJECT* module = yr_module();
2496
0
  YR_SCAN_CONTEXT* context = yr_scan_context();
2497
2498
0
  int64_t offset;
2499
0
  int64_t size;
2500
2501
0
  int64_t addr = integer_argument(1);
2502
0
  int64_t n = yr_get_integer(module, "number_of_sections");
2503
2504
0
  if (yr_is_undefined(module, "number_of_sections"))
2505
0
    return_integer(YR_UNDEFINED);
2506
2507
0
  for (int i = 0; i < yr_min(n, MAX_PE_SECTIONS); i++)
2508
0
  {
2509
0
    if (context->flags & SCAN_FLAGS_PROCESS_MEMORY)
2510
0
    {
2511
0
      offset = yr_get_integer(module, "sections[%i].virtual_address", i);
2512
0
      size = yr_get_integer(module, "sections[%i].virtual_size", i);
2513
0
    }
2514
0
    else
2515
0
    {
2516
0
      offset = yr_get_integer(module, "sections[%i].raw_data_offset", i);
2517
0
      size = yr_get_integer(module, "sections[%i].raw_data_size", i);
2518
0
    }
2519
2520
0
    if (addr >= offset && addr < offset + size)
2521
0
      return_integer(i);
2522
0
  }
2523
2524
0
  return_integer(YR_UNDEFINED);
2525
0
}
2526
2527
define_function(section_index_name)
2528
0
{
2529
0
  YR_OBJECT* module = yr_module();
2530
2531
0
  char* name = string_argument(1);
2532
2533
0
  int64_t n = yr_get_integer(module, "number_of_sections");
2534
2535
0
  if (yr_is_undefined(module, "number_of_sections"))
2536
0
    return_integer(YR_UNDEFINED);
2537
2538
0
  for (int i = 0; i < yr_min(n, MAX_PE_SECTIONS); i++)
2539
0
  {
2540
0
    SIZED_STRING* sect = yr_get_string(module, "sections[%i].name", i);
2541
2542
0
    if (sect != NULL && strcmp(name, sect->c_string) == 0)
2543
0
      return_integer(i);
2544
0
  }
2545
2546
0
  return_integer(YR_UNDEFINED);
2547
0
}
2548
2549
define_function(exports)
2550
0
{
2551
0
  SIZED_STRING* search_name = sized_string_argument(1);
2552
2553
0
  SIZED_STRING* function_name = NULL;
2554
0
  YR_OBJECT* module = yr_module();
2555
0
  PE* pe = (PE*) module->data;
2556
2557
  // If not a PE, return YR_UNDEFINED.
2558
0
  if (pe == NULL)
2559
0
    return_integer(YR_UNDEFINED);
2560
2561
  // If PE, but no exported functions, return false.
2562
0
  int n = (int) yr_get_integer(module, "number_of_exports");
2563
2564
0
  if (n == 0)
2565
0
    return_integer(0);
2566
2567
0
  for (int i = 0; i < n; i++)
2568
0
  {
2569
0
    function_name = yr_get_string(module, "export_details[%i].name", i);
2570
2571
0
    if (function_name == NULL)
2572
0
      continue;
2573
2574
0
    if (ss_icompare(function_name, search_name) == 0)
2575
0
      return_integer(1);
2576
0
  }
2577
2578
0
  return_integer(0);
2579
0
}
2580
2581
define_function(exports_regexp)
2582
0
{
2583
0
  RE* regex = regexp_argument(1);
2584
2585
0
  SIZED_STRING* function_name = NULL;
2586
0
  YR_OBJECT* module = yr_module();
2587
0
  PE* pe = (PE*) module->data;
2588
2589
  // If not a PE, return YR_UNDEFINED.
2590
0
  if (pe == NULL)
2591
0
    return_integer(YR_UNDEFINED);
2592
2593
  // If PE, but no exported functions, return false.
2594
0
  int n = (int) yr_get_integer(module, "number_of_exports");
2595
2596
0
  if (n == 0)
2597
0
    return_integer(0);
2598
2599
0
  for (int i = 0; i < n; i++)
2600
0
  {
2601
0
    function_name = yr_get_string(module, "export_details[%i].name", i);
2602
0
    if (function_name == NULL)
2603
0
      continue;
2604
2605
0
    if (yr_re_match(yr_scan_context(), regex, function_name->c_string) != -1)
2606
0
      return_integer(1);
2607
0
  }
2608
2609
0
  return_integer(0);
2610
0
}
2611
2612
define_function(exports_ordinal)
2613
0
{
2614
0
  int64_t ordinal = integer_argument(1);
2615
2616
0
  YR_OBJECT* module = yr_module();
2617
0
  PE* pe = (PE*) module->data;
2618
2619
  // If not a PE, return YR_UNDEFINED.
2620
0
  if (pe == NULL)
2621
0
    return_integer(YR_UNDEFINED);
2622
2623
  // If PE, but no exported functions, return false.
2624
0
  int n = (int) yr_get_integer(module, "number_of_exports");
2625
2626
0
  if (n == 0)
2627
0
    return_integer(0);
2628
2629
0
  if (ordinal == 0 || ordinal > n)
2630
0
    return_integer(0);
2631
2632
0
  for (int i = 0; i < n; i++)
2633
0
  {
2634
0
    int64_t exported_ordinal = yr_object_get_integer(
2635
0
        module, "export_details[%i].ordinal", i);
2636
2637
0
    if (exported_ordinal == ordinal)
2638
0
      return_integer(1);
2639
0
  }
2640
2641
0
  return_integer(0);
2642
0
}
2643
2644
define_function(exports_index_name)
2645
0
{
2646
0
  SIZED_STRING* search_name = sized_string_argument(1);
2647
2648
0
  SIZED_STRING* function_name = NULL;
2649
0
  YR_OBJECT* module = yr_module();
2650
0
  PE* pe = (PE*) module->data;
2651
2652
  // If not a PE, return YR_UNDEFINED.
2653
0
  if (pe == NULL)
2654
0
    return_integer(YR_UNDEFINED);
2655
2656
  // If PE, but no exported functions, return false.
2657
0
  int n = (int) yr_get_integer(module, "number_of_exports");
2658
2659
0
  if (n == 0)
2660
0
    return_integer(YR_UNDEFINED);
2661
2662
0
  for (int i = 0; i < n; i++)
2663
0
  {
2664
0
    function_name = yr_get_string(module, "export_details[%i].name", i);
2665
2666
0
    if (function_name == NULL)
2667
0
      continue;
2668
2669
0
    if (ss_icompare(function_name, search_name) == 0)
2670
0
      return_integer(i);
2671
0
  }
2672
2673
0
  return_integer(YR_UNDEFINED);
2674
0
}
2675
2676
define_function(exports_index_ordinal)
2677
0
{
2678
0
  int64_t ordinal = integer_argument(1);
2679
2680
0
  YR_OBJECT* module = yr_module();
2681
0
  PE* pe = (PE*) module->data;
2682
2683
  // If not a PE, return YR_UNDEFINED.
2684
0
  if (pe == NULL)
2685
0
    return_integer(YR_UNDEFINED);
2686
2687
  // If PE, but no exported functions, return false.
2688
0
  int n = (int) yr_get_integer(module, "number_of_exports");
2689
2690
0
  if (n == 0)
2691
0
    return_integer(YR_UNDEFINED);
2692
2693
0
  if (ordinal == 0 || ordinal > n)
2694
0
    return_integer(YR_UNDEFINED);
2695
2696
0
  for (int i = 0; i < n; i++)
2697
0
  {
2698
0
    int64_t exported_ordinal = yr_object_get_integer(
2699
0
        module, "export_details[%i].ordinal", i);
2700
2701
0
    if (exported_ordinal == ordinal)
2702
0
      return_integer(i);
2703
0
  }
2704
2705
0
  return_integer(YR_UNDEFINED);
2706
0
}
2707
2708
define_function(exports_index_regex)
2709
0
{
2710
0
  RE* regex = regexp_argument(1);
2711
2712
0
  SIZED_STRING* function_name = NULL;
2713
0
  YR_OBJECT* module = yr_module();
2714
0
  PE* pe = (PE*) module->data;
2715
2716
  // If not a PE, return YR_UNDEFINED.
2717
0
  if (pe == NULL)
2718
0
    return_integer(YR_UNDEFINED);
2719
2720
  // If PE, but no exported functions, return false.
2721
0
  int n = (int) yr_get_integer(module, "number_of_exports");
2722
2723
0
  if (n == 0)
2724
0
    return_integer(YR_UNDEFINED);
2725
2726
0
  for (int i = 0; i < n; i++)
2727
0
  {
2728
0
    function_name = yr_get_string(module, "export_details[%i].name", i);
2729
0
    if (function_name == NULL)
2730
0
      continue;
2731
2732
0
    if (yr_re_match(yr_scan_context(), regex, function_name->c_string) != -1)
2733
0
    {
2734
0
      return_integer(i);
2735
0
    }
2736
0
  }
2737
2738
0
  return_integer(YR_UNDEFINED);
2739
0
}
2740
2741
#if defined(HAVE_LIBCRYPTO) || defined(HAVE_WINCRYPT_H) || \
2742
    defined(HAVE_COMMONCRYPTO_COMMONCRYPTO_H)
2743
2744
//
2745
// Generate an import hash:
2746
// https://www.mandiant.com/blog/tracking-malware-import-hashing/
2747
// It is important to make duplicates of the strings as we don't want
2748
// to alter the contents of the parsed import structures.
2749
//
2750
2751
define_function(imphash)
2752
{
2753
  YR_OBJECT* module = yr_module();
2754
2755
  IMPORTED_DLL* dll;
2756
  yr_md5_ctx ctx;
2757
2758
  unsigned char digest[YR_MD5_LEN];
2759
  char* digest_ascii;
2760
2761
  size_t i;
2762
  bool first = true;
2763
2764
  PE* pe = (PE*) module->data;
2765
2766
  // If not a PE, return YR_UNDEFINED.
2767
2768
  if (!pe)
2769
    return_string(YR_UNDEFINED);
2770
2771
  // Lookup in cache first.
2772
  digest_ascii = (char*) yr_hash_table_lookup(pe->hash_table, "imphash", NULL);
2773
2774
  if (digest_ascii != NULL)
2775
    return_string(digest_ascii);
2776
2777
  if (!yr_md5_init(&ctx))
2778
    return_string(YR_UNDEFINED);
2779
2780
  dll = pe->imported_dlls;
2781
2782
  while (dll)
2783
  {
2784
    IMPORT_FUNCTION* func;
2785
2786
    size_t dll_name_len;
2787
    char* dll_name;
2788
2789
    // If extension is 'ocx', 'sys' or 'dll', chop it.
2790
2791
    char* ext = strrchr(dll->name, '.');
2792
2793
    if (ext &&
2794
        (strncasecmp(ext, ".ocx", 4) == 0 || strncasecmp(ext, ".sys", 4) == 0 ||
2795
         strncasecmp(ext, ".dll", 4) == 0))
2796
    {
2797
      dll_name_len = (ext - dll->name);
2798
    }
2799
    else
2800
    {
2801
      dll_name_len = strlen(dll->name);
2802
    }
2803
2804
    // Allocate a new string to hold the dll name.
2805
2806
    dll_name = (char*) yr_malloc(dll_name_len + 1);
2807
2808
    if (!dll_name)
2809
      return ERROR_INSUFFICIENT_MEMORY;
2810
2811
    strlcpy(dll_name, dll->name, dll_name_len + 1);
2812
2813
    func = dll->functions;
2814
2815
    while (func)
2816
    {
2817
      char* final_name;
2818
      size_t final_name_len = dll_name_len + strlen(func->name) + 1;
2819
2820
      if (!first)
2821
        final_name_len++;  // Additional byte to accommodate the extra comma
2822
2823
      final_name = (char*) yr_malloc(final_name_len + 1);
2824
2825
      if (final_name == NULL)
2826
        break;
2827
2828
      sprintf(final_name, first ? "%s.%s" : ",%s.%s", dll_name, func->name);
2829
2830
      // Lowercase the whole thing.
2831
2832
      for (i = 0; i < final_name_len; i++)
2833
        final_name[i] = tolower((unsigned char) final_name[i]);
2834
2835
      yr_md5_update(&ctx, final_name, final_name_len);
2836
2837
      yr_free(final_name);
2838
2839
      func = func->next;
2840
      first = false;
2841
    }
2842
2843
    yr_free(dll_name);
2844
2845
    dll = dll->next;
2846
  }
2847
2848
  yr_md5_final(digest, &ctx);
2849
2850
  digest_ascii = (char*) yr_malloc(YR_MD5_LEN * 2 + 1);
2851
2852
  if (digest_ascii == NULL)
2853
    return ERROR_INSUFFICIENT_MEMORY;
2854
2855
  // Transform the binary digest to ascii
2856
2857
  for (i = 0; i < YR_MD5_LEN; i++)
2858
  {
2859
    sprintf(digest_ascii + (i * 2), "%02x", digest[i]);
2860
  }
2861
2862
  digest_ascii[YR_MD5_LEN * 2] = '\0';
2863
2864
  yr_hash_table_add(pe->hash_table, "imphash", NULL, digest_ascii);
2865
2866
  return_string(digest_ascii);
2867
}
2868
2869
#endif  // defined(HAVE_LIBCRYPTO) || defined(HAVE_WINCRYPT_H)
2870
2871
int64_t pe_imports_dll(IMPORTED_DLL* dll, char* dll_name)
2872
0
{
2873
0
  if (dll == NULL)
2874
0
    return 0;
2875
2876
0
  int64_t result = 0;
2877
2878
0
  for (; dll != NULL; dll = dll->next)
2879
0
  {
2880
0
    if (strcasecmp(dll->name, dll_name) == 0)
2881
0
    {
2882
0
      IMPORT_FUNCTION* fun = dll->functions;
2883
0
      for (; fun != NULL; fun = fun->next)
2884
0
      {
2885
0
        result++;
2886
0
      }
2887
0
    }
2888
0
  }
2889
2890
0
  return result;
2891
0
}
2892
2893
int64_t pe_imports(IMPORTED_DLL* dll, char* dll_name, char* fun_name)
2894
0
{
2895
0
  if (dll == NULL)
2896
0
    return 0;
2897
2898
0
  for (; dll != NULL; dll = dll->next)
2899
0
  {
2900
0
    if (strcasecmp(dll->name, dll_name) == 0)
2901
0
    {
2902
0
      IMPORT_FUNCTION* fun = dll->functions;
2903
0
      for (; fun != NULL; fun = fun->next)
2904
0
      {
2905
0
        if (strcasecmp(fun->name, fun_name) == 0)
2906
0
          return 1;
2907
0
      }
2908
0
    }
2909
0
  }
2910
2911
0
  return 0;
2912
0
}
2913
2914
int64_t pe_imports_regexp(
2915
    YR_SCAN_CONTEXT* context,
2916
    IMPORTED_DLL* dll,
2917
    RE* dll_name,
2918
    RE* fun_name)
2919
0
{
2920
0
  if (dll == NULL)
2921
0
    return 0;
2922
2923
0
  int64_t result = 0;
2924
2925
0
  for (; dll != NULL; dll = dll->next)
2926
0
  {
2927
0
    if (yr_re_match(context, dll_name, dll->name) > 0)
2928
0
    {
2929
0
      IMPORT_FUNCTION* fun = dll->functions;
2930
0
      for (; fun != NULL; fun = fun->next)
2931
0
      {
2932
0
        if (yr_re_match(context, fun_name, fun->name) > 0)
2933
0
          result++;
2934
0
      }
2935
0
    }
2936
0
  }
2937
2938
0
  return result;
2939
0
}
2940
2941
int64_t pe_imports_ordinal(IMPORTED_DLL* dll, char* dll_name, uint64_t ordinal)
2942
0
{
2943
0
  if (dll == NULL)
2944
0
    return 0;
2945
2946
0
  for (; dll != NULL; dll = dll->next)
2947
0
  {
2948
0
    if (strcasecmp(dll->name, dll_name) == 0)
2949
0
    {
2950
0
      IMPORT_FUNCTION* fun = dll->functions;
2951
0
      for (; fun != NULL; fun = fun->next)
2952
0
      {
2953
0
        if (fun->has_ordinal && fun->ordinal == ordinal)
2954
0
          return 1;
2955
0
      }
2956
0
    }
2957
0
  }
2958
2959
0
  return 0;
2960
0
}
2961
2962
define_function(imports_standard)
2963
0
{
2964
0
  char* dll_name = string_argument(1);
2965
0
  char* function_name = string_argument(2);
2966
2967
0
  YR_OBJECT* module = yr_module();
2968
0
  PE* pe = (PE*) module->data;
2969
2970
0
  if (!pe)
2971
0
    return_integer(YR_UNDEFINED);
2972
2973
0
  return_integer(pe_imports(pe->imported_dlls, dll_name, function_name));
2974
0
}
2975
2976
define_function(imports)
2977
0
{
2978
0
  int64_t flags = integer_argument(1);
2979
0
  char* dll_name = string_argument(2);
2980
0
  char* function_name = string_argument(3);
2981
2982
0
  YR_OBJECT* module = yr_module();
2983
0
  PE* pe = (PE*) module->data;
2984
2985
0
  if (!pe)
2986
0
    return_integer(YR_UNDEFINED);
2987
2988
0
  if (flags & IMPORT_STANDARD &&
2989
0
      pe_imports(pe->imported_dlls, dll_name, function_name))
2990
0
  {
2991
0
    return_integer(1);
2992
0
  }
2993
2994
0
  if (flags & IMPORT_DELAYED &&
2995
0
      pe_imports(pe->delay_imported_dlls, dll_name, function_name))
2996
0
  {
2997
0
    return_integer(1);
2998
0
  }
2999
3000
0
  return_integer(0);
3001
0
}
3002
3003
define_function(imports_standard_ordinal)
3004
0
{
3005
0
  char* dll_name = string_argument(1);
3006
0
  int64_t ordinal = integer_argument(2);
3007
3008
0
  YR_OBJECT* module = yr_module();
3009
0
  PE* pe = (PE*) module->data;
3010
3011
0
  if (!pe)
3012
0
    return_integer(YR_UNDEFINED);
3013
3014
0
  return_integer(pe_imports_ordinal(pe->imported_dlls, dll_name, ordinal))
3015
0
}
3016
3017
define_function(imports_ordinal)
3018
0
{
3019
0
  int64_t flags = integer_argument(1);
3020
0
  char* dll_name = string_argument(2);
3021
0
  int64_t ordinal = integer_argument(3);
3022
3023
0
  YR_OBJECT* module = yr_module();
3024
0
  PE* pe = (PE*) module->data;
3025
3026
0
  if (!pe)
3027
0
    return_integer(YR_UNDEFINED);
3028
3029
0
  if (flags & IMPORT_STANDARD &&
3030
0
      pe_imports_ordinal(pe->imported_dlls, dll_name, ordinal))
3031
0
  {
3032
0
    return_integer(1);
3033
0
  }
3034
3035
0
  if (flags & IMPORT_DELAYED &&
3036
0
      pe_imports_ordinal(pe->delay_imported_dlls, dll_name, ordinal))
3037
0
  {
3038
0
    return_integer(1);
3039
0
  }
3040
3041
0
  return_integer(0);
3042
0
}
3043
3044
define_function(imports_standard_regex)
3045
0
{
3046
0
  RE* dll_name = regexp_argument(1);
3047
0
  RE* function_name = regexp_argument(2);
3048
3049
0
  YR_OBJECT* module = yr_module();
3050
0
  PE* pe = (PE*) module->data;
3051
3052
0
  if (!pe)
3053
0
    return_integer(YR_UNDEFINED);
3054
3055
0
  return_integer(pe_imports_regexp(
3056
0
      yr_scan_context(), pe->imported_dlls, dll_name, function_name))
3057
0
}
3058
3059
define_function(imports_regex)
3060
0
{
3061
0
  int64_t flags = integer_argument(1);
3062
0
  RE* dll_name = regexp_argument(2);
3063
0
  RE* function_name = regexp_argument(3);
3064
3065
0
  YR_OBJECT* module = yr_module();
3066
0
  PE* pe = (PE*) module->data;
3067
3068
0
  if (!pe)
3069
0
    return_integer(YR_UNDEFINED);
3070
3071
0
  int64_t result = 0;
3072
3073
0
  if (flags & IMPORT_STANDARD)
3074
0
    result += pe_imports_regexp(
3075
0
        yr_scan_context(), pe->imported_dlls, dll_name, function_name);
3076
3077
0
  if (flags & IMPORT_DELAYED)
3078
0
    result += pe_imports_regexp(
3079
0
        yr_scan_context(), pe->delay_imported_dlls, dll_name, function_name);
3080
3081
0
  return_integer(result);
3082
0
}
3083
3084
define_function(imports_standard_dll)
3085
0
{
3086
0
  char* dll_name = string_argument(1);
3087
3088
0
  YR_OBJECT* module = yr_module();
3089
0
  PE* pe = (PE*) module->data;
3090
3091
0
  if (!pe)
3092
0
    return_integer(YR_UNDEFINED);
3093
3094
0
  return_integer(pe_imports_dll(pe->imported_dlls, dll_name));
3095
0
}
3096
3097
define_function(imports_dll)
3098
0
{
3099
0
  int64_t flags = integer_argument(1);
3100
0
  char* dll_name = string_argument(2);
3101
3102
0
  YR_OBJECT* module = yr_module();
3103
0
  PE* pe = (PE*) module->data;
3104
3105
0
  if (!pe)
3106
0
    return_integer(YR_UNDEFINED);
3107
3108
0
  int64_t result = 0;
3109
3110
0
  if (flags & IMPORT_STANDARD)
3111
0
    result += pe_imports_dll(pe->imported_dlls, dll_name);
3112
3113
0
  if (flags & IMPORT_DELAYED)
3114
0
    result += pe_imports_dll(pe->delay_imported_dlls, dll_name);
3115
3116
0
  return_integer(result);
3117
0
}
3118
3119
define_function(import_rva)
3120
0
{
3121
0
  SIZED_STRING* in_dll_name = sized_string_argument(1);
3122
0
  SIZED_STRING* in_function_name = sized_string_argument(2);
3123
3124
0
  SIZED_STRING* dll_name;
3125
0
  SIZED_STRING* function_name;
3126
0
  YR_OBJECT* module = yr_module();
3127
0
  PE* pe = (PE*) module->data;
3128
3129
0
  if (!pe)
3130
0
    return_integer(YR_UNDEFINED);
3131
3132
0
  int64_t num_imports = yr_get_integer(pe->object, "number_of_imports");
3133
0
  if (IS_UNDEFINED(num_imports))
3134
0
    return_integer(YR_UNDEFINED);
3135
3136
0
  for (int i = 0; i < num_imports; i++)
3137
0
  {
3138
0
    dll_name = yr_get_string(module, "import_details[%i].library_name", i);
3139
0
    if (dll_name == NULL || IS_UNDEFINED(dll_name) ||
3140
0
        ss_icompare(in_dll_name, dll_name) != 0)
3141
0
      continue;
3142
3143
0
    int64_t num_functions = yr_get_integer(
3144
0
        module, "import_details[%i].number_of_functions", i);
3145
0
    if (IS_UNDEFINED(num_functions))
3146
0
      return_integer(YR_UNDEFINED);
3147
3148
0
    for (int j = 0; j < num_functions; j++)
3149
0
    {
3150
0
      function_name = yr_get_string(
3151
0
          module, "import_details[%i].functions[%i].name", i, j);
3152
0
      if (function_name == NULL || IS_UNDEFINED(function_name))
3153
0
        continue;
3154
3155
0
      if (ss_icompare(in_function_name, function_name) == 0)
3156
0
        return_integer(yr_get_integer(
3157
0
            module, "import_details[%i].functions[%i].rva", i, j));
3158
0
    }
3159
0
  }
3160
3161
0
  return_integer(YR_UNDEFINED);
3162
0
}
3163
3164
define_function(import_rva_ordinal)
3165
0
{
3166
0
  SIZED_STRING* in_dll_name = sized_string_argument(1);
3167
0
  int64_t in_ordinal = integer_argument(2);
3168
3169
0
  SIZED_STRING* dll_name;
3170
0
  int64_t ordinal;
3171
0
  YR_OBJECT* module = yr_module();
3172
0
  PE* pe = (PE*) module->data;
3173
3174
0
  if (!pe)
3175
0
    return_integer(YR_UNDEFINED);
3176
3177
0
  int64_t num_imports = yr_get_integer(pe->object, "number_of_imports");
3178
0
  if (IS_UNDEFINED(num_imports))
3179
0
    return_integer(YR_UNDEFINED);
3180
3181
0
  for (int i = 0; i < num_imports; i++)
3182
0
  {
3183
0
    dll_name = yr_get_string(module, "import_details[%i].library_name", i);
3184
0
    if (dll_name == NULL || IS_UNDEFINED(dll_name) ||
3185
0
        ss_icompare(in_dll_name, dll_name) != 0)
3186
0
      continue;
3187
3188
0
    int64_t num_functions = yr_get_integer(
3189
0
        module, "import_details[%i].number_of_functions", i);
3190
0
    if (IS_UNDEFINED(num_functions))
3191
0
      return_integer(YR_UNDEFINED);
3192
3193
0
    for (int j = 0; j < num_functions; j++)
3194
0
    {
3195
0
      ordinal = yr_get_integer(
3196
0
          module, "import_details[%i].functions[%i].ordinal", i, j);
3197
0
      if (IS_UNDEFINED(ordinal))
3198
0
        continue;
3199
3200
0
      if (ordinal == in_ordinal)
3201
0
        return_integer(yr_get_integer(
3202
0
            module, "import_details[%i].functions[%i].rva", i, j));
3203
0
    }
3204
0
  }
3205
3206
0
  return_integer(YR_UNDEFINED);
3207
0
}
3208
3209
define_function(delayed_import_rva)
3210
0
{
3211
0
  SIZED_STRING* in_dll_name = sized_string_argument(1);
3212
0
  SIZED_STRING* in_function_name = sized_string_argument(2);
3213
3214
0
  SIZED_STRING* dll_name;
3215
0
  SIZED_STRING* function_name;
3216
0
  YR_OBJECT* module = yr_module();
3217
0
  PE* pe = (PE*) module->data;
3218
3219
0
  if (!pe)
3220
0
    return_integer(YR_UNDEFINED);
3221
3222
0
  int64_t num_imports = yr_get_integer(pe->object, "number_of_delayed_imports");
3223
3224
0
  if (IS_UNDEFINED(num_imports))
3225
0
    return_integer(YR_UNDEFINED);
3226
3227
0
  for (int i = 0; i < num_imports; i++)
3228
0
  {
3229
0
    dll_name = yr_get_string(
3230
0
        module, "delayed_import_details[%i].library_name", i);
3231
3232
0
    if (dll_name == NULL || IS_UNDEFINED(dll_name) ||
3233
0
        ss_icompare(in_dll_name, dll_name) != 0)
3234
0
      continue;
3235
3236
0
    int64_t num_functions = yr_get_integer(
3237
0
        module, "delayed_import_details[%i].number_of_functions", i);
3238
3239
0
    if (IS_UNDEFINED(num_functions))
3240
0
      return_integer(YR_UNDEFINED);
3241
3242
0
    for (int j = 0; j < num_functions; j++)
3243
0
    {
3244
0
      function_name = yr_get_string(
3245
0
          module, "delayed_import_details[%i].functions[%i].name", i, j);
3246
3247
0
      if (function_name == NULL || IS_UNDEFINED(function_name))
3248
0
        continue;
3249
3250
0
      if (ss_icompare(in_function_name, function_name) == 0)
3251
0
        return_integer(yr_get_integer(
3252
0
            module, "delayed_import_details[%i].functions[%i].rva", i, j));
3253
0
    }
3254
0
  }
3255
3256
0
  return_integer(YR_UNDEFINED);
3257
0
}
3258
3259
define_function(delayed_import_rva_ordinal)
3260
0
{
3261
0
  SIZED_STRING* in_dll_name = sized_string_argument(1);
3262
0
  int64_t in_ordinal = integer_argument(2);
3263
3264
0
  SIZED_STRING* dll_name;
3265
0
  int64_t ordinal;
3266
0
  YR_OBJECT* module = yr_module();
3267
0
  PE* pe = (PE*) module->data;
3268
3269
0
  if (!pe)
3270
0
    return_integer(YR_UNDEFINED);
3271
3272
0
  int64_t num_imports = yr_get_integer(pe->object, "number_of_delayed_imports");
3273
0
  if (IS_UNDEFINED(num_imports))
3274
0
    return_integer(YR_UNDEFINED);
3275
3276
0
  for (int i = 0; i < num_imports; i++)
3277
0
  {
3278
0
    dll_name = yr_get_string(
3279
0
        module, "delayed_import_details[%i].library_name", i);
3280
3281
0
    if (dll_name == NULL || IS_UNDEFINED(dll_name) ||
3282
0
        ss_icompare(in_dll_name, dll_name) != 0)
3283
0
      continue;
3284
3285
0
    int64_t num_functions = yr_get_integer(
3286
0
        module, "delayed_import_details[%i].number_of_functions", i);
3287
3288
0
    if (IS_UNDEFINED(num_functions))
3289
0
      return_integer(YR_UNDEFINED);
3290
3291
0
    for (int j = 0; j < num_functions; j++)
3292
0
    {
3293
0
      ordinal = yr_get_integer(
3294
0
          module, "delayed_import_details[%i].functions[%i].ordinal", i, j);
3295
3296
0
      if (IS_UNDEFINED(ordinal))
3297
0
        continue;
3298
3299
0
      if (ordinal == in_ordinal)
3300
0
        return_integer(yr_get_integer(
3301
0
            module, "delayed_import_details[%i].functions[%i].rva", i, j));
3302
0
    }
3303
0
  }
3304
3305
0
  return_integer(YR_UNDEFINED);
3306
0
}
3307
3308
define_function(locale)
3309
0
{
3310
0
  YR_OBJECT* module = yr_module();
3311
0
  PE* pe = (PE*) module->data;
3312
3313
0
  uint64_t locale = integer_argument(1);
3314
3315
0
  if (yr_is_undefined(module, "number_of_resources"))
3316
0
    return_integer(YR_UNDEFINED);
3317
3318
  // If not a PE file, return YR_UNDEFINED
3319
3320
0
  if (pe == NULL)
3321
0
    return_integer(YR_UNDEFINED);
3322
3323
0
  int n = (int) yr_get_integer(module, "number_of_resources");
3324
3325
0
  for (int i = 0; i < n; i++)
3326
0
  {
3327
0
    uint64_t rsrc_language = yr_get_integer(
3328
0
        module, "resources[%i].language", i);
3329
3330
0
    if ((rsrc_language & 0xFFFF) == locale)
3331
0
      return_integer(1);
3332
0
  }
3333
3334
0
  return_integer(0);
3335
0
}
3336
3337
define_function(language)
3338
0
{
3339
0
  YR_OBJECT* module = yr_module();
3340
0
  PE* pe = (PE*) module->data;
3341
3342
0
  uint64_t language = integer_argument(1);
3343
3344
0
  if (yr_is_undefined(module, "number_of_resources"))
3345
0
    return_integer(YR_UNDEFINED);
3346
3347
  // If not a PE file, return YR_UNDEFINED
3348
3349
0
  if (pe == NULL)
3350
0
    return_integer(YR_UNDEFINED);
3351
3352
0
  int n = (int) yr_get_integer(module, "number_of_resources");
3353
3354
0
  for (int i = 0; i < n; i++)
3355
0
  {
3356
0
    uint64_t rsrc_language = yr_get_integer(
3357
0
        module, "resources[%i].language", i);
3358
3359
0
    if ((rsrc_language & 0xFF) == language)
3360
0
      return_integer(1);
3361
0
  }
3362
3363
0
  return_integer(0);
3364
0
}
3365
3366
define_function(is_dll)
3367
0
{
3368
0
  int64_t characteristics;
3369
0
  YR_OBJECT* module = yr_module();
3370
3371
0
  if (yr_is_undefined(module, "characteristics"))
3372
0
    return_integer(YR_UNDEFINED);
3373
3374
0
  characteristics = yr_get_integer(module, "characteristics");
3375
0
  return_integer(characteristics & IMAGE_FILE_DLL);
3376
0
}
3377
3378
define_function(is_32bit)
3379
0
{
3380
0
  YR_OBJECT* module = yr_module();
3381
3382
0
  if (yr_is_undefined(module, "opthdr_magic"))
3383
0
    return_integer(YR_UNDEFINED);
3384
3385
0
  return_integer(
3386
0
      yr_get_integer(module, "opthdr_magic") == IMAGE_NT_OPTIONAL_HDR64_MAGIC
3387
0
          ? 0
3388
0
          : 1);
3389
0
}
3390
3391
define_function(is_64bit)
3392
0
{
3393
0
  YR_OBJECT* module = yr_module();
3394
3395
0
  if (yr_is_undefined(module, "opthdr_magic"))
3396
0
    return_integer(YR_UNDEFINED);
3397
3398
0
  return_integer(
3399
0
      yr_get_integer(module, "opthdr_magic") == IMAGE_NT_OPTIONAL_HDR64_MAGIC
3400
0
          ? 1
3401
0
          : 0);
3402
0
}
3403
3404
// _rich_version
3405
//
3406
// Returns the number of rich signatures that match the specified version and
3407
// toolid numbers.
3408
//
3409
static int64_t _rich_version(
3410
    YR_OBJECT* module,
3411
    uint64_t version,
3412
    uint64_t toolid)
3413
0
{
3414
0
  int64_t rich_length;
3415
0
  int64_t rich_count;
3416
3417
0
  PRICH_SIGNATURE clear_rich_signature;
3418
0
  SIZED_STRING* rich_string;
3419
3420
0
  int64_t result = 0;
3421
3422
  // Check if the required fields are set
3423
0
  if (yr_is_undefined(module, "rich_signature.length"))
3424
0
    return YR_UNDEFINED;
3425
3426
0
  rich_length = yr_get_integer(module, "rich_signature.length");
3427
0
  rich_string = yr_get_string(module, "rich_signature.clear_data");
3428
3429
  // If clear_data was not set, return YR_UNDEFINED
3430
0
  if (rich_string == NULL)
3431
0
    return YR_UNDEFINED;
3432
3433
  // File e77b007c9a964411c5e33afeec18be32c86963b78f3c3e906b28fcf1382f46c3
3434
  // has a Rich header of length 8, which is smaller than RICH_SIGNATURE and
3435
  // causes a crash.
3436
0
  if (rich_length < sizeof(RICH_SIGNATURE))
3437
0
    return YR_UNDEFINED;
3438
3439
0
  if (version == YR_UNDEFINED && toolid == YR_UNDEFINED)
3440
0
    return 0;
3441
3442
0
  clear_rich_signature = (PRICH_SIGNATURE) rich_string->c_string;
3443
3444
  // Loop over the versions in the rich signature
3445
0
  rich_count = (rich_length - sizeof(RICH_SIGNATURE)) /
3446
0
               sizeof(RICH_VERSION_INFO);
3447
3448
0
  for (int i = 0; i < rich_count; i++)
3449
0
  {
3450
0
    DWORD id_version = yr_le32toh(clear_rich_signature->versions[i].id_version);
3451
3452
0
    int match_version = (version == RICH_VERSION_VERSION(id_version));
3453
0
    int match_toolid = (toolid == RICH_VERSION_ID(id_version));
3454
3455
0
    if ((version == YR_UNDEFINED || match_version) &&
3456
0
        (toolid == YR_UNDEFINED || match_toolid))
3457
0
    {
3458
0
      result += yr_le32toh(clear_rich_signature->versions[i].times);
3459
0
    }
3460
0
  }
3461
3462
0
  return result;
3463
0
}
3464
3465
define_function(rich_version)
3466
0
{
3467
0
  return_integer(_rich_version(yr_module(), integer_argument(1), YR_UNDEFINED));
3468
0
}
3469
3470
define_function(rich_version_toolid)
3471
0
{
3472
0
  return_integer(
3473
0
      _rich_version(yr_module(), integer_argument(1), integer_argument(2)));
3474
0
}
3475
3476
define_function(rich_toolid)
3477
0
{
3478
0
  return_integer(_rich_version(yr_module(), YR_UNDEFINED, integer_argument(1)));
3479
0
}
3480
3481
define_function(rich_toolid_version)
3482
0
{
3483
0
  return_integer(
3484
0
      _rich_version(yr_module(), integer_argument(2), integer_argument(1)));
3485
0
}
3486
3487
define_function(calculate_checksum)
3488
0
{
3489
0
  YR_OBJECT* module = yr_module();
3490
0
  PE* pe = (PE*) module->data;
3491
3492
0
  if (pe == NULL)
3493
0
    return_integer(YR_UNDEFINED);
3494
3495
0
  if (pe->has_calculated_checksum)
3496
0
    return_integer(pe->calculated_checksum);
3497
3498
0
  YR_SCAN_CONTEXT* context = yr_scan_context();
3499
0
  YR_MEMORY_BLOCK* block;
3500
0
  YR_MEMORY_BLOCK_ITERATOR* iterator = context->iterator;
3501
0
  const uint8_t* block_data = NULL;
3502
0
  size_t data_size = 0;
3503
3504
0
  foreach_memory_block(iterator, block)
3505
0
  {
3506
0
    if (block->base == pe->block_base)
3507
0
    {
3508
0
      block_data = yr_fetch_block_data(block);
3509
0
      data_size = block->size;
3510
0
      break;
3511
0
    }
3512
0
  }
3513
3514
0
  if (block_data == NULL)
3515
0
  {
3516
0
    pe->has_calculated_checksum = true;
3517
0
    pe->calculated_checksum = YR_UNDEFINED;
3518
0
    return_integer(YR_UNDEFINED);
3519
0
  }
3520
3521
0
  uint64_t csum = 0;
3522
3523
0
  for (size_t i = 0; i <= data_size / 4; i++)
3524
0
  {
3525
    // Treat the CheckSum field as 0 -- the offset is the same for
3526
    // PE32 and PE64.
3527
3528
0
    if (4 * i == pe->csum_offset)
3529
0
      continue;
3530
3531
0
    if (4 * i + 4 <= data_size)
3532
0
    {
3533
0
      csum +=
3534
0
          ((uint64_t) block_data[4 * i] +
3535
0
           ((uint64_t) block_data[4 * i + 1] << 8) +
3536
0
           ((uint64_t) block_data[4 * i + 2] << 16) +
3537
0
           ((uint64_t) block_data[4 * i + 3] << 24));
3538
0
    }
3539
0
    else
3540
0
    {
3541
0
      for (size_t j = 0; j < data_size % 4; j++)
3542
0
        csum += (uint64_t) block_data[4 * i + j] << (8 * j);
3543
0
    }
3544
3545
0
    if (csum > 0xffffffff)
3546
0
      csum = (csum & 0xffffffff) + (csum >> 32);
3547
0
  }
3548
3549
0
  csum = (csum & 0xffff) + (csum >> 16);
3550
0
  csum += (csum >> 16);
3551
0
  csum &= 0xffff;
3552
0
  csum += data_size;
3553
3554
0
  pe->has_calculated_checksum = true;
3555
0
  pe->calculated_checksum = (int64_t) csum;
3556
3557
0
  return_integer(pe->calculated_checksum);
3558
0
}
3559
3560
define_function(rva_to_offset)
3561
2.09k
{
3562
2.09k
  YR_OBJECT* module = yr_module();
3563
2.09k
  PE* pe = (PE*) module->data;
3564
3565
2.09k
  uint64_t rva;
3566
2.09k
  int64_t offset;
3567
3568
2.09k
  if (pe == NULL)
3569
2.09k
    return_integer(YR_UNDEFINED);
3570
3571
2.09k
  rva = integer_argument(1);
3572
2.09k
  offset = pe_rva_to_offset(pe, rva);
3573
3574
2.09k
  if (offset == -1)
3575
1.48k
    return_integer(YR_UNDEFINED);
3576
3577
1.48k
  return_integer(offset);
3578
0
}
3579
3580
8.20k
begin_declarations
3581
8.20k
  declare_integer("MACHINE_UNKNOWN");
3582
8.20k
  declare_integer("MACHINE_AM33");
3583
8.20k
  declare_integer("MACHINE_AMD64");
3584
8.20k
  declare_integer("MACHINE_ARM");
3585
8.20k
  declare_integer("MACHINE_ARMNT");
3586
8.20k
  declare_integer("MACHINE_ARM64");
3587
8.20k
  declare_integer("MACHINE_EBC");
3588
8.20k
  declare_integer("MACHINE_I386");
3589
8.20k
  declare_integer("MACHINE_IA64");
3590
8.20k
  declare_integer("MACHINE_M32R");
3591
8.20k
  declare_integer("MACHINE_MIPS16");
3592
8.20k
  declare_integer("MACHINE_MIPSFPU");
3593
8.20k
  declare_integer("MACHINE_MIPSFPU16");
3594
8.20k
  declare_integer("MACHINE_POWERPC");
3595
8.20k
  declare_integer("MACHINE_POWERPCFP");
3596
8.20k
  declare_integer("MACHINE_R4000");
3597
8.20k
  declare_integer("MACHINE_SH3");
3598
8.20k
  declare_integer("MACHINE_SH3DSP");
3599
8.20k
  declare_integer("MACHINE_SH4");
3600
8.20k
  declare_integer("MACHINE_SH5");
3601
8.20k
  declare_integer("MACHINE_THUMB");
3602
8.20k
  declare_integer("MACHINE_WCEMIPSV2");
3603
8.20k
  declare_integer("MACHINE_TARGET_HOST");
3604
8.20k
  declare_integer("MACHINE_R3000");
3605
8.20k
  declare_integer("MACHINE_R10000");
3606
8.20k
  declare_integer("MACHINE_ALPHA");
3607
8.20k
  declare_integer("MACHINE_SH3E");
3608
8.20k
  declare_integer("MACHINE_ALPHA64");
3609
8.20k
  declare_integer("MACHINE_AXP64");
3610
8.20k
  declare_integer("MACHINE_TRICORE");
3611
8.20k
  declare_integer("MACHINE_CEF");
3612
8.20k
  declare_integer("MACHINE_CEE");
3613
3614
8.20k
  declare_integer("SUBSYSTEM_UNKNOWN");
3615
8.20k
  declare_integer("SUBSYSTEM_NATIVE");
3616
8.20k
  declare_integer("SUBSYSTEM_WINDOWS_GUI");
3617
8.20k
  declare_integer("SUBSYSTEM_WINDOWS_CUI");
3618
8.20k
  declare_integer("SUBSYSTEM_OS2_CUI");
3619
8.20k
  declare_integer("SUBSYSTEM_POSIX_CUI");
3620
8.20k
  declare_integer("SUBSYSTEM_NATIVE_WINDOWS");
3621
8.20k
  declare_integer("SUBSYSTEM_WINDOWS_CE_GUI");
3622
8.20k
  declare_integer("SUBSYSTEM_EFI_APPLICATION");
3623
8.20k
  declare_integer("SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER");
3624
8.20k
  declare_integer("SUBSYSTEM_EFI_RUNTIME_DRIVER");
3625
8.20k
  declare_integer("SUBSYSTEM_EFI_ROM_IMAGE");
3626
8.20k
  declare_integer("SUBSYSTEM_XBOX");
3627
8.20k
  declare_integer("SUBSYSTEM_WINDOWS_BOOT_APPLICATION");
3628
3629
8.20k
  declare_integer("HIGH_ENTROPY_VA");
3630
8.20k
  declare_integer("DYNAMIC_BASE");
3631
8.20k
  declare_integer("FORCE_INTEGRITY");
3632
8.20k
  declare_integer("NX_COMPAT");
3633
8.20k
  declare_integer("NO_ISOLATION");
3634
8.20k
  declare_integer("NO_SEH");
3635
8.20k
  declare_integer("NO_BIND");
3636
8.20k
  declare_integer("APPCONTAINER");
3637
8.20k
  declare_integer("WDM_DRIVER");
3638
8.20k
  declare_integer("GUARD_CF");
3639
8.20k
  declare_integer("TERMINAL_SERVER_AWARE");
3640
3641
8.20k
  declare_integer("RELOCS_STRIPPED");
3642
8.20k
  declare_integer("EXECUTABLE_IMAGE");
3643
8.20k
  declare_integer("LINE_NUMS_STRIPPED");
3644
8.20k
  declare_integer("LOCAL_SYMS_STRIPPED");
3645
8.20k
  declare_integer("AGGRESIVE_WS_TRIM");
3646
8.20k
  declare_integer("LARGE_ADDRESS_AWARE");
3647
8.20k
  declare_integer("BYTES_REVERSED_LO");
3648
8.20k
  declare_integer("MACHINE_32BIT");
3649
8.20k
  declare_integer("DEBUG_STRIPPED");
3650
8.20k
  declare_integer("REMOVABLE_RUN_FROM_SWAP");
3651
8.20k
  declare_integer("NET_RUN_FROM_SWAP");
3652
8.20k
  declare_integer("SYSTEM");
3653
8.20k
  declare_integer("DLL");
3654
8.20k
  declare_integer("UP_SYSTEM_ONLY");
3655
8.20k
  declare_integer("BYTES_REVERSED_HI");
3656
3657
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_EXPORT");
3658
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_IMPORT");
3659
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_RESOURCE");
3660
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_EXCEPTION");
3661
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_SECURITY");
3662
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_BASERELOC");
3663
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_DEBUG");
3664
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_ARCHITECTURE");
3665
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_COPYRIGHT");
3666
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_GLOBALPTR");
3667
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_TLS");
3668
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG");
3669
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT");
3670
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_IAT");
3671
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT");
3672
8.20k
  declare_integer("IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR");
3673
3674
8.20k
  declare_integer("IMAGE_NT_OPTIONAL_HDR32_MAGIC");
3675
8.20k
  declare_integer("IMAGE_NT_OPTIONAL_HDR64_MAGIC");
3676
8.20k
  declare_integer("IMAGE_ROM_OPTIONAL_HDR_MAGIC");
3677
3678
8.20k
  declare_integer("SECTION_NO_PAD");
3679
8.20k
  declare_integer("SECTION_CNT_CODE");
3680
8.20k
  declare_integer("SECTION_CNT_INITIALIZED_DATA");
3681
8.20k
  declare_integer("SECTION_CNT_UNINITIALIZED_DATA");
3682
8.20k
  declare_integer("SECTION_LNK_OTHER");
3683
8.20k
  declare_integer("SECTION_LNK_INFO");
3684
8.20k
  declare_integer("SECTION_LNK_REMOVE");
3685
8.20k
  declare_integer("SECTION_LNK_COMDAT");
3686
8.20k
  declare_integer("SECTION_NO_DEFER_SPEC_EXC");
3687
8.20k
  declare_integer("SECTION_GPREL");
3688
8.20k
  declare_integer("SECTION_MEM_FARDATA");
3689
8.20k
  declare_integer("SECTION_MEM_PURGEABLE");
3690
8.20k
  declare_integer("SECTION_MEM_16BIT");
3691
8.20k
  declare_integer("SECTION_MEM_LOCKED");
3692
8.20k
  declare_integer("SECTION_MEM_PRELOAD");
3693
8.20k
  declare_integer("SECTION_ALIGN_1BYTES");
3694
8.20k
  declare_integer("SECTION_ALIGN_2BYTES");
3695
8.20k
  declare_integer("SECTION_ALIGN_4BYTES");
3696
8.20k
  declare_integer("SECTION_ALIGN_8BYTES");
3697
8.20k
  declare_integer("SECTION_ALIGN_16BYTES");
3698
8.20k
  declare_integer("SECTION_ALIGN_32BYTES");
3699
8.20k
  declare_integer("SECTION_ALIGN_64BYTES");
3700
8.20k
  declare_integer("SECTION_ALIGN_128BYTES");
3701
8.20k
  declare_integer("SECTION_ALIGN_256BYTES");
3702
8.20k
  declare_integer("SECTION_ALIGN_512BYTES");
3703
8.20k
  declare_integer("SECTION_ALIGN_1024BYTES");
3704
8.20k
  declare_integer("SECTION_ALIGN_2048BYTES");
3705
8.20k
  declare_integer("SECTION_ALIGN_4096BYTES");
3706
8.20k
  declare_integer("SECTION_ALIGN_8192BYTES");
3707
8.20k
  declare_integer("SECTION_ALIGN_MASK");
3708
8.20k
  declare_integer("SECTION_LNK_NRELOC_OVFL");
3709
8.20k
  declare_integer("SECTION_MEM_DISCARDABLE");
3710
8.20k
  declare_integer("SECTION_MEM_NOT_CACHED");
3711
8.20k
  declare_integer("SECTION_MEM_NOT_PAGED");
3712
8.20k
  declare_integer("SECTION_MEM_SHARED");
3713
8.20k
  declare_integer("SECTION_MEM_EXECUTE");
3714
8.20k
  declare_integer("SECTION_MEM_READ");
3715
8.20k
  declare_integer("SECTION_MEM_WRITE");
3716
8.20k
  declare_integer("SECTION_SCALE_INDEX");
3717
3718
8.20k
  declare_integer("RESOURCE_TYPE_CURSOR");
3719
8.20k
  declare_integer("RESOURCE_TYPE_BITMAP");
3720
8.20k
  declare_integer("RESOURCE_TYPE_ICON");
3721
8.20k
  declare_integer("RESOURCE_TYPE_MENU");
3722
8.20k
  declare_integer("RESOURCE_TYPE_DIALOG");
3723
8.20k
  declare_integer("RESOURCE_TYPE_STRING");
3724
8.20k
  declare_integer("RESOURCE_TYPE_FONTDIR");
3725
8.20k
  declare_integer("RESOURCE_TYPE_FONT");
3726
8.20k
  declare_integer("RESOURCE_TYPE_ACCELERATOR");
3727
8.20k
  declare_integer("RESOURCE_TYPE_RCDATA");
3728
8.20k
  declare_integer("RESOURCE_TYPE_MESSAGETABLE");
3729
8.20k
  declare_integer("RESOURCE_TYPE_GROUP_CURSOR");
3730
8.20k
  declare_integer("RESOURCE_TYPE_GROUP_ICON");
3731
8.20k
  declare_integer("RESOURCE_TYPE_VERSION");
3732
8.20k
  declare_integer("RESOURCE_TYPE_DLGINCLUDE");
3733
8.20k
  declare_integer("RESOURCE_TYPE_PLUGPLAY");
3734
8.20k
  declare_integer("RESOURCE_TYPE_VXD");
3735
8.20k
  declare_integer("RESOURCE_TYPE_ANICURSOR");
3736
8.20k
  declare_integer("RESOURCE_TYPE_ANIICON");
3737
8.20k
  declare_integer("RESOURCE_TYPE_HTML");
3738
8.20k
  declare_integer("RESOURCE_TYPE_MANIFEST");
3739
3740
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_UNKNOWN");
3741
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_COFF");
3742
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_CODEVIEW");
3743
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_FPO");
3744
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_MISC");
3745
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_EXCEPTION");
3746
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_FIXUP");
3747
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_OMAP_TO_SRC");
3748
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_OMAP_FROM_SRC");
3749
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_BORLAND");
3750
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_RESERVED10");
3751
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_CLSID");
3752
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_VC_FEATURE");
3753
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_POGO");
3754
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_ILTCG");
3755
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_MPX");
3756
8.20k
  declare_integer("IMAGE_DEBUG_TYPE_REPRO");
3757
3758
8.20k
  declare_integer("IMPORT_DELAYED");
3759
8.20k
  declare_integer("IMPORT_STANDARD");
3760
8.20k
  declare_integer("IMPORT_ANY");
3761
3762
8.20k
  declare_integer("is_pe");
3763
8.20k
  declare_integer("machine");
3764
8.20k
  declare_integer("number_of_sections");
3765
8.20k
  declare_integer("timestamp");
3766
8.20k
  declare_integer("pointer_to_symbol_table");
3767
8.20k
  declare_integer("number_of_symbols");
3768
8.20k
  declare_integer("size_of_optional_header");
3769
8.20k
  declare_integer("characteristics");
3770
3771
8.20k
  declare_integer("entry_point");
3772
8.20k
  declare_integer("entry_point_raw");
3773
8.20k
  declare_integer("image_base");
3774
8.20k
  declare_integer("number_of_rva_and_sizes");
3775
8.20k
  declare_integer("number_of_version_infos");
3776
3777
16.4k
  declare_string_dictionary("version_info");
3778
3779
24.6k
  begin_struct_array("version_info_list")
3780
8.20k
    declare_string("key");
3781
8.20k
    declare_string("value");
3782
16.4k
  end_struct_array("version_info_list");
3783
3784
16.4k
  declare_integer("opthdr_magic");
3785
8.20k
  declare_integer("size_of_code");
3786
8.20k
  declare_integer("size_of_initialized_data");
3787
8.20k
  declare_integer("size_of_uninitialized_data");
3788
8.20k
  declare_integer("base_of_code");
3789
8.20k
  declare_integer("base_of_data");
3790
8.20k
  declare_integer("section_alignment");
3791
8.20k
  declare_integer("file_alignment");
3792
3793
16.4k
  begin_struct("linker_version")
3794
8.20k
    declare_integer("major");
3795
8.20k
    declare_integer("minor");
3796
16.4k
  end_struct("linker_version");
3797
3798
16.4k
  begin_struct("os_version")
3799
8.20k
    declare_integer("major");
3800
8.20k
    declare_integer("minor");
3801
16.4k
  end_struct("os_version");
3802
3803
16.4k
  begin_struct("image_version")
3804
8.20k
    declare_integer("major");
3805
8.20k
    declare_integer("minor");
3806
16.4k
  end_struct("image_version");
3807
3808
16.4k
  begin_struct("subsystem_version")
3809
8.20k
    declare_integer("major");
3810
8.20k
    declare_integer("minor");
3811
16.4k
  end_struct("subsystem_version");
3812
3813
16.4k
  declare_integer("win32_version_value");
3814
8.20k
  declare_integer("size_of_image");
3815
8.20k
  declare_integer("size_of_headers");
3816
3817
8.20k
  declare_integer("checksum");
3818
8.20k
  declare_function("calculate_checksum", "", "i", calculate_checksum);
3819
8.20k
  declare_integer("subsystem");
3820
3821
8.20k
  declare_integer("dll_characteristics");
3822
8.20k
  declare_integer("size_of_stack_reserve");
3823
8.20k
  declare_integer("size_of_stack_commit");
3824
8.20k
  declare_integer("size_of_heap_reserve");
3825
8.20k
  declare_integer("size_of_heap_commit");
3826
8.20k
  declare_integer("loader_flags");
3827
3828
24.6k
  begin_struct_array("data_directories")
3829
8.20k
    declare_integer("virtual_address");
3830
8.20k
    declare_integer("size");
3831
16.4k
  end_struct_array("data_directories");
3832
3833
24.6k
  begin_struct_array("sections")
3834
8.20k
    declare_string("name");
3835
8.20k
    declare_string("full_name");
3836
8.20k
    declare_integer("characteristics");
3837
8.20k
    declare_integer("virtual_address");
3838
8.20k
    declare_integer("virtual_size");
3839
8.20k
    declare_integer("raw_data_offset");
3840
8.20k
    declare_integer("raw_data_size");
3841
8.20k
    declare_integer("pointer_to_relocations");
3842
8.20k
    declare_integer("pointer_to_line_numbers");
3843
8.20k
    declare_integer("number_of_relocations");
3844
8.20k
    declare_integer("number_of_line_numbers");
3845
16.4k
  end_struct_array("sections");
3846
3847
16.4k
  begin_struct("overlay")
3848
8.20k
    declare_integer("offset");
3849
8.20k
    declare_integer("size");
3850
16.4k
  end_struct("overlay");
3851
3852
16.4k
  begin_struct("rich_signature")
3853
8.20k
    declare_integer("offset");
3854
8.20k
    declare_integer("length");
3855
8.20k
    declare_integer("key");
3856
8.20k
    declare_string("raw_data");
3857
8.20k
    declare_string("clear_data");
3858
8.20k
    declare_string("version_data");
3859
8.20k
    declare_function("version", "i", "i", rich_version);
3860
8.20k
    declare_function("version", "ii", "i", rich_version_toolid);
3861
8.20k
    declare_function("toolid", "i", "i", rich_toolid);
3862
8.20k
    declare_function("toolid", "ii", "i", rich_toolid_version);
3863
16.4k
  end_struct("rich_signature");
3864
3865
#if defined(HAVE_LIBCRYPTO) || defined(HAVE_WINCRYPT_H) || \
3866
    defined(HAVE_COMMONCRYPTO_COMMONCRYPTO_H)
3867
  declare_function("imphash", "", "s", imphash);
3868
#endif
3869
3870
16.4k
  declare_function("section_index", "s", "i", section_index_name);
3871
8.20k
  declare_function("section_index", "i", "i", section_index_addr);
3872
8.20k
  declare_function("exports", "s", "i", exports);
3873
8.20k
  declare_function("exports", "r", "i", exports_regexp);
3874
8.20k
  declare_function("exports", "i", "i", exports_ordinal);
3875
8.20k
  declare_function("exports_index", "s", "i", exports_index_name);
3876
8.20k
  declare_function("exports_index", "i", "i", exports_index_ordinal);
3877
8.20k
  declare_function("exports_index", "r", "i", exports_index_regex);
3878
8.20k
  declare_function("imports", "ss", "i", imports_standard);
3879
8.20k
  declare_function("imports", "si", "i", imports_standard_ordinal);
3880
8.20k
  declare_function("imports", "s", "i", imports_standard_dll);
3881
8.20k
  declare_function("imports", "rr", "i", imports_standard_regex);
3882
8.20k
  declare_function("imports", "iss", "i", imports);
3883
8.20k
  declare_function("imports", "isi", "i", imports_ordinal);
3884
8.20k
  declare_function("imports", "is", "i", imports_dll);
3885
8.20k
  declare_function("imports", "irr", "i", imports_regex);
3886
8.20k
  declare_function("import_rva", "ss", "i", import_rva);
3887
8.20k
  declare_function("import_rva", "si", "i", import_rva_ordinal);
3888
8.20k
  declare_function("delayed_import_rva", "ss", "i", delayed_import_rva);
3889
8.20k
  declare_function("delayed_import_rva", "si", "i", delayed_import_rva_ordinal);
3890
8.20k
  declare_function("locale", "i", "i", locale);
3891
8.20k
  declare_function("language", "i", "i", language);
3892
8.20k
  declare_function("is_dll", "", "i", is_dll);
3893
8.20k
  declare_function("is_32bit", "", "i", is_32bit);
3894
8.20k
  declare_function("is_64bit", "", "i", is_64bit);
3895
3896
8.20k
  declare_integer("number_of_imports");
3897
8.20k
  declare_integer("number_of_imported_functions");
3898
8.20k
  declare_integer("number_of_delayed_imports");
3899
8.20k
  declare_integer("number_of_delayed_imported_functions");
3900
8.20k
  declare_integer("number_of_exports");
3901
3902
8.20k
  declare_string("dll_name");
3903
8.20k
  declare_integer("export_timestamp");
3904
24.6k
  begin_struct_array("export_details")
3905
8.20k
    declare_integer("offset");
3906
8.20k
    declare_string("name");
3907
8.20k
    declare_string("forward_name");
3908
8.20k
    declare_integer("ordinal");
3909
8.20k
    declare_integer("rva");
3910
16.4k
  end_struct_array("export_details")
3911
3912
24.6k
  begin_struct_array("import_details")
3913
8.20k
    declare_string("library_name");
3914
8.20k
    declare_integer("number_of_functions");
3915
24.6k
    begin_struct_array("functions")
3916
8.20k
      declare_string("name");
3917
8.20k
      declare_integer("ordinal");
3918
8.20k
      declare_integer("rva");
3919
16.4k
    end_struct_array("functions");
3920
16.4k
  end_struct_array("import_details");
3921
3922
24.6k
  begin_struct_array("delayed_import_details")
3923
8.20k
    declare_string("library_name");
3924
8.20k
    declare_integer("number_of_functions");
3925
24.6k
    begin_struct_array("functions")
3926
8.20k
      declare_string("name");
3927
8.20k
      declare_integer("ordinal");
3928
8.20k
      declare_integer("rva");
3929
16.4k
    end_struct_array("functions");
3930
16.4k
  end_struct_array("delayed_import_details");
3931
3932
16.4k
  declare_integer("resource_timestamp");
3933
3934
16.4k
  begin_struct("resource_version")
3935
8.20k
    declare_integer("major");
3936
8.20k
    declare_integer("minor");
3937
16.4k
  end_struct("resource_version")
3938
3939
24.6k
  begin_struct_array("resources")
3940
8.20k
    declare_integer("rva");
3941
8.20k
    declare_integer("offset");
3942
8.20k
    declare_integer("length");
3943
8.20k
    declare_integer("type");
3944
8.20k
    declare_integer("id");
3945
8.20k
    declare_integer("language");
3946
8.20k
    declare_string("type_string");
3947
8.20k
    declare_string("name_string");
3948
8.20k
    declare_string("language_string");
3949
16.4k
  end_struct_array("resources")
3950
3951
8.20k
  declare_integer("number_of_resources");
3952
8.20k
  declare_string("pdb_path");
3953
3954
#if defined(HAVE_LIBCRYPTO) && !defined(BORINGSSL)
3955
  begin_struct_array("signatures")
3956
    declare_string("thumbprint");
3957
    declare_string("issuer");
3958
    declare_string("subject");
3959
    declare_integer("version");
3960
    declare_string("algorithm");
3961
    declare_string("algorithm_oid");
3962
    declare_string("serial");
3963
    declare_integer("not_before");
3964
    declare_integer("not_after");
3965
3966
    declare_integer("verified");
3967
    declare_string("digest_alg");
3968
    declare_string("digest");
3969
    declare_string("file_digest");
3970
    declare_integer("number_of_certificates");
3971
    begin_struct_array("certificates")
3972
      ;
3973
      declare_string("thumbprint");
3974
      declare_string("issuer");
3975
      declare_string("subject");
3976
      declare_integer("version");
3977
      declare_string("algorithm");
3978
      declare_string("algorithm_oid");
3979
      declare_string("serial");
3980
      declare_integer("not_before");
3981
      declare_integer("not_after");
3982
    end_struct_array("certificates");
3983
3984
    begin_struct("signer_info")
3985
      ;
3986
      declare_string("program_name");
3987
      declare_string("digest");
3988
      declare_string("digest_alg");
3989
      declare_integer("length_of_chain");
3990
      begin_struct_array("chain")
3991
        ;
3992
        declare_string("thumbprint");
3993
        declare_string("issuer");
3994
        declare_string("subject");
3995
        declare_integer("version");
3996
        declare_string("algorithm");
3997
        declare_string("algorithm_oid");
3998
        declare_string("serial");
3999
        declare_integer("not_before");
4000
        declare_integer("not_after");
4001
      end_struct_array("chain");
4002
    end_struct("signer_info");
4003
4004
    declare_integer("number_of_countersignatures");
4005
    begin_struct_array("countersignatures")
4006
      ;
4007
      declare_integer("verified");
4008
      declare_integer("sign_time");
4009
      declare_string("digest_alg");
4010
      declare_string("digest");
4011
      declare_integer("length_of_chain");
4012
      begin_struct_array("chain")
4013
        ;
4014
        declare_string("thumbprint");
4015
        declare_string("issuer");
4016
        declare_string("subject");
4017
        declare_integer("version");
4018
        declare_string("algorithm");
4019
        declare_string("algorithm_oid");
4020
        declare_string("serial");
4021
        declare_integer("not_before");
4022
        declare_integer("not_after");
4023
      end_struct_array("chain");
4024
    end_struct_array("countersignatures")
4025
4026
    declare_function("valid_on", "i", "i", valid_on);
4027
4028
  end_struct_array("signatures")
4029
4030
  // If any of the signatures correctly signs the binary
4031
  declare_integer("is_signed");
4032
  declare_integer("number_of_signatures");
4033
#endif
4034
4035
8.20k
  declare_function("rva_to_offset", "i", "i", rva_to_offset);
4036
8.20k
end_declarations
4037
4038
int module_initialize(YR_MODULE* module)
4039
2
{
4040
#if defined(HAVE_LIBCRYPTO) && !defined(BORINGSSL)
4041
  // Initialize OpenSSL global objects for the auth library before any
4042
  // multithreaded environment as it is not thread-safe. This can
4043
  // only be called once per process.
4044
  static bool s_initialized = false;
4045
4046
  if (!s_initialized)
4047
  {
4048
    s_initialized = true;
4049
    initialize_authenticode_parser();
4050
  }
4051
#endif
4052
2
  return ERROR_SUCCESS;
4053
2
}
4054
4055
int module_finalize(YR_MODULE* module)
4056
0
{
4057
0
  return ERROR_SUCCESS;
4058
0
}
4059
4060
int module_load(
4061
    YR_SCAN_CONTEXT* context,
4062
    YR_OBJECT* module_object,
4063
    void* module_data,
4064
    size_t module_data_size)
4065
8.20k
{
4066
8.20k
  YR_MEMORY_BLOCK* block;
4067
8.20k
  YR_MEMORY_BLOCK_ITERATOR* iterator = context->iterator;
4068
4069
8.20k
  PIMAGE_NT_HEADERS32 pe_header;
4070
8.20k
  const uint8_t* block_data = NULL;
4071
8.20k
  PE* pe = NULL;
4072
4073
8.20k
  yr_set_integer(IMPORT_DELAYED, module_object, "IMPORT_DELAYED");
4074
8.20k
  yr_set_integer(IMPORT_STANDARD, module_object, "IMPORT_STANDARD");
4075
8.20k
  yr_set_integer(IMPORT_ANY, module_object, "IMPORT_ANY");
4076
4077
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_UNKNOWN, module_object, "MACHINE_UNKNOWN");
4078
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_AM33, module_object, "MACHINE_AM33");
4079
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_AMD64, module_object, "MACHINE_AMD64");
4080
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_ARM, module_object, "MACHINE_ARM");
4081
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_ARMNT, module_object, "MACHINE_ARMNT");
4082
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_ARM64, module_object, "MACHINE_ARM64");
4083
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_EBC, module_object, "MACHINE_EBC");
4084
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_I386, module_object, "MACHINE_I386");
4085
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_IA64, module_object, "MACHINE_IA64");
4086
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_M32R, module_object, "MACHINE_M32R");
4087
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_MIPS16, module_object, "MACHINE_MIPS16");
4088
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_MIPSFPU, module_object, "MACHINE_MIPSFPU");
4089
8.20k
  yr_set_integer(
4090
8.20k
      IMAGE_FILE_MACHINE_MIPSFPU16, module_object, "MACHINE_MIPSFPU16");
4091
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_POWERPC, module_object, "MACHINE_POWERPC");
4092
8.20k
  yr_set_integer(
4093
8.20k
      IMAGE_FILE_MACHINE_POWERPCFP, module_object, "MACHINE_POWERPCFP");
4094
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_R4000, module_object, "MACHINE_R4000");
4095
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_SH3, module_object, "MACHINE_SH3");
4096
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_SH3DSP, module_object, "MACHINE_SH3DSP");
4097
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_SH4, module_object, "MACHINE_SH4");
4098
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_SH5, module_object, "MACHINE_SH5");
4099
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_THUMB, module_object, "MACHINE_THUMB");
4100
8.20k
  yr_set_integer(
4101
8.20k
      IMAGE_FILE_MACHINE_WCEMIPSV2, module_object, "MACHINE_WCEMIPSV2");
4102
8.20k
  yr_set_integer(
4103
8.20k
      IMAGE_FILE_MACHINE_TARGET_HOST, module_object, "MACHINE_TARGET_HOST");
4104
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_R3000, module_object, "MACHINE_R3000");
4105
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_R10000, module_object, "MACHINE_R10000");
4106
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_ALPHA, module_object, "MACHINE_ALPHA");
4107
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_SH3E, module_object, "MACHINE_SH3E");
4108
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_ALPHA64, module_object, "MACHINE_ALPHA64");
4109
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_AXP64, module_object, "MACHINE_AXP64");
4110
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_TRICORE, module_object, "MACHINE_TRICORE");
4111
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_CEF, module_object, "MACHINE_CEF");
4112
8.20k
  yr_set_integer(IMAGE_FILE_MACHINE_CEE, module_object, "MACHINE_CEE");
4113
4114
8.20k
  yr_set_integer(IMAGE_SUBSYSTEM_UNKNOWN, module_object, "SUBSYSTEM_UNKNOWN");
4115
8.20k
  yr_set_integer(IMAGE_SUBSYSTEM_NATIVE, module_object, "SUBSYSTEM_NATIVE");
4116
8.20k
  yr_set_integer(
4117
8.20k
      IMAGE_SUBSYSTEM_WINDOWS_GUI, module_object, "SUBSYSTEM_WINDOWS_GUI");
4118
8.20k
  yr_set_integer(
4119
8.20k
      IMAGE_SUBSYSTEM_WINDOWS_CUI, module_object, "SUBSYSTEM_WINDOWS_CUI");
4120
8.20k
  yr_set_integer(IMAGE_SUBSYSTEM_OS2_CUI, module_object, "SUBSYSTEM_OS2_CUI");
4121
8.20k
  yr_set_integer(
4122
8.20k
      IMAGE_SUBSYSTEM_POSIX_CUI, module_object, "SUBSYSTEM_POSIX_CUI");
4123
8.20k
  yr_set_integer(
4124
8.20k
      IMAGE_SUBSYSTEM_NATIVE_WINDOWS,
4125
8.20k
      module_object,
4126
8.20k
      "SUBSYSTEM_NATIVE_WINDOWS");
4127
8.20k
  yr_set_integer(
4128
8.20k
      IMAGE_SUBSYSTEM_WINDOWS_CE_GUI,
4129
8.20k
      module_object,
4130
8.20k
      "SUBSYSTEM_WINDOWS_CE_GUI");
4131
8.20k
  yr_set_integer(
4132
8.20k
      IMAGE_SUBSYSTEM_EFI_APPLICATION,
4133
8.20k
      module_object,
4134
8.20k
      "SUBSYSTEM_EFI_APPLICATION");
4135
8.20k
  yr_set_integer(
4136
8.20k
      IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER,
4137
8.20k
      module_object,
4138
8.20k
      "SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER");
4139
8.20k
  yr_set_integer(
4140
8.20k
      IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER,
4141
8.20k
      module_object,
4142
8.20k
      "SUBSYSTEM_EFI_RUNTIME_DRIVER");
4143
8.20k
  yr_set_integer(
4144
8.20k
      IMAGE_SUBSYSTEM_EFI_ROM_IMAGE, module_object, "SUBSYSTEM_EFI_ROM_IMAGE");
4145
8.20k
  yr_set_integer(IMAGE_SUBSYSTEM_XBOX, module_object, "SUBSYSTEM_XBOX");
4146
8.20k
  yr_set_integer(
4147
8.20k
      IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION,
4148
8.20k
      module_object,
4149
8.20k
      "SUBSYSTEM_WINDOWS_BOOT_APPLICATION");
4150
4151
8.20k
  yr_set_integer(
4152
8.20k
      IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA,
4153
8.20k
      module_object,
4154
8.20k
      "HIGH_ENTROPY_VA");
4155
8.20k
  yr_set_integer(
4156
8.20k
      IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE, module_object, "DYNAMIC_BASE");
4157
8.20k
  yr_set_integer(
4158
8.20k
      IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY,
4159
8.20k
      module_object,
4160
8.20k
      "FORCE_INTEGRITY");
4161
8.20k
  yr_set_integer(
4162
8.20k
      IMAGE_DLLCHARACTERISTICS_NX_COMPAT, module_object, "NX_COMPAT");
4163
8.20k
  yr_set_integer(
4164
8.20k
      IMAGE_DLLCHARACTERISTICS_NO_ISOLATION, module_object, "NO_ISOLATION");
4165
8.20k
  yr_set_integer(IMAGE_DLLCHARACTERISTICS_NO_SEH, module_object, "NO_SEH");
4166
8.20k
  yr_set_integer(IMAGE_DLLCHARACTERISTICS_NO_BIND, module_object, "NO_BIND");
4167
8.20k
  yr_set_integer(
4168
8.20k
      IMAGE_DLLCHARACTERISTICS_APPCONTAINER, module_object, "APPCONTAINER");
4169
8.20k
  yr_set_integer(
4170
8.20k
      IMAGE_DLLCHARACTERISTICS_WDM_DRIVER, module_object, "WDM_DRIVER");
4171
8.20k
  yr_set_integer(IMAGE_DLLCHARACTERISTICS_GUARD_CF, module_object, "GUARD_CF");
4172
8.20k
  yr_set_integer(
4173
8.20k
      IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE,
4174
8.20k
      module_object,
4175
8.20k
      "TERMINAL_SERVER_AWARE");
4176
4177
8.20k
  yr_set_integer(IMAGE_FILE_RELOCS_STRIPPED, module_object, "RELOCS_STRIPPED");
4178
8.20k
  yr_set_integer(
4179
8.20k
      IMAGE_FILE_EXECUTABLE_IMAGE, module_object, "EXECUTABLE_IMAGE");
4180
8.20k
  yr_set_integer(
4181
8.20k
      IMAGE_FILE_LINE_NUMS_STRIPPED, module_object, "LINE_NUMS_STRIPPED");
4182
8.20k
  yr_set_integer(
4183
8.20k
      IMAGE_FILE_LOCAL_SYMS_STRIPPED, module_object, "LOCAL_SYMS_STRIPPED");
4184
8.20k
  yr_set_integer(
4185
8.20k
      IMAGE_FILE_AGGRESIVE_WS_TRIM, module_object, "AGGRESIVE_WS_TRIM");
4186
8.20k
  yr_set_integer(
4187
8.20k
      IMAGE_FILE_LARGE_ADDRESS_AWARE, module_object, "LARGE_ADDRESS_AWARE");
4188
8.20k
  yr_set_integer(
4189
8.20k
      IMAGE_FILE_BYTES_REVERSED_LO, module_object, "BYTES_REVERSED_LO");
4190
8.20k
  yr_set_integer(IMAGE_FILE_32BIT_MACHINE, module_object, "MACHINE_32BIT");
4191
8.20k
  yr_set_integer(IMAGE_FILE_DEBUG_STRIPPED, module_object, "DEBUG_STRIPPED");
4192
8.20k
  yr_set_integer(
4193
8.20k
      IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP,
4194
8.20k
      module_object,
4195
8.20k
      "REMOVABLE_RUN_FROM_SWAP");
4196
8.20k
  yr_set_integer(
4197
8.20k
      IMAGE_FILE_NET_RUN_FROM_SWAP, module_object, "NET_RUN_FROM_SWAP");
4198
8.20k
  yr_set_integer(IMAGE_FILE_SYSTEM, module_object, "SYSTEM");
4199
8.20k
  yr_set_integer(IMAGE_FILE_DLL, module_object, "DLL");
4200
8.20k
  yr_set_integer(IMAGE_FILE_UP_SYSTEM_ONLY, module_object, "UP_SYSTEM_ONLY");
4201
8.20k
  yr_set_integer(
4202
8.20k
      IMAGE_FILE_BYTES_REVERSED_HI, module_object, "BYTES_REVERSED_HI");
4203
4204
8.20k
  yr_set_integer(
4205
8.20k
      IMAGE_DIRECTORY_ENTRY_EXPORT,
4206
8.20k
      module_object,
4207
8.20k
      "IMAGE_DIRECTORY_ENTRY_EXPORT");
4208
8.20k
  yr_set_integer(
4209
8.20k
      IMAGE_DIRECTORY_ENTRY_IMPORT,
4210
8.20k
      module_object,
4211
8.20k
      "IMAGE_DIRECTORY_ENTRY_IMPORT");
4212
8.20k
  yr_set_integer(
4213
8.20k
      IMAGE_DIRECTORY_ENTRY_RESOURCE,
4214
8.20k
      module_object,
4215
8.20k
      "IMAGE_DIRECTORY_ENTRY_RESOURCE");
4216
8.20k
  yr_set_integer(
4217
8.20k
      IMAGE_DIRECTORY_ENTRY_EXCEPTION,
4218
8.20k
      module_object,
4219
8.20k
      "IMAGE_DIRECTORY_ENTRY_EXCEPTION");
4220
8.20k
  yr_set_integer(
4221
8.20k
      IMAGE_DIRECTORY_ENTRY_SECURITY,
4222
8.20k
      module_object,
4223
8.20k
      "IMAGE_DIRECTORY_ENTRY_SECURITY");
4224
8.20k
  yr_set_integer(
4225
8.20k
      IMAGE_DIRECTORY_ENTRY_BASERELOC,
4226
8.20k
      module_object,
4227
8.20k
      "IMAGE_DIRECTORY_ENTRY_BASERELOC");
4228
8.20k
  yr_set_integer(
4229
8.20k
      IMAGE_DIRECTORY_ENTRY_DEBUG,
4230
8.20k
      module_object,
4231
8.20k
      "IMAGE_DIRECTORY_ENTRY_DEBUG");
4232
8.20k
  yr_set_integer(
4233
8.20k
      IMAGE_DIRECTORY_ENTRY_ARCHITECTURE,
4234
8.20k
      module_object,
4235
8.20k
      "IMAGE_DIRECTORY_ENTRY_ARCHITECTURE");
4236
8.20k
  yr_set_integer(
4237
8.20k
      IMAGE_DIRECTORY_ENTRY_COPYRIGHT,
4238
8.20k
      module_object,
4239
8.20k
      "IMAGE_DIRECTORY_ENTRY_COPYRIGHT");
4240
8.20k
  yr_set_integer(
4241
8.20k
      IMAGE_DIRECTORY_ENTRY_GLOBALPTR,
4242
8.20k
      module_object,
4243
8.20k
      "IMAGE_DIRECTORY_ENTRY_GLOBALPTR");
4244
8.20k
  yr_set_integer(
4245
8.20k
      IMAGE_DIRECTORY_ENTRY_TLS, module_object, "IMAGE_DIRECTORY_ENTRY_TLS");
4246
8.20k
  yr_set_integer(
4247
8.20k
      IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG,
4248
8.20k
      module_object,
4249
8.20k
      "IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG");
4250
8.20k
  yr_set_integer(
4251
8.20k
      IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT,
4252
8.20k
      module_object,
4253
8.20k
      "IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT");
4254
8.20k
  yr_set_integer(
4255
8.20k
      IMAGE_DIRECTORY_ENTRY_IAT, module_object, "IMAGE_DIRECTORY_ENTRY_IAT");
4256
8.20k
  yr_set_integer(
4257
8.20k
      IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT,
4258
8.20k
      module_object,
4259
8.20k
      "IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT");
4260
8.20k
  yr_set_integer(
4261
8.20k
      IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR,
4262
8.20k
      module_object,
4263
8.20k
      "IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR");
4264
4265
8.20k
  yr_set_integer(
4266
8.20k
      IMAGE_NT_OPTIONAL_HDR32_MAGIC,
4267
8.20k
      module_object,
4268
8.20k
      "IMAGE_NT_OPTIONAL_HDR32_MAGIC");
4269
8.20k
  yr_set_integer(
4270
8.20k
      IMAGE_NT_OPTIONAL_HDR64_MAGIC,
4271
8.20k
      module_object,
4272
8.20k
      "IMAGE_NT_OPTIONAL_HDR64_MAGIC");
4273
8.20k
  yr_set_integer(
4274
8.20k
      IMAGE_ROM_OPTIONAL_HDR_MAGIC,
4275
8.20k
      module_object,
4276
8.20k
      "IMAGE_ROM_OPTIONAL_HDR_MAGIC");
4277
4278
8.20k
  yr_set_integer(IMAGE_SCN_TYPE_NO_PAD, module_object, "SECTION_NO_PAD");
4279
8.20k
  yr_set_integer(IMAGE_SCN_CNT_CODE, module_object, "SECTION_CNT_CODE");
4280
8.20k
  yr_set_integer(
4281
8.20k
      IMAGE_SCN_CNT_INITIALIZED_DATA,
4282
8.20k
      module_object,
4283
8.20k
      "SECTION_CNT_INITIALIZED_DATA");
4284
8.20k
  yr_set_integer(
4285
8.20k
      IMAGE_SCN_CNT_UNINITIALIZED_DATA,
4286
8.20k
      module_object,
4287
8.20k
      "SECTION_CNT_UNINITIALIZED_DATA");
4288
8.20k
  yr_set_integer(IMAGE_SCN_LNK_OTHER, module_object, "SECTION_LNK_OTHER");
4289
8.20k
  yr_set_integer(IMAGE_SCN_LNK_INFO, module_object, "SECTION_LNK_INFO");
4290
8.20k
  yr_set_integer(IMAGE_SCN_LNK_REMOVE, module_object, "SECTION_LNK_REMOVE");
4291
8.20k
  yr_set_integer(IMAGE_SCN_LNK_COMDAT, module_object, "SECTION_LNK_COMDAT");
4292
8.20k
  yr_set_integer(
4293
8.20k
      IMAGE_SCN_NO_DEFER_SPEC_EXC, module_object, "SECTION_NO_DEFER_SPEC_EXC");
4294
8.20k
  yr_set_integer(IMAGE_SCN_GPREL, module_object, "SECTION_GPREL");
4295
8.20k
  yr_set_integer(IMAGE_SCN_MEM_FARDATA, module_object, "SECTION_MEM_FARDATA");
4296
8.20k
  yr_set_integer(
4297
8.20k
      IMAGE_SCN_MEM_PURGEABLE, module_object, "SECTION_MEM_PURGEABLE");
4298
8.20k
  yr_set_integer(IMAGE_SCN_MEM_16BIT, module_object, "SECTION_MEM_16BIT");
4299
8.20k
  yr_set_integer(IMAGE_SCN_MEM_LOCKED, module_object, "SECTION_MEM_LOCKED");
4300
8.20k
  yr_set_integer(IMAGE_SCN_MEM_PRELOAD, module_object, "SECTION_MEM_PRELOAD");
4301
8.20k
  yr_set_integer(IMAGE_SCN_ALIGN_1BYTES, module_object, "SECTION_ALIGN_1BYTES");
4302
8.20k
  yr_set_integer(IMAGE_SCN_ALIGN_2BYTES, module_object, "SECTION_ALIGN_2BYTES");
4303
8.20k
  yr_set_integer(IMAGE_SCN_ALIGN_4BYTES, module_object, "SECTION_ALIGN_4BYTES");
4304
8.20k
  yr_set_integer(IMAGE_SCN_ALIGN_8BYTES, module_object, "SECTION_ALIGN_8BYTES");
4305
8.20k
  yr_set_integer(
4306
8.20k
      IMAGE_SCN_ALIGN_16BYTES, module_object, "SECTION_ALIGN_16BYTES");
4307
8.20k
  yr_set_integer(
4308
8.20k
      IMAGE_SCN_ALIGN_32BYTES, module_object, "SECTION_ALIGN_32BYTES");
4309
8.20k
  yr_set_integer(
4310
8.20k
      IMAGE_SCN_ALIGN_64BYTES, module_object, "SECTION_ALIGN_64BYTES");
4311
8.20k
  yr_set_integer(
4312
8.20k
      IMAGE_SCN_ALIGN_128BYTES, module_object, "SECTION_ALIGN_128BYTES");
4313
8.20k
  yr_set_integer(
4314
8.20k
      IMAGE_SCN_ALIGN_256BYTES, module_object, "SECTION_ALIGN_256BYTES");
4315
8.20k
  yr_set_integer(
4316
8.20k
      IMAGE_SCN_ALIGN_512BYTES, module_object, "SECTION_ALIGN_512BYTES");
4317
8.20k
  yr_set_integer(
4318
8.20k
      IMAGE_SCN_ALIGN_1024BYTES, module_object, "SECTION_ALIGN_1024BYTES");
4319
8.20k
  yr_set_integer(
4320
8.20k
      IMAGE_SCN_ALIGN_2048BYTES, module_object, "SECTION_ALIGN_2048BYTES");
4321
8.20k
  yr_set_integer(
4322
8.20k
      IMAGE_SCN_ALIGN_4096BYTES, module_object, "SECTION_ALIGN_4096BYTES");
4323
8.20k
  yr_set_integer(
4324
8.20k
      IMAGE_SCN_ALIGN_8192BYTES, module_object, "SECTION_ALIGN_8192BYTES");
4325
8.20k
  yr_set_integer(IMAGE_SCN_ALIGN_MASK, module_object, "SECTION_ALIGN_MASK");
4326
8.20k
  yr_set_integer(
4327
8.20k
      IMAGE_SCN_LNK_NRELOC_OVFL, module_object, "SECTION_LNK_NRELOC_OVFL");
4328
8.20k
  yr_set_integer(
4329
8.20k
      IMAGE_SCN_MEM_DISCARDABLE, module_object, "SECTION_MEM_DISCARDABLE");
4330
8.20k
  yr_set_integer(
4331
8.20k
      IMAGE_SCN_MEM_NOT_CACHED, module_object, "SECTION_MEM_NOT_CACHED");
4332
8.20k
  yr_set_integer(
4333
8.20k
      IMAGE_SCN_MEM_NOT_PAGED, module_object, "SECTION_MEM_NOT_PAGED");
4334
8.20k
  yr_set_integer(IMAGE_SCN_MEM_SHARED, module_object, "SECTION_MEM_SHARED");
4335
8.20k
  yr_set_integer(IMAGE_SCN_MEM_EXECUTE, module_object, "SECTION_MEM_EXECUTE");
4336
8.20k
  yr_set_integer(IMAGE_SCN_MEM_READ, module_object, "SECTION_MEM_READ");
4337
8.20k
  yr_set_integer(IMAGE_SCN_MEM_WRITE, module_object, "SECTION_MEM_WRITE");
4338
8.20k
  yr_set_integer(IMAGE_SCN_SCALE_INDEX, module_object, "SECTION_SCALE_INDEX");
4339
4340
8.20k
  yr_set_integer(RESOURCE_TYPE_CURSOR, module_object, "RESOURCE_TYPE_CURSOR");
4341
8.20k
  yr_set_integer(RESOURCE_TYPE_BITMAP, module_object, "RESOURCE_TYPE_BITMAP");
4342
8.20k
  yr_set_integer(RESOURCE_TYPE_ICON, module_object, "RESOURCE_TYPE_ICON");
4343
8.20k
  yr_set_integer(RESOURCE_TYPE_MENU, module_object, "RESOURCE_TYPE_MENU");
4344
8.20k
  yr_set_integer(RESOURCE_TYPE_DIALOG, module_object, "RESOURCE_TYPE_DIALOG");
4345
8.20k
  yr_set_integer(RESOURCE_TYPE_STRING, module_object, "RESOURCE_TYPE_STRING");
4346
8.20k
  yr_set_integer(RESOURCE_TYPE_FONTDIR, module_object, "RESOURCE_TYPE_FONTDIR");
4347
8.20k
  yr_set_integer(RESOURCE_TYPE_FONT, module_object, "RESOURCE_TYPE_FONT");
4348
8.20k
  yr_set_integer(
4349
8.20k
      RESOURCE_TYPE_ACCELERATOR, module_object, "RESOURCE_TYPE_ACCELERATOR");
4350
8.20k
  yr_set_integer(RESOURCE_TYPE_RCDATA, module_object, "RESOURCE_TYPE_RCDATA");
4351
8.20k
  yr_set_integer(
4352
8.20k
      RESOURCE_TYPE_MESSAGETABLE, module_object, "RESOURCE_TYPE_MESSAGETABLE");
4353
8.20k
  yr_set_integer(
4354
8.20k
      RESOURCE_TYPE_GROUP_CURSOR, module_object, "RESOURCE_TYPE_GROUP_CURSOR");
4355
8.20k
  yr_set_integer(
4356
8.20k
      RESOURCE_TYPE_GROUP_ICON, module_object, "RESOURCE_TYPE_GROUP_ICON");
4357
8.20k
  yr_set_integer(RESOURCE_TYPE_VERSION, module_object, "RESOURCE_TYPE_VERSION");
4358
8.20k
  yr_set_integer(
4359
8.20k
      RESOURCE_TYPE_DLGINCLUDE, module_object, "RESOURCE_TYPE_DLGINCLUDE");
4360
8.20k
  yr_set_integer(
4361
8.20k
      RESOURCE_TYPE_PLUGPLAY, module_object, "RESOURCE_TYPE_PLUGPLAY");
4362
8.20k
  yr_set_integer(RESOURCE_TYPE_VXD, module_object, "RESOURCE_TYPE_VXD");
4363
8.20k
  yr_set_integer(
4364
8.20k
      RESOURCE_TYPE_ANICURSOR, module_object, "RESOURCE_TYPE_ANICURSOR");
4365
8.20k
  yr_set_integer(RESOURCE_TYPE_ANIICON, module_object, "RESOURCE_TYPE_ANIICON");
4366
8.20k
  yr_set_integer(RESOURCE_TYPE_HTML, module_object, "RESOURCE_TYPE_HTML");
4367
8.20k
  yr_set_integer(
4368
8.20k
      RESOURCE_TYPE_MANIFEST, module_object, "RESOURCE_TYPE_MANIFEST");
4369
4370
8.20k
  yr_set_integer(
4371
8.20k
      IMAGE_DEBUG_TYPE_UNKNOWN, module_object, "IMAGE_DEBUG_TYPE_UNKNOWN");
4372
8.20k
  yr_set_integer(IMAGE_DEBUG_TYPE_COFF, module_object, "IMAGE_DEBUG_TYPE_COFF");
4373
8.20k
  yr_set_integer(
4374
8.20k
      IMAGE_DEBUG_TYPE_CODEVIEW, module_object, "IMAGE_DEBUG_TYPE_CODEVIEW");
4375
8.20k
  yr_set_integer(IMAGE_DEBUG_TYPE_FPO, module_object, "IMAGE_DEBUG_TYPE_FPO");
4376
8.20k
  yr_set_integer(IMAGE_DEBUG_TYPE_MISC, module_object, "IMAGE_DEBUG_TYPE_MISC");
4377
8.20k
  yr_set_integer(
4378
8.20k
      IMAGE_DEBUG_TYPE_EXCEPTION, module_object, "IMAGE_DEBUG_TYPE_EXCEPTION");
4379
8.20k
  yr_set_integer(
4380
8.20k
      IMAGE_DEBUG_TYPE_FIXUP, module_object, "IMAGE_DEBUG_TYPE_FIXUP");
4381
8.20k
  yr_set_integer(
4382
8.20k
      IMAGE_DEBUG_TYPE_OMAP_TO_SRC,
4383
8.20k
      module_object,
4384
8.20k
      "IMAGE_DEBUG_TYPE_OMAP_TO_SRC");
4385
8.20k
  yr_set_integer(
4386
8.20k
      IMAGE_DEBUG_TYPE_OMAP_FROM_SRC,
4387
8.20k
      module_object,
4388
8.20k
      "IMAGE_DEBUG_TYPE_OMAP_FROM_SRC");
4389
8.20k
  yr_set_integer(
4390
8.20k
      IMAGE_DEBUG_TYPE_BORLAND, module_object, "IMAGE_DEBUG_TYPE_BORLAND");
4391
8.20k
  yr_set_integer(
4392
8.20k
      IMAGE_DEBUG_TYPE_RESERVED10,
4393
8.20k
      module_object,
4394
8.20k
      "IMAGE_DEBUG_TYPE_RESERVED10");
4395
8.20k
  yr_set_integer(
4396
8.20k
      IMAGE_DEBUG_TYPE_CLSID, module_object, "IMAGE_DEBUG_TYPE_CLSID");
4397
8.20k
  yr_set_integer(
4398
8.20k
      IMAGE_DEBUG_TYPE_VC_FEATURE,
4399
8.20k
      module_object,
4400
8.20k
      "IMAGE_DEBUG_TYPE_VC_FEATURE");
4401
8.20k
  yr_set_integer(IMAGE_DEBUG_TYPE_POGO, module_object, "IMAGE_DEBUG_TYPE_POGO");
4402
8.20k
  yr_set_integer(
4403
8.20k
      IMAGE_DEBUG_TYPE_ILTCG, module_object, "IMAGE_DEBUG_TYPE_ILTCG");
4404
8.20k
  yr_set_integer(IMAGE_DEBUG_TYPE_MPX, module_object, "IMAGE_DEBUG_TYPE_MPX");
4405
8.20k
  yr_set_integer(
4406
8.20k
      IMAGE_DEBUG_TYPE_REPRO, module_object, "IMAGE_DEBUG_TYPE_REPRO");
4407
4408
8.20k
  yr_set_integer(0, module_object, "is_pe");
4409
4410
8.20k
  foreach_memory_block(iterator, block)
4411
8.20k
  {
4412
8.20k
    block_data = yr_fetch_block_data(block);
4413
4414
8.20k
    if (block_data == NULL)
4415
0
      continue;
4416
4417
8.20k
    pe_header = pe_get_header(block_data, block->size);
4418
4419
8.20k
    if (pe_header != NULL)
4420
6.89k
    {
4421
      // Ignore DLLs while scanning a process
4422
4423
6.89k
      if (!(context->flags & SCAN_FLAGS_PROCESS_MEMORY) ||
4424
0
          !(yr_le16toh(pe_header->FileHeader.Characteristics) & IMAGE_FILE_DLL))
4425
6.89k
      {
4426
6.89k
        pe = (PE*) yr_malloc(sizeof(PE));
4427
4428
6.89k
        if (pe == NULL)
4429
0
          return ERROR_INSUFFICIENT_MEMORY;
4430
4431
6.89k
        FAIL_ON_ERROR_WITH_CLEANUP(
4432
6.89k
            yr_hash_table_create(17, &pe->hash_table), yr_free(pe));
4433
4434
6.89k
        pe->data = block_data;
4435
6.89k
        pe->data_size = block->size;
4436
6.89k
        pe->header = pe_header;
4437
6.89k
        pe->object = module_object;
4438
6.89k
        pe->resources = 0;
4439
6.89k
        pe->version_infos = 0;
4440
6.89k
        pe->block_base = block->base;
4441
6.89k
        pe->csum_offset = ((const uint8_t*) &(pe_header->OptionalHeader) +
4442
6.89k
                           offsetof(IMAGE_OPTIONAL_HEADER32, CheckSum)) -
4443
6.89k
                          block_data;
4444
6.89k
        pe->has_calculated_checksum = false;
4445
6.89k
        pe->calculated_checksum = YR_UNDEFINED;
4446
4447
6.89k
        module_object->data = pe;
4448
4449
6.89k
        pe_parse_header(pe, block->base, context->flags);
4450
6.89k
        pe_parse_rich_signature(pe, block->base);
4451
6.89k
        pe_parse_debug_directory(pe);
4452
4453
#if defined(HAVE_LIBCRYPTO) && !defined(BORINGSSL)
4454
        pe_parse_certificates(pe);
4455
#endif
4456
4457
6.89k
        pe->imported_dlls = pe_parse_imports(pe);
4458
6.89k
        pe->delay_imported_dlls = pe_parse_delayed_imports(pe);
4459
6.89k
        pe_parse_exports(pe);
4460
4461
        // Block data returned by yr_fetch_block_data is only valid until the
4462
        // next block is fetched, so do not retain pointers into it beyond
4463
        // module_load.
4464
6.89k
        pe->data = NULL;
4465
6.89k
        pe->header = NULL;
4466
4467
6.89k
        break;
4468
6.89k
      }
4469
6.89k
    }
4470
8.20k
  }
4471
4472
8.20k
  return ERROR_SUCCESS;
4473
8.20k
}
4474
4475
void free_dlls(IMPORTED_DLL* dll)
4476
13.7k
{
4477
13.7k
  IMPORTED_DLL* next_dll = NULL;
4478
13.7k
  IMPORT_FUNCTION* func = NULL;
4479
13.7k
  IMPORT_FUNCTION* next_func = NULL;
4480
4481
67.9k
  while (dll)
4482
54.1k
  {
4483
54.1k
    if (dll->name)
4484
54.1k
      yr_free(dll->name);
4485
4486
54.1k
    func = dll->functions;
4487
4488
1.83M
    while (func)
4489
1.78M
    {
4490
1.78M
      if (func->name)
4491
1.78M
        yr_free(func->name);
4492
4493
1.78M
      next_func = func->next;
4494
1.78M
      yr_free(func);
4495
1.78M
      func = next_func;
4496
1.78M
    }
4497
4498
54.1k
    next_dll = dll->next;
4499
54.1k
    yr_free(dll);
4500
54.1k
    dll = next_dll;
4501
54.1k
  }
4502
13.7k
}
4503
4504
int module_unload(YR_OBJECT* module_object)
4505
8.20k
{
4506
8.20k
  PE* pe = (PE*) module_object->data;
4507
4508
8.20k
  if (pe == NULL)
4509
1.31k
    return ERROR_SUCCESS;
4510
4511
6.89k
  if (pe->hash_table != NULL)
4512
6.89k
    yr_hash_table_destroy(
4513
6.89k
        pe->hash_table, (YR_HASH_TABLE_FREE_VALUE_FUNC) yr_free);
4514
4515
6.89k
  free_dlls(pe->imported_dlls);
4516
6.89k
  free_dlls(pe->delay_imported_dlls);
4517
4518
6.89k
  yr_free(pe);
4519
4520
6.89k
  return ERROR_SUCCESS;
4521
8.20k
}