Debian Codegraph @

src/sbsign/sbsign.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <unistd.h>
4
5 #include "alloc-util.h"
6 #include "ansi-color.h"
7 #include "ask-password-api.h"
8 #include "authenticode.h"
9 #include "build.h"
10 #include "copy.h"
11 #include "crypto-util.h"
12 #include "efi.h"
13 #include "fd-util.h"
14 #include "fileio.h"
15 #include "format-table.h"
16 #include "fs-util.h"
17 #include "install-file.h"
18 #include "io-util.h"
19 #include "log.h"
20 #include "main-func.h"
21 #include "options.h"
22 #include "parse-argument.h"
23 #include "pe-binary.h"
24 #include "pretty-print.h"
25 #include "stat-util.h"
26 #include "string-util.h"
27 #include "time-util.h"
28 #include "tmpfile-util.h"
29 #include "verbs.h"
30
31 static char *arg_output = NULL;
32 static char *arg_certificate = NULL;
33 static CertificateSourceType arg_certificate_source_type = OPENSSL_CERTIFICATE_SOURCE_FILE;
34 static char *arg_certificate_source = NULL;
35 static char *arg_private_key = NULL;
36 static KeySourceType arg_private_key_source_type = OPENSSL_KEY_SOURCE_FILE;
37 static char *arg_private_key_source = NULL;
38 static bool arg_prepare_offline_signing = false;
39 static char *arg_signed_data = NULL;
40 static char *arg_signed_data_signature = NULL;
41
42 STATIC_DESTRUCTOR_REGISTER(arg_output, freep);
43 STATIC_DESTRUCTOR_REGISTER(arg_certificate, freep);
44 STATIC_DESTRUCTOR_REGISTER(arg_certificate_source, freep);
45 STATIC_DESTRUCTOR_REGISTER(arg_private_key, freep);
46 STATIC_DESTRUCTOR_REGISTER(arg_private_key_source, freep);
47 STATIC_DESTRUCTOR_REGISTER(arg_signed_data, freep);
48 STATIC_DESTRUCTOR_REGISTER(arg_signed_data_signature, freep);
49
50 static int help(void) {
51 _cleanup_free_ char *link = NULL;
52 _cleanup_(table_unrefp) Table *options = NULL, *verbs = NULL;
53 int r;
54
55 r = terminal_urlify_man("systemd-sbsign", "1", &link);
56 if (r < 0)
57 return log_oom();
58
59 r = verbs_get_help_table(&verbs);
60 if (r < 0)
61 return r;
62
63 r = option_parser_get_help_table(&options);
64 if (r < 0)
65 return r;
66
67 (void) table_sync_column_widths(0, verbs, options);
68
69 printf("%s [OPTIONS...] COMMAND ...\n"
70 "\n%sSign binaries for EFI Secure Boot%s\n"
71 "\n%sCommands:%s\n",
72 program_invocation_short_name,
73 ansi_highlight(), ansi_normal(),
74 ansi_underline(), ansi_normal());
75
76 r = table_print_or_warn(verbs);
77 if (r < 0)
78 return r;
79
80 printf("\n%sOptions:%s\n", ansi_underline(), ansi_normal());
81 r = table_print_or_warn(options);
82 if (r < 0)
83 return r;
84
85 printf("\nSee the %s for details.\n", link);
86 return 0;
87 }
88
89 VERB_COMMON_HELP_HIDDEN(help);
90
91 static int parse_argv(int argc, char *argv[], char ***ret_args) {
92 assert(argc >= 0);
93 assert(argv);
94 assert(ret_args);
95
96 OptionParser opts = { argc, argv };
97 int r;
98
99 FOREACH_OPTION_OR_RETURN(c, &opts)
100 switch (c) {
101
102 OPTION_COMMON_HELP:
103 return help();
104
105 OPTION_COMMON_VERSION:
106 return version();
107
108 OPTION_LONG("output", "PATH",
109 "Where to write the signed PE binary"):
110 r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_output);
111 if (r < 0)
112 return r;
113
114 break;
115
116 OPTION_COMMON_CERTIFICATE("PEM certificate to use for signing"):
117 r = free_and_strdup_warn(&arg_certificate, opts.arg);
118 if (r < 0)
119 return r;
120 break;
121
122 OPTION_COMMON_CERTIFICATE_SOURCE:
123 r = parse_openssl_certificate_source_argument(
124 opts.arg,
125 &arg_certificate_source,
126 &arg_certificate_source_type);
127 if (r < 0)
128 return r;
129 break;
130
131 OPTION_COMMON_PRIVATE_KEY("Private key (PEM) to sign with"):
132 r = free_and_strdup_warn(&arg_private_key, opts.arg);
133 if (r < 0)
134 return r;
135
136 break;
137
138 OPTION_COMMON_PRIVATE_KEY_SOURCE:
139 r = parse_openssl_key_source_argument(
140 opts.arg,
141 &arg_private_key_source,
142 &arg_private_key_source_type);
143 if (r < 0)
144 return r;
145
146 break;
147
148 OPTION_LONG("prepare-offline-signing", NULL, /* help= */ NULL):
149 arg_prepare_offline_signing = true;
150 break;
151
152 OPTION_LONG("signed-data", "PATH", /* help= */ NULL):
153 r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_signed_data);
154 if (r < 0)
155 return r;
156
157 break;
158
159 OPTION_LONG("signed-data-signature", "PATH", /* help= */ NULL):
160 r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_signed_data_signature);
161 if (r < 0)
162 return r;
163
164 break;
165 }
166
167 if (arg_private_key_source && !arg_certificate)
168 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "When using --private-key-source=, --certificate= must be specified.");
169
170 if (!!arg_signed_data != !!arg_signed_data_signature)
171 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--signed-data= and --signed-data-signature= must always be used together.");
172
173 if (arg_prepare_offline_signing && (arg_private_key || arg_signed_data || arg_signed_data_signature))
174 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--prepare-offline-signing cannot be used with --private-key=, --signed-data= or --signed-data-signature=");
175
176 *ret_args = option_parser_get_args(&opts);
177 return 1;
178 }
179
180 static int spc_indirect_data_content_new(const void *digest, size_t digestsz, uint8_t **ret_idc, size_t *ret_idcsz) {
181 assert(digest);
182 assert(ret_idc);
183 assert(ret_idcsz);
184
185 /* This function allocates and populates a new SpcIndirectDataContent object. See the authenticode
186 * spec https://aka.ms/AuthenticodeSpec for more information on the individual fields. */
187
188 /* <<<Obsolete>>> in unicode bytes. */
189 static const uint8_t obsolete[] = {
190 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x3c, 0x00, 0x4f,
191 0x00, 0x62, 0x00, 0x73, 0x00, 0x6f, 0x00, 0x6c,
192 0x00, 0x65, 0x00, 0x74, 0x00, 0x65, 0x00, 0x3e,
193 0x00, 0x3e, 0x00, 0x3e
194 };
195
196 _cleanup_(SpcLink_freep) SpcLink *link = SpcLink_new();
197 if (!link)
198 return log_oom();
199
200 link->type = 2;
201 link->value.file = SpcString_new();
202 if (!link->value.file)
203 return log_oom();
204
205 link->value.file->type = 0;
206 link->value.file->value.unicode = sym_ASN1_BMPSTRING_new();
207 if (!link->value.file->value.unicode)
208 return log_oom();
209
210 if (sym_ASN1_STRING_set(link->value.file->value.unicode, obsolete, sizeof(obsolete)) == 0)
211 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to set ASN1 string: %s",
212 sym_ERR_error_string(sym_ERR_get_error(), NULL));
213
214 _cleanup_(SpcPeImageData_freep) SpcPeImageData *peid = SpcPeImageData_new();
215 if (!peid)
216 return log_oom();
217
218 peid->file = TAKE_PTR(link);
219
220 _cleanup_free_ uint8_t *peidraw = NULL;
221 int peidrawsz = i2d_SpcPeImageData(peid, &peidraw);
222 if (peidrawsz < 0)
223 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert SpcPeImageData to BER: %s",
224 sym_ERR_error_string(sym_ERR_get_error(), NULL));
225
226 _cleanup_(SpcIndirectDataContent_freep) SpcIndirectDataContent *idc = SpcIndirectDataContent_new();
227 idc->data->value = sym_ASN1_TYPE_new();
228 if (!idc->data->value)
229 return log_oom();
230
231 idc->data->value->type = V_ASN1_SEQUENCE;
232 idc->data->value->value.sequence = sym_ASN1_STRING_new();
233 if (!idc->data->value->value.sequence)
234 return log_oom();
235
236 idc->data->type = sym_OBJ_txt2obj(SPC_PE_IMAGE_DATA_OBJID, /* no_name= */ 1);
237 if (!idc->data->type)
238 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to get SpcPeImageData object: %s",
239 sym_ERR_error_string(sym_ERR_get_error(), NULL));
240
241 if (!sym_ASN1_STRING_set(idc->data->value->value.sequence, peidraw, peidrawsz))
242 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to set ASN1_STRING data.");
243
244 idc->messageDigest->digestAlgorithm->algorithm = sym_OBJ_nid2obj(NID_sha256);
245 if (!idc->messageDigest->digestAlgorithm->algorithm)
246 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to get SHA256 object: %s",
247 sym_ERR_error_string(sym_ERR_get_error(), NULL));
248
249 idc->messageDigest->digestAlgorithm->parameters = sym_ASN1_TYPE_new();
250 if (!idc->messageDigest->digestAlgorithm->parameters)
251 return log_oom();
252
253 idc->messageDigest->digestAlgorithm->parameters->type = V_ASN1_NULL;
254
255 if (sym_ASN1_OCTET_STRING_set(idc->messageDigest->digest, digest, digestsz) == 0)
256 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to set digest: %s",
257 sym_ERR_error_string(sym_ERR_get_error(), NULL));
258
259 _cleanup_free_ uint8_t *idcraw = NULL;
260 int idcrawsz = i2d_SpcIndirectDataContent(idc, &idcraw);
261 if (idcrawsz < 0)
262 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert SpcIndirectDataContent to BER: %s",
263 sym_ERR_error_string(sym_ERR_get_error(), NULL));
264
265 *ret_idc = TAKE_PTR(idcraw);
266 *ret_idcsz = (size_t) idcrawsz;
267
268 return 0;
269 }
270
271 static int asn1_timestamp(ASN1_TIME **ret) {
272 ASN1_TIME *time;
273
274 assert(ret);
275
276 usec_t epoch = parse_source_date_epoch();
277
278 if (epoch == USEC_INFINITY) {
279 time = sym_X509_gmtime_adj(NULL, 0);
280 if (!time)
281 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to get current time: %s",
282 sym_ERR_error_string(sym_ERR_get_error(), NULL));
283 } else {
284 time = sym_ASN1_TIME_set(NULL, (time_t) (epoch / USEC_PER_SEC));
285 if (!time)
286 return log_oom();
287 }
288
289 *ret = TAKE_PTR(time);
290
291 return 0;
292 }
293
294 static int pkcs7_new_with_attributes(
295 X509 *certificate,
296 EVP_PKEY *private_key,
297 const char *hash_algorithm,
298 STACK_OF(X509_ATTRIBUTE) *signed_attributes,
299 PKCS7 **ret_p7,
300 PKCS7_SIGNER_INFO **ret_si) {
301
302 int r;
303
304 /* This function sets up a new PKCS#7 signing context with the signed attributes required for
305 * authenticode signing. */
306
307 assert(certificate);
308 assert(ret_p7);
309 assert(ret_si);
310
311 _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
312 PKCS7_SIGNER_INFO *si = NULL; /* avoid false maybe-uninitialized warning */
313 r = pkcs7_new(certificate, private_key, hash_algorithm, &p7, &si);
314 if (r < 0)
315 return log_error_errno(r, "Failed to allocate PKCS# context: %m");
316
317 if (signed_attributes) {
318 si->auth_attr = signed_attributes;
319
320 *ret_p7 = TAKE_PTR(p7);
321 *ret_si = TAKE_PTR(si);
322 return 0;
323 }
324
325 /* Add an empty SMIMECAP attribute to indicate we don't have any SMIME capabilities. */
326 _cleanup_(x509_algor_free_manyp) STACK_OF(X509_ALGOR) *smcap = (STACK_OF(X509_ALGOR)*) sym_OPENSSL_sk_new_null();
327 if (!smcap)
328 return log_oom();
329
330 if (sym_PKCS7_add_attrib_smimecap(si, smcap) == 0)
331 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to add smimecap signed attribute to signer info: %s",
332 sym_ERR_error_string(sym_ERR_get_error(), NULL));
333
334 if (sym_PKCS7_add_attrib_content_type(si, NULL) == 0)
335 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to add content type signed attribute to signer info: %s",
336 sym_ERR_error_string(sym_ERR_get_error(), NULL));
337
338 _cleanup_(ASN1_TIME_freep) ASN1_TIME *time = NULL;
339 r = asn1_timestamp(&time);
340 if (r < 0)
341 return r;
342
343 if (sym_PKCS7_add0_attrib_signing_time(si, time) == 0)
344 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to add signing time signed attribute to signer info: %s",
345 sym_ERR_error_string(sym_ERR_get_error(), NULL));
346
347 TAKE_PTR(time);
348
349 ASN1_OBJECT *idc = sym_OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, /* no_name= */ true);
350 if (!idc)
351 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to get SpcIndirectDataContent object: %s",
352 sym_ERR_error_string(sym_ERR_get_error(), NULL));
353
354 if (sym_PKCS7_add_signed_attribute(si, NID_pkcs9_contentType, V_ASN1_OBJECT, idc) == 0)
355 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to add signed attribute to pkcs7 signer info: %s",
356 sym_ERR_error_string(sym_ERR_get_error(), NULL));
357
358 *ret_p7 = TAKE_PTR(p7);
359 *ret_si = TAKE_PTR(si);
360 return 0;
361 }
362
363 static int pkcs7_populate_data_bio(PKCS7* p7, const void *data, size_t size, BIO **ret) {
364 assert(ret);
365
366 _cleanup_(BIO_free_allp) BIO *bio = sym_PKCS7_dataInit(p7, NULL);
367 if (!bio)
368 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to create PKCS7 data bio: %s",
369 sym_ERR_error_string(sym_ERR_get_error(), NULL));
370
371 int tag, class;
372 long psz;
373 const uint8_t *p = data;
374
375 /* This function weirdly enough reports errors by setting the 0x80 bit in its return value. */
376 if (sym_ASN1_get_object(&p, &psz, &tag, &class, size) & 0x80)
377 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to parse ASN.1 object: %s",
378 sym_ERR_error_string(sym_ERR_get_error(), NULL));
379
380 if (sym_BIO_write(bio, p, psz) < 0)
381 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write to PKCS7 data bio: %s",
382 sym_ERR_error_string(sym_ERR_get_error(), NULL));
383
384 *ret = TAKE_PTR(bio);
385
386 return 0;
387 }
388
389 static int pkcs7_add_digest_attribute(PKCS7 *p7, BIO *data, PKCS7_SIGNER_INFO *si) {
390 assert(p7);
391 assert(data);
392 assert(si);
393
394 BIO *mdbio = sym_BIO_find_type(data, BIO_TYPE_MD);
395 if (!mdbio)
396 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to find digest bio: %s",
397 sym_ERR_error_string(sym_ERR_get_error(), NULL));
398
399 EVP_MD_CTX *mdc;
400 if (sym_BIO_get_md_ctx(mdbio, &mdc) <= 0)
401 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to get digest context from bio: %s",
402 sym_ERR_error_string(sym_ERR_get_error(), NULL));
403
404 unsigned char digest[EVP_MAX_MD_SIZE];
405 unsigned digestsz;
406
407 if (sym_EVP_DigestFinal_ex(mdc, digest, &digestsz) == 0)
408 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to get digest: %s",
409 sym_ERR_error_string(sym_ERR_get_error(), NULL));
410
411 if (sym_PKCS7_add1_attrib_digest(si, digest, digestsz) == 0)
412 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to add PKCS9 message digest signed attribute to signer info: %s",
413 sym_ERR_error_string(sym_ERR_get_error(), NULL));
414
415 return 0;
416 }
417
418 VERB(verb_sign, "sign", "EXEFILE", 2, 2, 0,
419 "Sign the given binary for EFI Secure Boot");
420 static int verb_sign(int argc, char *argv[], uintptr_t _data, void *userdata) {
421 _cleanup_(openssl_ask_password_ui_freep) OpenSSLAskPasswordUI *ui = NULL;
422 _cleanup_(EVP_PKEY_freep) EVP_PKEY *private_key = NULL;
423 _cleanup_(X509_freep) X509 *certificate = NULL;
424 _cleanup_(x509_attribute_free_manyp) STACK_OF(X509_ATTRIBUTE) *signed_attributes = NULL;
425 _cleanup_(iovec_done) struct iovec signed_attributes_signature = {};
426 int r;
427
428 r = DLOPEN_LIBCRYPTO(LOG_ERR, SD_ELF_NOTE_DLOPEN_PRIORITY_REQUIRED);
429 if (r < 0)
430 return r;
431
432 if (argc < 2)
433 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No input file specified");
434
435 if (!arg_certificate)
436 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
437 "No certificate specified, use --certificate=");
438
439 if (!arg_private_key && !arg_signed_data_signature && !arg_prepare_offline_signing)
440 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
441 "No private key or signed data signature specified, use --private-key= or --signed-data-signature=.");
442
443 if (!arg_output)
444 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No output specified, use --output=");
445
446 if (arg_certificate_source_type == OPENSSL_CERTIFICATE_SOURCE_FILE) {
447 r = parse_path_argument(arg_certificate, /* suppress_root= */ false, &arg_certificate);
448 if (r < 0)
449 return r;
450 }
451
452 r = openssl_load_x509_certificate(
453 arg_certificate_source_type,
454 arg_certificate_source,
455 arg_certificate,
456 &certificate);
457 if (r < 0)
458 return log_error_errno(r, "Failed to load X.509 certificate from %s: %m", arg_certificate);
459
460 if (arg_private_key) {
461 if (arg_private_key_source_type == OPENSSL_KEY_SOURCE_FILE) {
462 r = parse_path_argument(arg_private_key, /* suppress_root= */ false, &arg_private_key);
463 if (r < 0)
464 return r;
465 }
466
467 r = openssl_load_private_key(
468 arg_private_key_source_type,
469 arg_private_key_source,
470 arg_private_key,
471 &(AskPasswordRequest) {
472 .tty_fd = -EBADF,
473 .id = "sbsign-private-key-pin",
474 .keyring = arg_private_key,
475 .credential = "sbsign.private-key-pin",
476 .until = USEC_INFINITY,
477 .hup_fd = -EBADF,
478 },
479 &private_key,
480 &ui);
481 if (r < 0)
482 return log_error_errno(r, "Failed to load private key from %s: %m", arg_private_key);
483 }
484
485 if (arg_signed_data) {
486 _cleanup_free_ void *content = NULL;
487 size_t contentsz;
488
489 r = read_full_file(arg_signed_data, (char**) &content, &contentsz);
490 if (r < 0)
491 return log_error_errno(r, "Failed to read signed attributes file '%s': %m", arg_signed_data);
492
493 const uint8_t *p = content;
494 if (!sym_ASN1_item_d2i((ASN1_VALUE **) &signed_attributes, &p, contentsz, sym_PKCS7_ATTR_SIGN_it()))
495 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to parse signed attributes: %s",
496 sym_ERR_error_string(sym_ERR_get_error(), NULL));
497 }
498
499 if (arg_signed_data_signature) {
500 _cleanup_free_ void *content = NULL;
501 size_t contentsz;
502
503 r = read_full_file(arg_signed_data_signature, (char**) &content, &contentsz);
504 if (r < 0)
505 return log_error_errno(r, "Failed to read signed attributes signature file '%s': %m", arg_signed_data_signature);
506
507 signed_attributes_signature = IOVEC_MAKE(TAKE_PTR(content), contentsz);
508 }
509
510 _cleanup_close_ int srcfd = open(argv[1], O_RDONLY|O_CLOEXEC);
511 if (srcfd < 0)
512 return log_error_errno(errno, "Failed to open %s: %m", argv[1]);
513
514 struct stat st;
515 if (fstat(srcfd, &st) < 0)
516 return log_error_errno(errno, "Failed to stat %s: %m", argv[1]);
517
518 r = stat_verify_regular(&st);
519 if (r < 0)
520 return log_error_errno(r, "%s is not a regular file: %m", argv[1]);
521
522 _cleanup_(unlink_and_freep) char *tmp = NULL;
523 _cleanup_close_ int dstfd = open_tmpfile_linkable(arg_output, O_RDWR|O_CLOEXEC, &tmp);
524 if (dstfd < 0)
525 return log_error_errno(dstfd, "Failed to open temporary file: %m");
526
527 r = fchmod_umask(dstfd, 0666);
528 if (r < 0)
529 log_debug_errno(r, "Failed to change temporary file mode: %m");
530
531 _cleanup_free_ void *pehash = NULL;
532 size_t pehashsz;
533 r = pe_hash(srcfd, sym_EVP_sha256(), &pehash, &pehashsz);
534 if (r < 0)
535 return log_error_errno(r, "Failed to hash PE binary %s: %m", argv[0]);
536
537 _cleanup_free_ uint8_t *idcraw = NULL;
538 size_t idcrawsz = 0; /* avoid false maybe-uninitialized warning */
539 r = spc_indirect_data_content_new(pehash, pehashsz, &idcraw, &idcrawsz);
540 if (r < 0)
541 return r;
542
543 _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
544 PKCS7_SIGNER_INFO *si = NULL; /* avoid false maybe-uninitialized warning */
545 r = pkcs7_new_with_attributes(certificate, private_key, /* hash_algorithm= */ NULL, signed_attributes, &p7, &si);
546 if (r < 0)
547 return r;
548
549 TAKE_PTR(signed_attributes);
550
551 if (arg_prepare_offline_signing) {
552 _cleanup_(BIO_free_allp) BIO *bio = NULL;
553 r = pkcs7_populate_data_bio(p7, idcraw, idcrawsz, &bio);
554 if (r < 0)
555 return r;
556
557 r = pkcs7_add_digest_attribute(p7, bio, si);
558 if (r < 0)
559 return r;
560
561 _cleanup_free_ unsigned char *abuf = NULL;
562 int alen = sym_ASN1_item_i2d((ASN1_VALUE *)si->auth_attr, &abuf, sym_PKCS7_ATTR_SIGN_it());
563 if (alen < 0 || !abuf)
564 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert signed attributes ASN.1 to DER: %s",
565 sym_ERR_error_string(sym_ERR_get_error(), NULL));
566
567 r = loop_write(dstfd, abuf, alen);
568 if (r < 0)
569 return log_error_errno(r, "Failed to write PKCS#7 DER-encoded signed attributes blob to temporary file: %m");
570
571 r = link_tmpfile(dstfd, tmp, arg_output, LINK_TMPFILE_REPLACE|LINK_TMPFILE_SYNC);
572 if (r < 0)
573 return log_error_errno(r, "Failed to link temporary file to %s: %m", arg_output);
574
575 log_info("Wrote PKCS#7 DER-encoded signed attributes blob to %s", arg_output);
576 return 0;
577 }
578
579 if (iovec_is_set(&signed_attributes_signature))
580 sym_ASN1_STRING_set0(si->enc_digest, TAKE_PTR(signed_attributes_signature.iov_base), signed_attributes_signature.iov_len);
581 else {
582 _cleanup_(BIO_free_allp) BIO *bio = NULL;
583 r = pkcs7_populate_data_bio(p7, idcraw, idcrawsz, &bio);
584 if (r < 0)
585 return r;
586
587 if (sym_PKCS7_dataFinal(p7, bio) == 0)
588 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to sign data: %s",
589 sym_ERR_error_string(sym_ERR_get_error(), NULL));
590 }
591
592 _cleanup_(PKCS7_freep) PKCS7 *p7c = sym_PKCS7_new();
593 if (!p7c)
594 return log_oom();
595
596 p7c->type = sym_OBJ_txt2obj(SPC_INDIRECT_DATA_OBJID, /* no_name= */ true);
597 if (!p7c->type)
598 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to get SpcIndirectDataContent object: %s",
599 sym_ERR_error_string(sym_ERR_get_error(), NULL));
600
601 p7c->d.other = sym_ASN1_TYPE_new();
602 if (!p7c->d.other)
603 return log_oom();
604
605 p7c->d.other->type = V_ASN1_SEQUENCE;
606 p7c->d.other->value.sequence = sym_ASN1_STRING_new();
607 if (!p7c->d.other->value.sequence)
608 return log_oom();
609
610 if (sym_ASN1_STRING_set(p7c->d.other->value.sequence, idcraw, idcrawsz) == 0)
611 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to set ASN1 string: %s",
612 sym_ERR_error_string(sym_ERR_get_error(), NULL));
613
614 if (sym_PKCS7_set_content(p7, p7c) == 0)
615 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to set PKCS7 data: %s",
616 sym_ERR_error_string(sym_ERR_get_error(), NULL));
617
618 TAKE_PTR(p7c);
619
620 _cleanup_free_ uint8_t *sig = NULL;
621 int sigsz = sym_i2d_PKCS7(p7, &sig);
622 if (sigsz < 0)
623 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert PKCS7 signature to DER: %s",
624 sym_ERR_error_string(sym_ERR_get_error(), NULL));
625
626 _cleanup_free_ IMAGE_DOS_HEADER *dos_header = NULL;
627 _cleanup_free_ PeHeader *pe_header = NULL;
628 r = pe_load_headers(srcfd, &dos_header, &pe_header);
629 if (r < 0)
630 return log_error_errno(r, "Failed to load headers from PE file: %m");
631
632 const IMAGE_DATA_DIRECTORY *certificate_table;
633 certificate_table = pe_header_get_data_directory(pe_header, IMAGE_DATA_DIRECTORY_INDEX_CERTIFICATION_TABLE);
634 if (!certificate_table)
635 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "File lacks certificate table.");
636
637 r = copy_bytes(srcfd, dstfd, UINT64_MAX, COPY_REFLINK);
638 if (r < 0)
639 return log_error_errno(r, "Failed to copy %s to %s: %m", argv[1], tmp);
640
641 off_t end = st.st_size;
642 ssize_t n;
643
644 if (st.st_size % 8 != 0) {
645 if (certificate_table->VirtualAddress != 0)
646 return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Certificate table is not aligned to 8 bytes");
647
648 n = pwrite(dstfd, (const uint8_t[8]) {}, 8 - (st.st_size % 8), st.st_size);
649 if (n < 0)
650 return log_error_errno(errno, "Failed to write zero padding: %m");
651 if (n != 8 - (st.st_size % 8))
652 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while writing zero padding.");
653
654 end += n;
655 }
656
657 uint32_t certsz = sizeof(WIN_CERTIFICATE_HEADER) + sigsz;
658 n = pwrite(dstfd,
659 &(WIN_CERTIFICATE_HEADER) {
660 .wRevision = htole16(0x200),
661 .wCertificateType = htole16(0x0002), /* PKCS7 signedData */
662 .dwLength = htole32(ROUND_UP(certsz, 8)),
663 },
664 sizeof(WIN_CERTIFICATE_HEADER),
665 end);
666 if (n < 0)
667 return log_error_errno(errno, "Failed to write certificate header: %m");
668 if (n != sizeof(WIN_CERTIFICATE_HEADER))
669 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while writing certificate header.");
670
671 end += n;
672
673 n = pwrite(dstfd, sig, sigsz, end);
674 if (n < 0)
675 return log_error_errno(errno, "Failed to write signature: %m");
676 if (n != sigsz)
677 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while writing signature.");
678
679 end += n;
680
681 if (certsz % 8 != 0) {
682 n = pwrite(dstfd, (const uint8_t[8]) {}, 8 - (certsz % 8), end);
683 if (n < 0)
684 return log_error_errno(errno, "Failed to write zero padding: %m");
685 if ((size_t) n != 8 - (certsz % 8))
686 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while writing zero padding.");
687 }
688
689 n = pwrite(dstfd,
690 &(IMAGE_DATA_DIRECTORY) {
691 .VirtualAddress = certificate_table->VirtualAddress ?: htole32(ROUND_UP(st.st_size, 8)),
692 .Size = htole32(le32toh(certificate_table->Size) + ROUND_UP(certsz, 8)),
693 },
694 sizeof(IMAGE_DATA_DIRECTORY),
695 le32toh(dos_header->e_lfanew) + PE_HEADER_OPTIONAL_FIELD_OFFSET(pe_header, DataDirectory[IMAGE_DATA_DIRECTORY_INDEX_CERTIFICATION_TABLE]));
696 if (n < 0)
697 return log_error_errno(errno, "Failed to update PE certificate table: %m");
698 if ((size_t) n != sizeof(IMAGE_DATA_DIRECTORY))
699 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while updating PE certificate table.");
700
701 uint32_t checksum;
702 r = pe_checksum(dstfd, &checksum);
703 if (r < 0)
704 return log_error_errno(r, "Failed to calculate PE file checksum: %m");
705
706 n = pwrite(dstfd,
707 &(le32_t) { htole32(checksum) },
708 sizeof(le32_t),
709 le32toh(dos_header->e_lfanew) + offsetof(PeHeader, optional.CheckSum));
710 if (n < 0)
711 return log_error_errno(errno, "Failed to update PE checksum: %m");
712 if ((size_t) n != sizeof(le32_t))
713 return log_error_errno(SYNTHETIC_ERRNO(EIO), "Short write while updating PE checksum.");
714
715 r = link_tmpfile(dstfd, tmp, arg_output, LINK_TMPFILE_REPLACE|LINK_TMPFILE_SYNC);
716 if (r < 0)
717 return log_error_errno(r, "Failed to link temporary file to %s: %m", arg_output);
718
719 log_info("Wrote signed PE binary to %s", arg_output);
720 return 0;
721 }
722
723 static int run(int argc, char *argv[]) {
724 int r;
725
726 log_setup();
727
728 char **args = NULL;
729 r = parse_argv(argc, argv, &args);
730 if (r <= 0)
731 return r;
732
733 return dispatch_verb(args, NULL);
734 }
735
736 DEFINE_MAIN_FUNCTION(run);