Coverage Report

Created: 2026-12-01 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/fwupd/libfwupdplugin/fu-pefile-firmware.c
Line
Count
Source
1
/*
2
 * Copyright 2023 Richard Hughes <richard@hughsie.com>
3
 *
4
 * SPDX-License-Identifier: LGPL-2.1-or-later
5
 */
6
7
14.3k
#define G_LOG_DOMAIN "FuFirmware"
8
9
#include "config.h"
10
11
#include "fu-byte-array.h"
12
#include "fu-bytes.h"
13
#include "fu-common.h"
14
#include "fu-composite-input-stream.h"
15
#include "fu-coswid-collection.h"
16
#include "fu-csv-firmware.h"
17
#include "fu-input-stream.h"
18
#include "fu-json-firmware.h"
19
#include "fu-linear-firmware.h"
20
#include "fu-partial-input-stream.h"
21
#include "fu-pefile-firmware.h"
22
#include "fu-pefile-struct.h"
23
#include "fu-pkcs7.h"
24
#include "fu-sbatlevel-section.h"
25
#include "fu-string.h"
26
#include "fu-x509-certificate.h"
27
28
/**
29
 * FuPefileFirmware:
30
 *
31
 * A PE file consists of a Microsoft MS-DOS stub, the PE signature, the COFF file header, and an
32
 * optional header, followed by section data.
33
 *
34
 * Documented:
35
 * https://learn.microsoft.com/en-gb/windows/win32/debug/pe-format
36
 */
37
38
typedef struct {
39
  gchar *authenticode_hash;
40
  guint16 subsystem_id;
41
  GPtrArray *certificates; /* element-type FuX509Certificate */
42
} FuPefileFirmwarePrivate;
43
44
3.46k
G_DEFINE_TYPE_WITH_PRIVATE(FuPefileFirmware, fu_pefile_firmware, FU_TYPE_FIRMWARE)
45
10.8k
#define GET_PRIVATE(o) (fu_pefile_firmware_get_instance_private(o))
46
47
64
#define FU_PEFILE_SECTION_ID_STRTAB_SIZE 16
48
49
3.34k
#define FU_PEFILE_FIRMWARE_SYMBOLS_MAX 1000000
50
51
0
#define FU_PEFILE_FIRMWARE_CERTIFICATES_MAX 32
52
53
static void
54
fu_pefile_firmware_export(FuFirmware *firmware,
55
        FuFirmwareExportFlags flags,
56
        FwupdJsonObject *json_object)
57
0
{
58
0
  FuPefileFirmware *self = FU_PEFILE_FIRMWARE(firmware);
59
0
  FuPefileFirmwarePrivate *priv = GET_PRIVATE(self);
60
0
  const gchar *subsystem_str = fu_coff_subsystem_to_string(priv->subsystem_id);
61
0
  if (priv->authenticode_hash != NULL)
62
0
    fwupd_json_object_add_string(json_object,
63
0
               "authenticode_hash",
64
0
               priv->authenticode_hash);
65
0
  if (subsystem_str != NULL)
66
0
    fwupd_json_object_add_string(json_object, "subsystem", subsystem_str);
67
0
  for (guint i = 0; i < priv->certificates->len; i++) {
68
0
    FuX509Certificate *crt = g_ptr_array_index(priv->certificates, i);
69
0
    g_autofree gchar *key = g_strdup_printf("certificate_%02u", i);
70
0
    const gchar *subject = fu_x509_certificate_get_subject(crt);
71
0
    if (subject != NULL)
72
0
      fwupd_json_object_add_string(json_object, key, subject);
73
0
  }
74
0
}
75
76
static gboolean
77
fu_pefile_firmware_validate(FuFirmware *firmware,
78
          FuInputStream *stream,
79
          gsize offset,
80
          GError **error)
81
3.45k
{
82
3.45k
  return fu_struct_pe_dos_header_validate_stream(stream, offset, error);
83
3.45k
}
84
85
typedef struct {
86
  gsize offset;
87
  gsize size;
88
  gchar *name;
89
} FuPefileFirmwareRegion;
90
91
static void
92
fu_pefile_firmware_add_region(GPtrArray *regions, const gchar *name, gsize offset, gsize size)
93
14.0k
{
94
14.0k
  FuPefileFirmwareRegion *r = g_new0(FuPefileFirmwareRegion, 1);
95
14.0k
  r->name = g_strdup(name);
96
14.0k
  r->offset = offset;
97
14.0k
  r->size = size;
98
14.0k
  g_ptr_array_add(regions, r);
99
14.0k
}
100
101
static void
102
fu_pefile_firmware_region_free(FuPefileFirmwareRegion *r)
103
14.0k
{
104
14.0k
  g_free(r->name);
105
14.0k
  g_free(r);
106
14.0k
}
107
108
static gint
109
fu_pefile_firmware_region_sort_cb(gconstpointer a, gconstpointer b)
110
16.6k
{
111
16.6k
  const FuPefileFirmwareRegion *r1 = *((const FuPefileFirmwareRegion **)a);
112
16.6k
  const FuPefileFirmwareRegion *r2 = *((const FuPefileFirmwareRegion **)b);
113
16.6k
  if (r1->offset < r2->offset)
114
2.34k
    return -1;
115
14.2k
  if (r1->offset > r2->offset)
116
5.22k
    return 1;
117
9.06k
  return 0;
118
14.2k
}
119
120
static gboolean
121
fu_pefile_firmware_parse_section(FuPefileFirmware *self,
122
         FuInputStream *stream,
123
         guint idx,
124
         gsize hdr_offset,
125
         gsize strtab_offset,
126
         GPtrArray *regions,
127
         FuFirmwareParseFlags flags,
128
         GError **error)
129
10.7k
{
130
10.7k
  g_autofree gchar *sect_id = NULL;
131
10.7k
  g_autofree gchar *sect_id_tmp = NULL;
132
10.7k
  g_autoptr(FuFirmware) img = NULL;
133
10.7k
  g_autoptr(FuStructPeCoffSection) st = NULL;
134
135
10.7k
  st = fu_struct_pe_coff_section_parse_stream(stream, hdr_offset, error);
136
10.7k
  if (st == NULL) {
137
105
    g_prefix_error_literal(error, "failed to read section: ");
138
105
    return FALSE;
139
105
  }
140
10.6k
  sect_id_tmp = fu_struct_pe_coff_section_get_name(st);
141
10.6k
  if (sect_id_tmp == NULL) {
142
3.69k
    sect_id = g_strdup_printf(".nul%04x", idx);
143
6.98k
  } else if (sect_id_tmp[0] == '/') {
144
260
    guint64 str_idx = 0x0;
145
260
    guint8 buf[FU_PEFILE_SECTION_ID_STRTAB_SIZE] = {0};
146
260
    gsize read_offset;
147
148
260
    if (!fu_strtoull(sect_id_tmp + 1,
149
260
         &str_idx,
150
260
         0,
151
260
         G_MAXUINT32,
152
260
         FU_INTEGER_BASE_10,
153
260
         error)) {
154
25
      g_prefix_error(error, "failed to parse section ID '%s': ", sect_id_tmp + 1);
155
25
      return FALSE;
156
25
    }
157
158
    /* calculate string table offset with overflow checking */
159
235
    read_offset = strtab_offset;
160
235
    if (!fu_size_checked_inc(&read_offset, str_idx, error)) {
161
0
      g_prefix_error(error, "string table offset overflow for section %u: ", idx);
162
0
      return FALSE;
163
0
    }
164
235
    if (!fu_input_stream_read_safe(stream,
165
235
                 buf,
166
235
                 sizeof(buf),
167
235
                 0x0,
168
235
                 read_offset, /* seek */
169
235
                 sizeof(buf),
170
235
                 error))
171
8
      return FALSE;
172
227
    sect_id = fu_strsafe((const gchar *)buf, sizeof(buf));
173
227
    if (sect_id == NULL) {
174
1
      g_set_error_literal(error,
175
1
              FWUPD_ERROR,
176
1
              FWUPD_ERROR_INVALID_DATA,
177
1
              "no section name");
178
1
      return FALSE;
179
1
    }
180
6.72k
  } else {
181
6.72k
    sect_id = g_steal_pointer(&sect_id_tmp);
182
6.72k
  }
183
184
  /* create new firmware */
185
10.6k
  if (g_strcmp0(sect_id, ".sbom") == 0) {
186
1.81k
    img = fu_coswid_collection_new();
187
8.82k
  } else if (g_strcmp0(sect_id, ".sbat") == 0 || g_strcmp0(sect_id, ".sbata") == 0 ||
188
6.23k
       g_strcmp0(sect_id, ".sbatl") == 0) {
189
2.83k
    img = fu_csv_firmware_new();
190
2.83k
    fu_csv_firmware_add_column_id(FU_CSV_FIRMWARE(img), "$id");
191
2.83k
    fu_csv_firmware_add_column_id(FU_CSV_FIRMWARE(img), "$version_raw");
192
2.83k
    fu_csv_firmware_add_column_id(FU_CSV_FIRMWARE(img), "vendor_name");
193
2.83k
    fu_csv_firmware_add_column_id(FU_CSV_FIRMWARE(img), "vendor_package_name");
194
2.83k
    fu_csv_firmware_add_column_id(FU_CSV_FIRMWARE(img), "$version");
195
2.83k
    fu_csv_firmware_add_column_id(FU_CSV_FIRMWARE(img), "vendor_url");
196
2.83k
    fu_csv_firmware_set_write_column_ids(FU_CSV_FIRMWARE(img), FALSE);
197
5.99k
  } else if (g_strcmp0(sect_id, ".sbatlevel") == 0) {
198
171
    img = fu_sbatlevel_section_new();
199
5.82k
  } else if (g_strcmp0(sect_id, ".pkgnote") == 0) {
200
183
    img = fu_json_firmware_new();
201
5.63k
  } else {
202
5.63k
    img = fu_firmware_new();
203
5.63k
  }
204
10.6k
  fu_firmware_set_id(img, sect_id);
205
10.6k
  fu_firmware_set_idx(img, idx);
206
207
  /* add data */
208
10.6k
  if (fu_struct_pe_coff_section_get_virtual_size(st) > 0) {
209
8.88k
    guint32 sect_offset = fu_struct_pe_coff_section_get_pointer_to_raw_data(st);
210
8.88k
    guint32 sect_size = fu_struct_pe_coff_section_get_virtual_size(st);
211
8.88k
    g_autoptr(FuInputStream) img_stream = NULL;
212
213
    /* use the raw data size if the section is compressed */
214
8.88k
    if (fu_struct_pe_coff_section_get_virtual_size(st) >
215
8.88k
        fu_struct_pe_coff_section_get_size_of_raw_data(st)) {
216
7.81k
      g_debug("virtual size 0x%x bigger than raw data, truncating to 0x%x",
217
7.81k
        sect_size,
218
7.81k
        fu_struct_pe_coff_section_get_size_of_raw_data(st));
219
7.81k
      sect_size = fu_struct_pe_coff_section_get_size_of_raw_data(st);
220
7.81k
    }
221
222
8.88k
    fu_firmware_set_offset(img, sect_offset);
223
8.88k
    img_stream = fu_partial_input_stream_new(stream, sect_offset, sect_size, error);
224
8.88k
    if (img_stream == NULL) {
225
628
      g_prefix_error_literal(error, "failed to cut raw PE data: ");
226
628
      return FALSE;
227
628
    }
228
8.25k
    if (!fu_firmware_parse_stream(img, img_stream, 0x0, flags, error)) {
229
1.72k
      g_prefix_error(error, "failed to parse raw data %s: ", sect_id);
230
1.72k
      return FALSE;
231
1.72k
    }
232
233
    /* add region for Authenticode checksum */
234
6.53k
    fu_pefile_firmware_add_region(regions,
235
6.53k
                sect_id,
236
6.53k
                sect_offset,
237
6.53k
                fu_struct_pe_coff_section_get_size_of_raw_data(st));
238
6.53k
  }
239
240
  /* add image */
241
8.29k
  if (!fu_firmware_add_image(FU_FIRMWARE(self), img, error)) {
242
2
    g_prefix_error(error, "failed to add %s: ", sect_id);
243
2
    return FALSE;
244
2
  }
245
246
  /* success */
247
8.28k
  return TRUE;
248
8.29k
}
249
250
static gboolean
251
fu_pefile_firmware_parse_certificate(FuPefileFirmware *self,
252
             FuInputStream *stream,
253
             gsize offset,
254
             gsize length,
255
             FuFirmwareParseFlags flags,
256
             GError **error)
257
0
{
258
0
  FuPefileFirmwarePrivate *priv = GET_PRIVATE(self);
259
0
  g_autoptr(FuInputStream) partial_stream = NULL;
260
0
  g_autoptr(FuPkcs7) pkcs7 = fu_pkcs7_new();
261
0
  g_autoptr(GPtrArray) imgs = NULL;
262
263
0
  partial_stream = fu_partial_input_stream_new(stream, offset, length, error);
264
0
  if (partial_stream == NULL)
265
0
    return FALSE;
266
0
  if (!fu_firmware_parse_stream(FU_FIRMWARE(pkcs7), partial_stream, 0x0, flags, error))
267
0
    return FALSE;
268
0
  imgs = fu_firmware_get_images(FU_FIRMWARE(pkcs7));
269
0
  for (guint i = 0; i < imgs->len; i++) {
270
0
    FuFirmware *img = g_ptr_array_index(imgs, i);
271
0
    if (priv->certificates->len >= FU_PEFILE_FIRMWARE_CERTIFICATES_MAX) {
272
0
      g_set_error(error,
273
0
            FWUPD_ERROR,
274
0
            FWUPD_ERROR_INVALID_DATA,
275
0
            "too many certificates, limit is %u",
276
0
            (guint)FU_PEFILE_FIRMWARE_CERTIFICATES_MAX);
277
0
      return FALSE;
278
0
    }
279
0
    g_ptr_array_add(priv->certificates, g_object_ref(img));
280
0
  }
281
282
  /* success */
283
0
  return TRUE;
284
0
}
285
286
/* the attribute certificate table is a list of 8-byte aligned WIN_CERTIFICATE entries */
287
static gboolean
288
fu_pefile_firmware_parse_certificates(FuPefileFirmware *self,
289
              FuInputStream *stream,
290
              gsize offset,
291
              gsize size,
292
              FuFirmwareParseFlags flags,
293
              GError **error)
294
2
{
295
2
  gsize offset_end = offset;
296
297
2
  if (!fu_size_checked_inc(&offset_end, size, error))
298
0
    return FALSE;
299
2
  while (offset + FU_STRUCT_PE_WIN_CERTIFICATE_SIZE <= offset_end) {
300
2
    gsize length;
301
2
    g_autoptr(FuStructPeWinCertificate) st = NULL;
302
303
2
    st = fu_struct_pe_win_certificate_parse_stream(stream, offset, error);
304
2
    if (st == NULL)
305
0
      return FALSE;
306
2
    length = fu_struct_pe_win_certificate_get_length(st);
307
2
    if (length < FU_STRUCT_PE_WIN_CERTIFICATE_SIZE || length > offset_end - offset) {
308
2
      g_set_error(error,
309
2
            FWUPD_ERROR,
310
2
            FWUPD_ERROR_INVALID_DATA,
311
2
            "invalid WIN_CERTIFICATE length 0x%x",
312
2
            (guint)length);
313
2
      return FALSE;
314
2
    }
315
0
    if (fu_struct_pe_win_certificate_get_certificate_type(st) ==
316
0
        FU_PE_WIN_CERTIFICATE_TYPE_PKCS_SIGNED_DATA) {
317
0
      if (!fu_pefile_firmware_parse_certificate(
318
0
        self,
319
0
        stream,
320
0
        offset + FU_STRUCT_PE_WIN_CERTIFICATE_SIZE,
321
0
        length - FU_STRUCT_PE_WIN_CERTIFICATE_SIZE,
322
0
        flags,
323
0
        error))
324
0
        return FALSE;
325
0
    }
326
0
    if (!fu_size_checked_inc(&offset, fu_common_align_up(length, 3), error))
327
0
      return FALSE;
328
0
  }
329
330
  /* success */
331
0
  return TRUE;
332
2
}
333
334
static gboolean
335
fu_pefile_firmware_parse(FuFirmware *firmware,
336
       FuInputStream *stream,
337
       FuFirmwareParseFlags flags,
338
       GError **error)
339
3.41k
{
340
3.41k
  FuPefileFirmware *self = FU_PEFILE_FIRMWARE(firmware);
341
3.41k
  FuPefileFirmwarePrivate *priv = GET_PRIVATE(self);
342
3.41k
  guint32 cert_table_offset = 0;
343
3.41k
  guint32 cert_table_sz = 0;
344
3.41k
  gsize offset = 0;
345
3.41k
  gsize region_end;
346
3.41k
  gsize streamsz = 0;
347
3.41k
  gsize strtab_offset;
348
3.41k
  gsize subsystem_offset;
349
3.41k
  gsize symbols_sz_safe = 0;
350
3.41k
  guint32 nr_sections;
351
3.41k
  guint32 nr_symbols;
352
3.41k
  guint64 symbols_sz;
353
3.41k
  g_autoptr(FuStructPeCoffFileHeader) st_coff = NULL;
354
3.41k
  g_autoptr(FuStructPeDosHeader) st_doshdr = NULL;
355
3.41k
  g_autoptr(GPtrArray) regions = NULL;
356
3.41k
  g_autoptr(FuInputStream) composite_stream = fu_composite_input_stream_new();
357
358
  /* get size */
359
3.41k
  if (!fu_input_stream_size(stream, &streamsz, error))
360
0
    return FALSE;
361
362
  /* parse the DOS header to get the COFF header */
363
3.41k
  st_doshdr = fu_struct_pe_dos_header_parse_stream(stream, offset, error);
364
3.41k
  if (st_doshdr == NULL) {
365
0
    g_prefix_error_literal(error, "failed to read DOS header: ");
366
0
    return FALSE;
367
0
  }
368
3.41k
  if (!fu_size_checked_inc(&offset, fu_struct_pe_dos_header_get_lfanew(st_doshdr), error))
369
0
    return FALSE;
370
3.41k
  st_coff = fu_struct_pe_coff_file_header_parse_stream(stream, offset, error);
371
3.41k
  if (st_coff == NULL) {
372
40
    g_prefix_error_literal(error, "failed to read COFF header: ");
373
40
    return FALSE;
374
40
  }
375
3.37k
  if (!fu_size_checked_inc(&offset, st_coff->buf->len, error)) {
376
0
    g_prefix_error_literal(error, "header offset overflow: ");
377
0
    return FALSE;
378
0
  }
379
380
3.37k
  regions = g_ptr_array_new_with_free_func((GDestroyNotify)fu_pefile_firmware_region_free);
381
382
  /* 1st Authenticode region */
383
3.37k
  region_end = offset;
384
3.37k
  if (!fu_size_checked_inc(&region_end,
385
3.37k
         FU_STRUCT_PE_COFF_OPTIONAL_HEADER64_OFFSET_CHECKSUM,
386
3.37k
         error))
387
0
    return FALSE;
388
3.37k
  fu_pefile_firmware_add_region(regions, "pre-cksum", 0x0, region_end);
389
390
  /* 2nd Authenticode region */
391
3.37k
  subsystem_offset = offset;
392
3.37k
  if (!fu_size_checked_inc(&subsystem_offset,
393
3.37k
         FU_STRUCT_PE_COFF_OPTIONAL_HEADER64_OFFSET_SUBSYSTEM,
394
3.37k
         error))
395
0
    return FALSE;
396
3.37k
  if (!fu_input_stream_read_safe(stream,
397
3.37k
               (guint8 *)&priv->subsystem_id,
398
3.37k
               sizeof(priv->subsystem_id),
399
3.37k
               0x0,
400
3.37k
               subsystem_offset, /* seek */
401
3.37k
               sizeof(priv->subsystem_id),
402
3.37k
               error))
403
1
    return FALSE;
404
3.37k
  fu_pefile_firmware_add_region(
405
3.37k
      regions,
406
3.37k
      "chksum->cert-table",
407
3.37k
      subsystem_offset,
408
3.37k
      FU_STRUCT_PE_COFF_OPTIONAL_HEADER64_OFFSET_CERTIFICATE_TABLE -
409
3.37k
    FU_STRUCT_PE_COFF_OPTIONAL_HEADER64_OFFSET_SUBSYSTEM); /* end */
410
411
  /* verify optional extra header */
412
3.37k
  if (fu_struct_pe_coff_file_header_get_size_of_optional_header(st_coff) > 0) {
413
324
    g_autoptr(FuStructPeCoffOptionalHeader64) st_opt =
414
324
        fu_struct_pe_coff_optional_header64_parse_stream(stream, offset, error);
415
324
    if (st_opt == NULL) {
416
11
      g_prefix_error_literal(error, "failed to read optional header: ");
417
11
      return FALSE;
418
11
    }
419
420
    /* 3rd Authenticode region */
421
313
    if (fu_struct_pe_coff_optional_header64_get_size_of_headers(st_opt) > 0) {
422
214
      gsize debug_table_offset = offset;
423
214
      gsize size_of_headers =
424
214
          fu_struct_pe_coff_optional_header64_get_size_of_headers(st_opt);
425
426
214
      if (!fu_size_checked_inc(
427
214
        &debug_table_offset,
428
214
        FU_STRUCT_PE_COFF_OPTIONAL_HEADER64_OFFSET_DEBUG_TABLE,
429
214
        error))
430
0
        return FALSE;
431
432
214
      if (size_of_headers < debug_table_offset) {
433
10
        g_set_error(error,
434
10
              FWUPD_ERROR,
435
10
              FWUPD_ERROR_INVALID_DATA,
436
10
              "header size too small: 0x%x < 0x%x",
437
10
              (guint)size_of_headers,
438
10
              (guint)debug_table_offset);
439
10
        return FALSE;
440
10
      }
441
442
204
      fu_pefile_firmware_add_region(regions,
443
204
                  "cert-table->end-of-headers",
444
204
                  debug_table_offset,
445
204
                  size_of_headers - debug_table_offset);
446
204
    }
447
448
    /* 4th Authenticode region */
449
303
    cert_table_offset =
450
303
        fu_struct_pe_coff_optional_header64_get_certificate_table(st_opt);
451
303
    cert_table_sz =
452
303
        fu_struct_pe_coff_optional_header64_get_size_of_certificate_table(st_opt);
453
454
303
    if (!fu_size_checked_inc(
455
303
      &offset,
456
303
      fu_struct_pe_coff_file_header_get_size_of_optional_header(st_coff),
457
303
      error))
458
0
      return FALSE;
459
303
  }
460
461
  /* read number of sections */
462
3.34k
  nr_sections = fu_struct_pe_coff_file_header_get_number_of_sections(st_coff);
463
3.34k
  if (nr_sections == 0) {
464
1
    g_set_error_literal(error,
465
1
            FWUPD_ERROR,
466
1
            FWUPD_ERROR_INVALID_FILE,
467
1
            "invalid number of sections");
468
1
    return FALSE;
469
1
  }
470
3.34k
  strtab_offset = fu_struct_pe_coff_file_header_get_pointer_to_symbol_table(st_coff);
471
472
3.34k
  nr_symbols = fu_struct_pe_coff_file_header_get_number_of_symbols(st_coff);
473
3.34k
  if (nr_symbols > FU_PEFILE_FIRMWARE_SYMBOLS_MAX) {
474
42
    g_set_error(error,
475
42
          FWUPD_ERROR,
476
42
          FWUPD_ERROR_INVALID_DATA,
477
42
          "excessive number of symbols: %u",
478
42
          nr_symbols);
479
42
    return FALSE;
480
42
  }
481
3.30k
  symbols_sz = (guint64)nr_symbols * FU_STRUCT_PE_COFF_SYMBOL_SIZE;
482
3.30k
  if (!fu_size_from_uint64(symbols_sz, &symbols_sz_safe, error))
483
0
    return FALSE;
484
3.30k
  if (!fu_size_checked_inc(&strtab_offset, symbols_sz_safe, error))
485
0
    return FALSE;
486
487
  /* read out each section */
488
11.5k
  for (guint idx = 0; idx < nr_sections; idx++) {
489
10.7k
    if (!fu_pefile_firmware_parse_section(self,
490
10.7k
                  stream,
491
10.7k
                  idx,
492
10.7k
                  offset,
493
10.7k
                  strtab_offset,
494
10.7k
                  regions,
495
10.7k
                  flags,
496
10.7k
                  error)) {
497
2.49k
      g_prefix_error(error, "failed to read section 0x%x: ", idx);
498
2.49k
      return FALSE;
499
2.49k
    }
500
8.28k
    if (!fu_size_checked_inc(&offset, FU_STRUCT_PE_COFF_SECTION_SIZE, error)) {
501
0
      g_prefix_error(error, "section %u offset overflow: ", idx);
502
0
      return FALSE;
503
0
    }
504
8.28k
  }
505
506
  /* make sure ordered by address */
507
811
  g_ptr_array_sort(regions, fu_pefile_firmware_region_sort_cb);
508
509
  /* for the data at the end of the image */
510
811
  if (regions->len > 0) {
511
811
    FuPefileFirmwareRegion *r = g_ptr_array_index(regions, regions->len - 1);
512
811
    gsize offset_end = r->offset;
513
811
    gsize end_with_cert;
514
515
    /* check for overflow when calculating region end */
516
811
    if (!fu_size_checked_inc(&offset_end, r->size, error))
517
0
      return FALSE;
518
519
    /* sanity check */
520
811
    if (offset_end > streamsz) {
521
164
      g_set_error(error,
522
164
            FWUPD_ERROR,
523
164
            FWUPD_ERROR_INVALID_DATA,
524
164
            "section extends beyond file boundary: 0x%x > 0x%x",
525
164
            (guint)offset_end,
526
164
            (guint)streamsz);
527
164
      return FALSE;
528
164
    }
529
530
    /* check for overflow when adding certificate table size */
531
647
    end_with_cert = offset_end;
532
647
    if (!fu_size_checked_inc(&end_with_cert, cert_table_sz, error))
533
0
      return FALSE;
534
535
647
    if (end_with_cert > streamsz) {
536
49
      g_set_error(error,
537
49
            FWUPD_ERROR,
538
49
            FWUPD_ERROR_INVALID_DATA,
539
49
            "certificate table extends beyond file: 0x%x + 0x%x > 0x%x",
540
49
            (guint)offset_end,
541
49
            cert_table_sz,
542
49
            (guint)streamsz);
543
49
      return FALSE;
544
49
    }
545
598
    fu_pefile_firmware_add_region(regions,
546
598
                "tabledata->cert-table",
547
598
                offset_end,
548
598
                streamsz - end_with_cert);
549
598
  }
550
551
  /* calculate the checksum we would find in the dbx */
552
6.70k
  for (guint i = 0; i < regions->len; i++) {
553
6.15k
    FuPefileFirmwareRegion *r = g_ptr_array_index(regions, i);
554
6.15k
    g_autoptr(FuInputStream) partial_stream = NULL;
555
556
6.15k
    if (r->size == 0)
557
184
      continue;
558
5.96k
    g_debug("authenticode region %s: 0x%04x -> 0x%04x [0x%04x]",
559
5.96k
      r->name,
560
5.96k
      (guint)r->offset,
561
5.96k
      (guint)(r->offset + r->size),
562
5.96k
      (guint)r->size);
563
5.96k
    partial_stream = fu_partial_input_stream_new(stream, r->offset, r->size, error);
564
5.96k
    if (partial_stream == NULL) {
565
48
      g_prefix_error_literal(error, "failed to cut Authenticode region: ");
566
48
      return FALSE;
567
48
    }
568
5.91k
    if (!fu_composite_input_stream_add_partial_stream(
569
5.91k
      FU_COMPOSITE_INPUT_STREAM(composite_stream),
570
5.91k
      FU_PARTIAL_INPUT_STREAM(partial_stream),
571
5.91k
      error))
572
0
      return FALSE;
573
5.91k
  }
574
550
  priv->authenticode_hash =
575
550
      fu_input_stream_compute_checksum(composite_stream, G_CHECKSUM_SHA256, error);
576
550
  if (priv->authenticode_hash == NULL)
577
0
    return FALSE;
578
579
  /* the X.509 certificates used to sign the image, which are optional as the image may not
580
   * be signed, or we may not have support for parsing PKCS#7 */
581
550
  if (cert_table_offset != 0 && cert_table_sz != 0) {
582
2
    g_autoptr(GError) error_local = NULL;
583
2
    if (!fu_pefile_firmware_parse_certificates(self,
584
2
                 stream,
585
2
                 cert_table_offset,
586
2
                 cert_table_sz,
587
2
                 flags,
588
2
                 &error_local)) {
589
2
      g_debug("ignoring certificate table: %s", error_local->message);
590
2
      g_ptr_array_set_size(priv->certificates, 0);
591
2
    }
592
2
  }
593
594
  /* success */
595
550
  return TRUE;
596
550
}
597
598
typedef struct {
599
  GByteArray *buf;
600
  gchar *id;
601
  gsize offset;
602
  gsize bufsz_aligned;
603
} FuPefileSection;
604
605
static void
606
fu_pefile_firmware_section_free(FuPefileSection *section)
607
3.04k
{
608
3.04k
  if (section->buf != NULL)
609
2.97k
    g_byte_array_unref(section->buf);
610
3.04k
  g_free(section->id);
611
3.04k
  g_free(section);
612
3.04k
}
613
614
G_DEFINE_AUTOPTR_CLEANUP_FUNC(FuPefileSection, fu_pefile_firmware_section_free)
615
616
/* a single WIN_CERTIFICATE containing a certs-only PKCS#7 bundle, padded to 8 bytes */
617
static GByteArray *
618
fu_pefile_firmware_write_certificates(FuPefileFirmware *self, GError **error)
619
0
{
620
0
  FuPefileFirmwarePrivate *priv = GET_PRIVATE(self);
621
0
  g_autoptr(FuPkcs7) pkcs7 = fu_pkcs7_new();
622
0
  g_autoptr(FuStructPeWinCertificate) st = fu_struct_pe_win_certificate_new();
623
0
  g_autoptr(GByteArray) buf = NULL;
624
625
0
  if (priv->certificates->len > FU_PEFILE_FIRMWARE_CERTIFICATES_MAX) {
626
0
    g_set_error(error,
627
0
          FWUPD_ERROR,
628
0
          FWUPD_ERROR_INVALID_DATA,
629
0
          "too many certificates, limit is %u",
630
0
          (guint)FU_PEFILE_FIRMWARE_CERTIFICATES_MAX);
631
0
    return NULL;
632
0
  }
633
0
  for (guint i = 0; i < priv->certificates->len; i++) {
634
0
    FuFirmware *crt = g_ptr_array_index(priv->certificates, i);
635
0
    if (!fu_firmware_add_image(FU_FIRMWARE(pkcs7), crt, error))
636
0
      return NULL;
637
0
  }
638
0
  buf = fu_firmware_write_array(FU_FIRMWARE(pkcs7), error);
639
0
  if (buf == NULL)
640
0
    return NULL;
641
0
  fu_struct_pe_win_certificate_set_length(st, st->buf->len + buf->len);
642
0
  fu_byte_array_append_array(st->buf, buf);
643
644
  /* dwLength does not include the padding */
645
0
  fu_byte_array_set_size(st->buf, fu_common_align_up(st->buf->len, 3), 0x0);
646
0
  return g_steal_pointer(&st->buf);
647
0
}
648
649
static GByteArray *
650
fu_pefile_firmware_write(FuFirmware *firmware, GError **error)
651
550
{
652
550
  FuPefileFirmware *self = FU_PEFILE_FIRMWARE(firmware);
653
550
  FuPefileFirmwarePrivate *priv = GET_PRIVATE(self);
654
550
  gsize offset = 0;
655
550
  g_autoptr(GPtrArray) imgs = fu_firmware_get_images(firmware);
656
550
  g_autoptr(FuStructPeDosHeader) st = fu_struct_pe_dos_header_new();
657
550
  g_autoptr(FuStructPeCoffFileHeader) st_hdr = fu_struct_pe_coff_file_header_new();
658
550
  g_autoptr(FuStructPeCoffOptionalHeader64) st_opt =
659
550
      fu_struct_pe_coff_optional_header64_new();
660
550
  gsize strtab_sz = 0;
661
550
  g_autoptr(GByteArray) cert_table = NULL;
662
550
  g_autoptr(GByteArray) strtab = g_byte_array_new();
663
550
  g_autoptr(GPtrArray) sections =
664
550
      g_ptr_array_new_with_free_func((GDestroyNotify)fu_pefile_firmware_section_free);
665
666
  /* calculate the offset for each of the sections */
667
550
  if (!fu_size_checked_inc(&offset, st->buf->len, error))
668
0
    return NULL;
669
550
  if (!fu_size_checked_inc(&offset, st_hdr->buf->len, error))
670
0
    return NULL;
671
550
  if (!fu_size_checked_inc(&offset, st_opt->buf->len, error))
672
0
    return NULL;
673
550
  if (!fu_size_checked_inc_product(&offset, FU_STRUCT_PE_COFF_SECTION_SIZE, imgs->len, error))
674
0
    return NULL;
675
3.52k
  for (guint i = 0; i < imgs->len; i++) {
676
3.04k
    g_autoptr(FuPefileSection) section = g_new0(FuPefileSection, 1);
677
3.04k
    FuFirmware *img = g_ptr_array_index(imgs, i);
678
679
3.04k
    section->offset = offset;
680
3.04k
    section->buf = fu_firmware_write_array(img, error);
681
3.04k
    if (section->buf == NULL)
682
70
      return NULL;
683
2.97k
    if (section->buf->len == 0) {
684
521
      g_debug("skipping zero length section %u", i);
685
521
      continue;
686
521
    }
687
    /* the spec explicitly requires a "NUL-terminated UTF-8 string" */
688
2.45k
    if (g_strcmp0(fu_firmware_get_id(img), ".pkgnote") == 0)
689
33
      fu_byte_array_append_uint8(section->buf, 0);
690
2.45k
    section->id = g_strdup(fu_firmware_get_id(img));
691
2.45k
    section->bufsz_aligned = fu_common_align_up(section->buf->len, 4);
692
2.45k
    if (!fu_size_checked_inc(&offset, section->bufsz_aligned, error))
693
0
      return NULL;
694
2.45k
    if (section->id != NULL && strlen(section->id) > 8) {
695
22
      if (!fu_size_checked_inc(&strtab_sz,
696
22
             FU_PEFILE_SECTION_ID_STRTAB_SIZE,
697
22
             error))
698
0
        return NULL;
699
22
    }
700
2.45k
    g_ptr_array_add(sections, g_steal_pointer(&section));
701
2.45k
  }
702
703
  /* export_table -> architecture_table */
704
480
  fu_struct_pe_coff_optional_header64_set_number_of_rva_and_sizes(st_opt, 7);
705
706
  /* attribute certificate table comes after the string table, 8-byte aligned */
707
480
  if (priv->certificates->len > 0) {
708
0
    gsize cert_table_offset = offset;
709
0
    if (!fu_size_checked_inc(&cert_table_offset, strtab_sz, error))
710
0
      return NULL;
711
0
    cert_table_offset = fu_common_align_up(cert_table_offset, 3);
712
0
    cert_table = fu_pefile_firmware_write_certificates(self, error);
713
0
    if (cert_table == NULL)
714
0
      return NULL;
715
0
    if (cert_table_offset > G_MAXUINT32 || cert_table->len > G_MAXUINT32) {
716
0
      g_set_error_literal(error,
717
0
              FWUPD_ERROR,
718
0
              FWUPD_ERROR_INVALID_DATA,
719
0
              "certificate table offset too large");
720
0
      return NULL;
721
0
    }
722
0
    fu_struct_pe_coff_optional_header64_set_certificate_table(st_opt,
723
0
                    cert_table_offset);
724
0
    fu_struct_pe_coff_optional_header64_set_size_of_certificate_table(st_opt,
725
0
                      cert_table->len);
726
0
  }
727
728
  /* COFF file header */
729
480
  fu_struct_pe_coff_file_header_set_size_of_optional_header(st_hdr, st_opt->buf->len);
730
480
  fu_struct_pe_coff_file_header_set_number_of_sections(st_hdr, sections->len);
731
480
  fu_struct_pe_coff_file_header_set_pointer_to_symbol_table(st_hdr, offset);
732
480
  fu_byte_array_append_array(st->buf, st_hdr->buf);
733
480
  fu_byte_array_append_array(st->buf, st_opt->buf);
734
735
  /* add sections */
736
2.35k
  for (guint i = 0; i < sections->len; i++) {
737
1.87k
    FuPefileSection *section = g_ptr_array_index(sections, i);
738
1.87k
    g_autoptr(FuStructPeCoffSection) st_sect = fu_struct_pe_coff_section_new();
739
740
1.87k
    fu_struct_pe_coff_section_set_size_of_raw_data(st_sect, section->buf->len);
741
1.87k
    fu_struct_pe_coff_section_set_virtual_address(st_sect, 0x0);
742
1.87k
    fu_struct_pe_coff_section_set_virtual_size(st_sect, section->bufsz_aligned);
743
1.87k
    fu_struct_pe_coff_section_set_pointer_to_raw_data(st_sect, section->offset);
744
745
    /* set the name directly, or add to the string table */
746
1.87k
    if (section->id == NULL) {
747
0
      g_set_error(error,
748
0
            FWUPD_ERROR,
749
0
            FWUPD_ERROR_INVALID_DATA,
750
0
            "image %u has no ID",
751
0
            i);
752
0
      return NULL;
753
0
    }
754
1.87k
    if (strlen(section->id) <= 8) {
755
1.85k
      if (!fu_struct_pe_coff_section_set_name(st_sect, section->id, error))
756
0
        return NULL;
757
1.85k
    } else {
758
21
      g_autofree gchar *name_tmp = g_strdup_printf("/%u", strtab->len);
759
21
      g_autoptr(GByteArray) strtab_buf = g_byte_array_new();
760
761
21
      if (!fu_struct_pe_coff_section_set_name(st_sect, name_tmp, error))
762
0
        return NULL;
763
764
      /* create a byte buffer of exactly the correct chunk size */
765
21
      g_byte_array_append(strtab_buf,
766
21
              (const guint8 *)section->id,
767
21
              strlen(section->id));
768
21
      if (strtab_buf->len > FU_PEFILE_SECTION_ID_STRTAB_SIZE) {
769
0
        g_set_error(error,
770
0
              FWUPD_ERROR,
771
0
              FWUPD_ERROR_INVALID_DATA,
772
0
              "image ID %s is too long",
773
0
              section->id);
774
0
        return NULL;
775
0
      }
776
21
      fu_byte_array_set_size(strtab_buf, FU_PEFILE_SECTION_ID_STRTAB_SIZE, 0x0);
777
21
      g_byte_array_append(strtab, strtab_buf->data, strtab_buf->len);
778
21
    }
779
1.87k
    fu_byte_array_append_array(st->buf, st_sect->buf);
780
1.87k
  }
781
782
  /* add the section data itself */
783
2.35k
  for (guint i = 0; i < sections->len; i++) {
784
1.87k
    FuPefileSection *section = g_ptr_array_index(sections, i);
785
1.87k
    fu_byte_array_set_size(section->buf, section->bufsz_aligned, 0xFF);
786
1.87k
    fu_byte_array_append_array(st->buf, section->buf);
787
1.87k
  }
788
789
  /* string table */
790
480
  g_byte_array_append(st->buf, strtab->data, strtab->len);
791
792
  /* attribute certificate table comes last */
793
480
  if (cert_table != NULL) {
794
0
    fu_byte_array_set_size(st->buf, fu_common_align_up(st->buf->len, 3), 0x0);
795
0
    fu_byte_array_append_array(st->buf, cert_table);
796
0
  }
797
798
  /* success */
799
480
  return g_steal_pointer(&st->buf);
800
480
}
801
802
static gchar *
803
fu_pefile_firmware_get_checksum(FuFirmware *firmware, GChecksumType csum_kind, GError **error)
804
0
{
805
0
  FuPefileFirmware *self = FU_PEFILE_FIRMWARE(firmware);
806
0
  FuPefileFirmwarePrivate *priv = GET_PRIVATE(self);
807
0
  if (csum_kind != G_CHECKSUM_SHA256) {
808
0
    g_set_error_literal(error,
809
0
            FWUPD_ERROR,
810
0
            FWUPD_ERROR_NOT_SUPPORTED,
811
0
            "Authenticode only supports SHA256");
812
0
    return NULL;
813
0
  }
814
0
  if (priv->authenticode_hash == NULL) {
815
0
    g_set_error_literal(error,
816
0
            FWUPD_ERROR,
817
0
            FWUPD_ERROR_INVALID_DATA,
818
0
            "Authenticode checksum not set");
819
0
    return NULL;
820
0
  }
821
0
  return g_strdup(priv->authenticode_hash);
822
0
}
823
824
/**
825
 * fu_pefile_firmware_get_certificates:
826
 * @self: a #FuPefileFirmware
827
 *
828
 * Gets the X.509 certificates included in the Authenticode signatures, typically the signer
829
 * certificate and any intermediate certificates.
830
 *
831
 * NOTE: nested signatures are not included, and no verification of the signature is performed.
832
 *
833
 * Returns: (transfer container) (element-type FuX509Certificate): certificates
834
 **/
835
GPtrArray *
836
fu_pefile_firmware_get_certificates(FuPefileFirmware *self)
837
0
{
838
0
  FuPefileFirmwarePrivate *priv = GET_PRIVATE(self);
839
0
  g_return_val_if_fail(FU_IS_PEFILE_FIRMWARE(self), NULL);
840
0
  return g_ptr_array_ref(priv->certificates);
841
0
}
842
843
/**
844
 * fu_pefile_firmware_add_certificate:
845
 * @self: a #FuPefileFirmware
846
 * @crt: a #FuX509Certificate
847
 *
848
 * Adds an X.509 certificate to be included in the Authenticode signature when writing.
849
 *
850
 * NOTE: the image is not actually signed, the certificates are written as a certs-only PKCS#7
851
 * bundle.
852
 **/
853
void
854
fu_pefile_firmware_add_certificate(FuPefileFirmware *self, FuX509Certificate *crt)
855
0
{
856
0
  FuPefileFirmwarePrivate *priv = GET_PRIVATE(self);
857
0
  g_return_if_fail(FU_IS_PEFILE_FIRMWARE(self));
858
0
  g_return_if_fail(FU_IS_X509_CERTIFICATE(crt));
859
0
  g_ptr_array_add(priv->certificates, g_object_ref(crt));
860
0
}
861
862
static void
863
fu_pefile_firmware_init(FuPefileFirmware *self)
864
3.45k
{
865
3.45k
  FuPefileFirmwarePrivate *priv = GET_PRIVATE(self);
866
3.45k
  priv->certificates = g_ptr_array_new_with_free_func((GDestroyNotify)g_object_unref);
867
3.45k
}
868
869
static void
870
fu_pefile_firmware_finalize(GObject *object)
871
3.45k
{
872
3.45k
  FuPefileFirmware *self = FU_PEFILE_FIRMWARE(object);
873
3.45k
  FuPefileFirmwarePrivate *priv = GET_PRIVATE(self);
874
3.45k
  g_free(priv->authenticode_hash);
875
3.45k
  g_ptr_array_unref(priv->certificates);
876
3.45k
  G_OBJECT_CLASS(fu_pefile_firmware_parent_class)->finalize(object);
877
3.45k
}
878
879
static void
880
fu_pefile_firmware_class_init(FuPefileFirmwareClass *klass)
881
1
{
882
1
  FuFirmwareClass *firmware_class = FU_FIRMWARE_CLASS(klass);
883
1
  GObjectClass *object_class = G_OBJECT_CLASS(klass);
884
1
  object_class->finalize = fu_pefile_firmware_finalize;
885
1
  firmware_class->validate = fu_pefile_firmware_validate;
886
1
  firmware_class->parse = fu_pefile_firmware_parse;
887
1
  firmware_class->write = fu_pefile_firmware_write;
888
1
  firmware_class->export = fu_pefile_firmware_export;
889
1
  firmware_class->get_checksum = fu_pefile_firmware_get_checksum;
890
1
  fu_firmware_add_image_gtype(firmware_class, FU_TYPE_FIRMWARE);
891
1
  fu_firmware_add_image_gtype(firmware_class, FU_TYPE_CSV_FIRMWARE);
892
1
  fu_firmware_add_image_gtype(firmware_class, FU_TYPE_SBATLEVEL_SECTION);
893
1
  fu_firmware_add_image_gtype(firmware_class, FU_TYPE_JSON_FIRMWARE);
894
1
  fu_firmware_add_image_gtype(firmware_class, FU_TYPE_COSWID_COLLECTION);
895
1
  fu_firmware_set_images_max(firmware_class, 100);
896
1
  fu_firmware_set_size_max(firmware_class, 256 * FU_MB);
897
1
}
898
899
/**
900
 * fu_pefile_firmware_new:
901
 *
902
 * Creates a new #FuPefileFirmware
903
 **/
904
FuFirmware *
905
fu_pefile_firmware_new(void)
906
0
{
907
0
  return FU_FIRMWARE(g_object_new(FU_TYPE_PEFILE_FIRMWARE, NULL));
908
0
}