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

systemd / systemd / 15789897806

20 Jun 2025 05:25PM UTC coverage: 72.105% (+0.06%) from 72.045%
15789897806

push

github

web-flow
bootctl: honour architecture when updating boot loaders (#37913)

Fixes: #33413
Follow-up for: #30418

21 of 29 new or added lines in 2 files covered. (72.41%)

1701 existing lines in 55 files now uncovered.

300497 of 416750 relevant lines covered (72.1%)

721912.12 hits per line

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

65.94
/src/bootctl/bootctl-install.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <stdlib.h>
4
#include <unistd.h>
5

6
#include "alloc-util.h"
7
#include "boot-entry.h"
8
#include "bootctl.h"
9
#include "bootctl-install.h"
10
#include "bootctl-random-seed.h"
11
#include "bootctl-util.h"
12
#include "chase.h"
13
#include "copy.h"
14
#include "dirent-util.h"
15
#include "efi-api.h"
16
#include "efi-fundamental.h"
17
#include "efivars.h"
18
#include "env-file.h"
19
#include "env-util.h"
20
#include "fd-util.h"
21
#include "fileio.h"
22
#include "fs-util.h"
23
#include "glyph-util.h"
24
#include "id128-util.h"
25
#include "io-util.h"
26
#include "kernel-config.h"
27
#include "log.h"
28
#include "openssl-util.h"
29
#include "parse-argument.h"
30
#include "path-util.h"
31
#include "pe-binary.h"
32
#include "rm-rf.h"
33
#include "stat-util.h"
34
#include "string-util.h"
35
#include "strv.h"
36
#include "sync-util.h"
37
#include "time-util.h"
38
#include "tmpfile-util.h"
39
#include "umask-util.h"
40
#include "utf8.h"
41

42
static int load_etc_machine_id(void) {
152✔
43
        int r;
152✔
44

45
        r = sd_id128_get_machine(&arg_machine_id);
152✔
46
        if (ERRNO_IS_NEG_MACHINE_ID_UNSET(r)) /* Not set or empty */
152✔
47
                return 0;
48
        if (r < 0)
152✔
49
                return log_error_errno(r, "Failed to get machine-id: %m");
×
50

51
        log_debug("Loaded machine ID %s from /etc/machine-id.", SD_ID128_TO_STRING(arg_machine_id));
152✔
52
        return 0;
152✔
53
}
54

55
static int load_etc_machine_info(void) {
152✔
56
        /* systemd v250 added support to store the kernel-install layout setting and the machine ID to use
57
         * for setting up the ESP in /etc/machine-info. The newer /etc/kernel/entry-token file, as well as
58
         * the $layout field in /etc/kernel/install.conf are better replacements for this though, hence this
59
         * has been deprecated and is only returned for compatibility. */
60
        _cleanup_free_ char *p = NULL, *s = NULL, *layout = NULL;
152✔
61
        int r;
152✔
62

63
        p = path_join(arg_root, "/etc/machine-info");
152✔
64
        if (!p)
152✔
65
                return log_oom();
×
66

67
        r = parse_env_file(NULL, p,
152✔
68
                           "KERNEL_INSTALL_LAYOUT", &layout,
69
                           "KERNEL_INSTALL_MACHINE_ID", &s);
70
        if (r == -ENOENT)
152✔
71
                return 0;
72
        if (r < 0)
×
73
                return log_error_errno(r, "Failed to parse /etc/machine-info: %m");
×
74

75
        if (!isempty(s)) {
×
76
                if (!arg_quiet)
×
77
                        log_notice("Read $KERNEL_INSTALL_MACHINE_ID from /etc/machine-info. "
×
78
                                   "Please move it to /etc/kernel/entry-token.");
79

80
                r = sd_id128_from_string(s, &arg_machine_id);
×
81
                if (r < 0)
×
82
                        return log_error_errno(r, "Failed to parse KERNEL_INSTALL_MACHINE_ID=%s in /etc/machine-info: %m", s);
×
83

84
                log_debug("Loaded KERNEL_INSTALL_MACHINE_ID=%s from /etc/machine-info.",
×
85
                          SD_ID128_TO_STRING(arg_machine_id));
86
        }
87

88
        if (!isempty(layout)) {
152✔
89
                if (!arg_quiet)
×
90
                        log_notice("Read $KERNEL_INSTALL_LAYOUT from /etc/machine-info. "
×
91
                                   "Please move it to the layout= setting of /etc/kernel/install.conf.");
92

93
                log_debug("KERNEL_INSTALL_LAYOUT=%s is specified in /etc/machine-info.", layout);
×
94
                free_and_replace(arg_install_layout, layout);
×
95
        }
96

97
        return 0;
98
}
99

100
static int load_kernel_install_layout(void) {
152✔
101
        _cleanup_free_ char *layout = NULL;
152✔
102
        int r;
152✔
103

104
        r = load_kernel_install_conf(arg_root,
152✔
105
                                     getenv("KERNEL_INSTALL_CONF_ROOT"),
152✔
106
                                     /* ret_machine_id= */ NULL,
107
                                     /* ret_boot_root= */ NULL,
108
                                     &layout,
109
                                     /* ret_initrd_generator= */ NULL,
110
                                     /* ret_uki_generator= */ NULL);
111
        if (r <= 0)
152✔
112
                return r;
113

114
        if (!isempty(layout)) {
152✔
115
                log_debug("layout=%s is specified in config.", layout);
×
116
                free_and_replace(arg_install_layout, layout);
×
117
        }
118

119
        return 0;
120
}
121

122
static bool use_boot_loader_spec_type1(void) {
152✔
123
        /* If the layout is not specified, or if it is set explicitly to "bls" we assume Boot Loader
124
         * Specification Type #1 is the chosen format for our boot loader entries */
125
        return !arg_install_layout || streq(arg_install_layout, "bls");
152✔
126
}
127

128
static int settle_make_entry_directory(void) {
152✔
129
        int r;
152✔
130

131
        r = load_etc_machine_id();
152✔
132
        if (r < 0)
152✔
133
                return r;
134

135
        r = load_etc_machine_info();
152✔
136
        if (r < 0)
152✔
137
                return r;
138

139
        r = load_kernel_install_layout();
152✔
140
        if (r < 0)
152✔
141
                return r;
142

143
        r = settle_entry_token();
152✔
144
        if (r < 0)
152✔
145
                return r;
146

147
        bool layout_type1 = use_boot_loader_spec_type1();
152✔
148
        if (arg_make_entry_directory < 0) { /* Automatic mode */
152✔
149
                if (layout_type1) {
×
150
                        if (arg_entry_token_type == BOOT_ENTRY_TOKEN_MACHINE_ID) {
×
151
                                r = path_is_temporary_fs("/etc/machine-id");
×
152
                                if (r < 0)
×
153
                                        return log_debug_errno(r, "Couldn't determine whether /etc/machine-id is on a temporary file system: %m");
×
154

155
                                arg_make_entry_directory = r == 0;
×
156
                        } else
157
                                arg_make_entry_directory = true;
×
158
                } else
159
                        arg_make_entry_directory = false;
×
160
        }
161

162
        if (arg_make_entry_directory > 0 && !layout_type1)
152✔
163
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
164
                                       "KERNEL_INSTALL_LAYOUT=%s is configured, but Boot Loader Specification Type #1 entry directory creation was requested.",
165
                                       arg_install_layout);
166

167
        return 0;
168
}
169

170
static int compare_product(const char *a, const char *b) {
378✔
171
        size_t x, y;
378✔
172

173
        assert(a);
378✔
174
        assert(b);
378✔
175

176
        x = strcspn(a, " ");
378✔
177
        y = strcspn(b, " ");
378✔
178
        if (x != y)
378✔
179
                return x < y ? -1 : x > y ? 1 : 0;
×
180

181
        return strncmp(a, b, x);
378✔
182
}
183

184
static int compare_version(const char *a, const char *b) {
378✔
185
        assert(a);
378✔
186
        assert(b);
378✔
187

188
        a += strcspn(a, " ");
378✔
189
        a += strspn(a, " ");
378✔
190
        b += strcspn(b, " ");
378✔
191
        b += strspn(b, " ");
378✔
192

193
        return strverscmp_improved(a, b);
378✔
194
}
195

196
static int version_check(int fd_from, const char *from, int fd_to, const char *to) {
378✔
197
        _cleanup_free_ char *a = NULL, *b = NULL;
378✔
198
        int r;
378✔
199

200
        assert(fd_from >= 0);
378✔
201
        assert(from);
378✔
202
        assert(fd_to >= 0);
378✔
203
        assert(to);
378✔
204

205
        r = get_file_version(fd_from, &a);
378✔
206
        if (r == -ESRCH)
378✔
207
                return log_notice_errno(r, "Source file \"%s\" does not carry version information!", from);
×
208
        if (r < 0)
378✔
209
                return r;
210

211
        r = get_file_version(fd_to, &b);
378✔
212
        if (r == -ESRCH)
378✔
213
                return log_notice_errno(r, "Skipping \"%s\", it's owned by another boot loader (no version info found).",
×
214
                                        to);
215
        if (r < 0)
378✔
216
                return r;
217
        if (compare_product(a, b) != 0)
378✔
218
                return log_notice_errno(SYNTHETIC_ERRNO(ESRCH),
×
219
                                        "Skipping \"%s\", it's owned by another boot loader.", to);
220

221
        r = compare_version(a, b);
378✔
222
        log_debug("Comparing versions: \"%s\" %s \"%s\"", a, comparison_operator(r), b);
738✔
223
        if (r < 0)
378✔
224
                return log_warning_errno(SYNTHETIC_ERRNO(ESTALE),
×
225
                                         "Skipping \"%s\", newer boot loader version in place already.", to);
226
        if (r == 0)
378✔
227
                return log_info_errno(SYNTHETIC_ERRNO(ESTALE),
378✔
228
                                      "Skipping \"%s\", same boot loader version in place already.", to);
229

230
        return 0;
231
}
232

233
static int copy_file_with_version_check(const char *from, const char *to, bool force) {
416✔
234
        _cleanup_close_ int fd_from = -EBADF, fd_to = -EBADF;
416✔
235
        _cleanup_free_ char *t = NULL;
416✔
236
        int r;
416✔
237

238
        fd_from = open(from, O_RDONLY|O_CLOEXEC|O_NOCTTY);
416✔
239
        if (fd_from < 0)
416✔
240
                return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", from);
×
241

242
        if (!force) {
416✔
243
                fd_to = open(to, O_RDONLY|O_CLOEXEC|O_NOCTTY);
378✔
244
                if (fd_to < 0) {
378✔
245
                        if (errno != ENOENT)
×
246
                                return log_error_errno(errno, "Failed to open \"%s\" for reading: %m", to);
×
247
                } else {
248
                        r = version_check(fd_from, from, fd_to, to);
378✔
249
                        if (r < 0)
378✔
250
                                return r;
251

252
                        if (lseek(fd_from, 0, SEEK_SET) < 0)
×
253
                                return log_error_errno(errno, "Failed to seek in \"%s\": %m", from);
×
254

255
                        fd_to = safe_close(fd_to);
×
256
                }
257
        }
258

259
        r = tempfn_random(to, NULL, &t);
38✔
260
        if (r < 0)
38✔
261
                return log_oom();
×
262

263
        WITH_UMASK(0000) {
76✔
264
                fd_to = open(t, O_WRONLY|O_CREAT|O_CLOEXEC|O_EXCL|O_NOFOLLOW, 0644);
38✔
265
                if (fd_to < 0)
38✔
266
                        return log_error_errno(errno, "Failed to open \"%s\" for writing: %m", t);
×
267
        }
268

269
        r = copy_bytes(fd_from, fd_to, UINT64_MAX, COPY_REFLINK);
38✔
270
        if (r < 0) {
38✔
271
                (void) unlink(t);
×
272
                return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
×
273
        }
274

275
        (void) copy_times(fd_from, fd_to, 0);
38✔
276

277
        r = fsync_full(fd_to);
38✔
278
        if (r < 0) {
38✔
279
                (void) unlink(t);
×
280
                return log_error_errno(r, "Failed to copy data from \"%s\" to \"%s\": %m", from, t);
×
281
        }
282

283
        r = RET_NERRNO(renameat(AT_FDCWD, t, AT_FDCWD, to));
38✔
284
        if (r < 0) {
×
285
                (void) unlink(t);
×
286
                return log_error_errno(r, "Failed to rename \"%s\" to \"%s\": %m", t, to);
×
287
        }
288

289
        log_info("Copied \"%s\" to \"%s\".", from, to);
38✔
290

291
        return 0;
292
}
293

294
static int mkdir_one(const char *prefix, const char *suffix) {
125✔
295
        _cleanup_free_ char *p = NULL;
125✔
296

297
        p = path_join(prefix, suffix);
125✔
298
        if (mkdir(p, 0700) < 0) {
125✔
299
                if (errno != EEXIST)
37✔
300
                        return log_error_errno(errno, "Failed to create \"%s\": %m", p);
×
301
        } else
302
                log_info("Created \"%s\".", p);
88✔
303

304
        return 0;
305
}
306

307
static const char *const esp_subdirs[] = {
308
        /* The directories to place in the ESP */
309
        "EFI",
310
        "EFI/systemd",
311
        "EFI/BOOT",
312
        "loader",
313
        "loader/keys",
314
        NULL
315
};
316

317
static const char *const dollar_boot_subdirs[] = {
318
        /* The directories to place in the XBOOTLDR partition or the ESP, depending what exists */
319
        "loader",
320
        "loader/entries",  /* Type #1 entries */
321
        "EFI",
322
        "EFI/Linux",       /* Type #2 entries */
323
        NULL
324
};
325

326
static int create_subdirs(const char *root, const char * const *subdirs) {
26✔
327
        int r;
26✔
328

329
        STRV_FOREACH(i, subdirs) {
143✔
330
                r = mkdir_one(root, *i);
117✔
331
                if (r < 0)
117✔
332
                        return r;
333
        }
334

335
        return 0;
336
}
337

338
static int update_efi_boot_binaries(const char *esp_path, const char *source_path) {
126✔
339
        _cleanup_closedir_ DIR *d = NULL;
126✔
340
        _cleanup_free_ char *p = NULL;
126✔
341
        int r, ret = 0;
126✔
342

343
        r = chase_and_opendir("/EFI/BOOT", esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &p, &d);
126✔
344
        if (r == -ENOENT)
126✔
345
                return 0;
346
        if (r < 0)
126✔
347
                return log_error_errno(r, "Failed to open directory \"%s/EFI/BOOT\": %m", esp_path);
×
348

349
        FOREACH_DIRENT(de, d, break) {
630✔
350
                _cleanup_close_ int fd = -EBADF;
252✔
351
                _cleanup_free_ char *v = NULL;
126✔
352

353
                if (!endswith_no_case(de->d_name, ".efi"))
252✔
354
                        continue;
×
355

356
                fd = xopenat_full(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_NOFOLLOW, XO_REGULAR, /* mode= */ 0);
252✔
357
                if (fd < 0)
252✔
NEW
358
                        return log_error_errno(fd, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
×
359

360
                r = pe_is_native_fd(fd);
252✔
361
                if (r < 0) {
252✔
NEW
362
                        log_warning_errno(r, "Failed to detect if \"%s/%s\" is native architecture, ignoring: %m", p, de->d_name);
×
NEW
363
                        continue;
×
364
                }
365
                if (r == 0)
252✔
366
                        continue;
126✔
367

368
                r = get_file_version(fd, &v);
126✔
369
                if (r == -ESRCH)
126✔
370
                        continue;  /* No version information */
×
371
                if (r < 0)
126✔
372
                        return r;
373
                if (!startswith(v, "systemd-boot "))
126✔
NEW
374
                        continue;
×
375

376
                _cleanup_free_ char *dest_path = path_join(p, de->d_name);
252✔
377
                if (!dest_path)
126✔
NEW
378
                        return log_oom();
×
379

380
                RET_GATHER(ret, copy_file_with_version_check(source_path, dest_path, /* force = */ false));
126✔
381
        }
382

383
        return ret;
384
}
385

386
static int copy_one_file(const char *esp_path, const char *name, bool force) {
145✔
387
        char *root = IN_SET(arg_install_source, ARG_INSTALL_SOURCE_AUTO, ARG_INSTALL_SOURCE_IMAGE) ? arg_root : NULL;
145✔
388
        _cleanup_free_ char *source_path = NULL, *dest_path = NULL, *p = NULL, *q = NULL;
145✔
389
        const char *e;
145✔
390
        char *dest_name, *s;
145✔
391
        int r, ret;
145✔
392

393
        dest_name = strdupa_safe(name);
145✔
394
        s = endswith_no_case(dest_name, ".signed");
145✔
395
        if (s)
145✔
396
                *s = 0;
×
397

398
        p = path_join(BOOTLIBDIR, name);
145✔
399
        if (!p)
145✔
400
                return log_oom();
×
401

402
        r = chase(p, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &source_path, NULL);
145✔
403
        /* If we had a root directory to try, we didn't find it and we are in auto mode, retry on the host */
404
        if (r == -ENOENT && root && arg_install_source == ARG_INSTALL_SOURCE_AUTO)
145✔
405
                r = chase(p, NULL, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &source_path, NULL);
16✔
406
        if (r < 0)
145✔
407
                return log_error_errno(r,
×
408
                                       "Failed to resolve path %s%s%s: %m",
409
                                       p,
410
                                       root ? " under directory " : "",
411
                                       strempty(root));
412

413
        q = path_join("/EFI/systemd/", dest_name);
145✔
414
        if (!q)
145✔
415
                return log_oom();
×
416

417
        r = chase(q, esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_NONEXISTENT, &dest_path, NULL);
145✔
418
        if (r < 0)
145✔
419
                return log_error_errno(r, "Failed to resolve path %s under directory %s: %m", q, esp_path);
×
420

421
        /* Note that if this fails we do the second copy anyway, but return this error code,
422
         * so we stash it away in a separate variable. */
423
        ret = copy_file_with_version_check(source_path, dest_path, force);
145✔
424

425
        e = startswith(dest_name, "systemd-boot");
145✔
426
        if (e) {
145✔
427
                _cleanup_free_ char *default_dest_path = NULL;
145✔
428
                char *v;
145✔
429

430
                /* Create the EFI default boot loader name (specified for removable devices) */
431
                v = strjoina("/EFI/BOOT/BOOT", e);
725✔
432
                ascii_strupper(strrchr(v, '/') + 1);
145✔
433

434
                r = chase(v, esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS|CHASE_NONEXISTENT, &default_dest_path, NULL);
145✔
435
                if (r < 0)
145✔
436
                        return log_error_errno(r, "Failed to resolve path %s under directory %s: %m", v, esp_path);
×
437

438
                RET_GATHER(ret, copy_file_with_version_check(source_path, default_dest_path, force));
145✔
439

440
                /* If we were installed under any other name in /EFI/BOOT, make sure we update those binaries
441
                 * as well. */
442
                if (!force)
145✔
443
                        RET_GATHER(ret, update_efi_boot_binaries(esp_path, source_path));
126✔
444
        }
445

446
        return ret;
447
}
448

449
static int install_binaries(const char *esp_path, const char *arch, bool force) {
139✔
450
        char *root = IN_SET(arg_install_source, ARG_INSTALL_SOURCE_AUTO, ARG_INSTALL_SOURCE_IMAGE) ? arg_root : NULL;
139✔
451
        _cleanup_closedir_ DIR *d = NULL;
139✔
452
        _cleanup_free_ char *path = NULL;
139✔
453
        int r;
139✔
454

455
        r = chase_and_opendir(BOOTLIBDIR, root, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &path, &d);
139✔
456
        /* If we had a root directory to try, we didn't find it and we are in auto mode, retry on the host */
457
        if (r == -ENOENT && root && arg_install_source == ARG_INSTALL_SOURCE_AUTO)
139✔
458
                r = chase_and_opendir(BOOTLIBDIR, NULL, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &path, &d);
12✔
459
        if (r == -ENOENT && arg_graceful) {
139✔
460
                log_debug("Source directory does not exist, ignoring.");
×
461
                return 0;
×
462
        }
463
        if (r < 0)
139✔
464
                return log_error_errno(r, "Failed to open boot loader directory %s%s: %m", strempty(root), BOOTLIBDIR);
×
465

466
        const char *suffix = strjoina(arch, ".efi");
695✔
467
        const char *suffix_signed = strjoina(arch, ".efi.signed");
695✔
468

469
        FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read \"%s\": %m", path)) {
1,251✔
470
                int k;
834✔
471

472
                if (!endswith_no_case(de->d_name, suffix) && !endswith_no_case(de->d_name, suffix_signed))
834✔
473
                        continue;
689✔
474

475
                /* skip the .efi file, if there's a .signed version of it */
476
                if (endswith_no_case(de->d_name, ".efi")) {
145✔
477
                        _cleanup_free_ const char *s = strjoin(de->d_name, ".signed");
290✔
478
                        if (!s)
145✔
479
                                return log_oom();
×
480
                        if (faccessat(dirfd(d), s, F_OK, 0) >= 0)
145✔
481
                                continue;
×
482
                }
483

484
                k = copy_one_file(esp_path, de->d_name, force);
145✔
485
                /* Don't propagate an error code if no update necessary, installed version already equal or
486
                 * newer version, or other boot loader in place. */
487
                if (arg_graceful && IN_SET(k, -ESTALE, -ESRCH))
145✔
488
                        continue;
123✔
489
                RET_GATHER(r, k);
22✔
490
        }
491

492
        return r;
493
}
494

495
static int install_loader_config(const char *esp_path) {
13✔
496
        _cleanup_(unlink_and_freep) char *t = NULL;
×
497
        _cleanup_fclose_ FILE *f = NULL;
13✔
498
        _cleanup_free_ char *p = NULL;
13✔
499
        int r;
13✔
500

501
        assert(arg_make_entry_directory >= 0);
13✔
502

503
        p = path_join(esp_path, "/loader/loader.conf");
13✔
504
        if (!p)
13✔
505
                return log_oom();
×
506
        if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
13✔
507
                return 0;
508

509
        r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
12✔
510
        if (r < 0)
12✔
511
                return log_error_errno(r, "Failed to open \"%s\" for writing: %m", p);
×
512

513
        fprintf(f, "#timeout 3\n"
12✔
514
                   "#console-mode keep\n");
515

516
        if (arg_make_entry_directory) {
12✔
517
                assert(arg_entry_token);
6✔
518
                fprintf(f, "default %s-*\n", arg_entry_token);
6✔
519
        }
520

521
        r = flink_tmpfile(f, t, p, LINK_TMPFILE_SYNC);
12✔
522
        if (r == -EEXIST)
12✔
523
                return 0; /* Silently skip creation if the file exists now (recheck) */
524
        if (r < 0)
12✔
525
                return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
×
526

527
        t = mfree(t);
12✔
528
        return 1;
12✔
529
}
530

531
static int install_loader_specification(const char *root) {
136✔
532
        _cleanup_(unlink_and_freep) char *t = NULL;
×
533
        _cleanup_fclose_ FILE *f = NULL;
136✔
534
        _cleanup_free_ char *p = NULL;
136✔
535
        int r;
136✔
536

537
        p = path_join(root, "/loader/entries.srel");
136✔
538
        if (!p)
136✔
539
                return log_oom();
×
540

541
        if (access(p, F_OK) >= 0) /* Silently skip creation if the file already exists (early check) */
136✔
542
                return 0;
543

544
        r = fopen_tmpfile_linkable(p, O_WRONLY|O_CLOEXEC, &t, &f);
12✔
545
        if (r < 0)
12✔
546
                return log_error_errno(r, "Failed to open \"%s\" for writing: %m", p);
×
547

548
        fprintf(f, "type1\n");
12✔
549

550
        r = flink_tmpfile(f, t, p, LINK_TMPFILE_SYNC);
12✔
551
        if (r == -EEXIST)
12✔
552
                return 0; /* Silently skip creation if the file exists now (recheck) */
553
        if (r < 0)
12✔
554
                return log_error_errno(r, "Failed to move \"%s\" into place: %m", p);
×
555

556
        t = mfree(t);
12✔
557
        return 1;
12✔
558
}
559

560
static int install_entry_directory(const char *root) {
13✔
561
        assert(root);
13✔
562
        assert(arg_make_entry_directory >= 0);
13✔
563

564
        if (!arg_make_entry_directory)
13✔
565
                return 0;
566

567
        assert(arg_entry_token);
7✔
568
        return mkdir_one(root, arg_entry_token);
7✔
569
}
570

571
static int install_entry_token(void) {
13✔
572
        _cleanup_free_ char* p = NULL;
13✔
573
        int r;
13✔
574

575
        assert(arg_make_entry_directory >= 0);
13✔
576
        assert(arg_entry_token);
13✔
577

578
        /* Let's save the used entry token in /etc/kernel/entry-token if we used it to create the entry
579
         * directory, or if anything else but the machine ID */
580

581
        if (!arg_make_entry_directory && arg_entry_token_type == BOOT_ENTRY_TOKEN_MACHINE_ID)
13✔
582
                return 0;
583

584
        p = path_join(arg_root, getenv("KERNEL_INSTALL_CONF_ROOT") ?: "/etc/kernel/", "entry-token");
26✔
585
        if (!p)
13✔
586
                return log_oom();
×
587

588
        r = write_string_file(p, arg_entry_token, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MKDIR_0755);
13✔
589
        if (r < 0)
13✔
590
                return log_error_errno(r, "Failed to write entry token '%s' to %s: %m", arg_entry_token, p);
×
591

592
        return 0;
593
}
594

595
#if HAVE_OPENSSL
596
static int efi_timestamp(EFI_TIME *ret) {
1✔
597
        uint64_t epoch = UINT64_MAX;
1✔
598
        struct tm tm = {};
1✔
599
        int r;
1✔
600

601
        assert(ret);
1✔
602

603
        r = secure_getenv_uint64("SOURCE_DATE_EPOCH", &epoch);
1✔
604
        if (r != -ENXIO)
1✔
605
                log_debug_errno(r, "Failed to parse $SOURCE_DATE_EPOCH, ignoring: %m");
×
606

607
        r = localtime_or_gmtime_usec(epoch != UINT64_MAX ? epoch : now(CLOCK_REALTIME), /*utc=*/ true, &tm);
1✔
608
        if (r < 0)
1✔
609
                return log_error_errno(r, "Failed to convert timestamp to calendar time: %m");
×
610

611
        *ret = (EFI_TIME) {
1✔
612
                .Year = 1900 + tm.tm_year,
1✔
613
                /* tm_mon starts at 0, EFI_TIME months start at 1. */
614
                .Month = tm.tm_mon + 1,
1✔
615
                .Day = tm.tm_mday,
1✔
616
                .Hour = tm.tm_hour,
1✔
617
                .Minute = tm.tm_min,
1✔
618
                .Second = tm.tm_sec,
1✔
619
        };
620

621
        return 0;
1✔
622
}
623
#endif
624

625
static int install_secure_boot_auto_enroll(const char *esp, X509 *certificate, EVP_PKEY *private_key) {
1✔
626
#if HAVE_OPENSSL
627
        int r;
1✔
628

629
        _cleanup_free_ uint8_t *dercert = NULL;
1✔
630
        int dercertsz;
1✔
631
        dercertsz = i2d_X509(certificate, &dercert);
1✔
632
        if (dercertsz < 0)
1✔
633
                return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert X.509 certificate to DER: %s",
×
634
                                       ERR_error_string(ERR_get_error(), NULL));
635

636
        r = mkdir_one(esp, "loader/keys/auto");
1✔
637
        if (r < 0)
1✔
638
                return r;
639

640
        _cleanup_close_ int keys_fd = chase_and_open("loader/keys/auto", esp, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, O_DIRECTORY, NULL);
2✔
641
        if (keys_fd < 0)
1✔
642
                return log_error_errno(keys_fd, "Failed to chase loader/keys/auto in the ESP: %m");
×
643

644
        uint32_t siglistsz = offsetof(EFI_SIGNATURE_LIST, Signatures) + offsetof(EFI_SIGNATURE_DATA, SignatureData) + dercertsz;
1✔
645
        /* We use malloc0() to zero-initialize the SignatureOwner field of Signatures[0]. */
646
        _cleanup_free_ EFI_SIGNATURE_LIST *siglist = malloc0(siglistsz);
2✔
647
        if (!siglist)
1✔
648
                return log_oom();
×
649

650
        *siglist = (EFI_SIGNATURE_LIST) {
1✔
651
                .SignatureType = EFI_CERT_X509_GUID,
652
                .SignatureListSize = siglistsz,
653
                .SignatureSize = offsetof(EFI_SIGNATURE_DATA, SignatureData) + dercertsz,
1✔
654
        };
655

656
        memcpy(siglist->Signatures[0].SignatureData, dercert, dercertsz);
1✔
657

658
        EFI_TIME timestamp;
1✔
659
        r = efi_timestamp(&timestamp);
1✔
660
        if (r < 0)
1✔
661
                return r;
662

663
        uint32_t attrs =
1✔
664
                EFI_VARIABLE_NON_VOLATILE|
665
                EFI_VARIABLE_BOOTSERVICE_ACCESS|
666
                EFI_VARIABLE_RUNTIME_ACCESS|
667
                EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
668

669
        FOREACH_STRING(db, "PK", "KEK", "db") {
4✔
670
                _cleanup_(BIO_freep) BIO *bio = NULL;
3✔
671

672
                bio = BIO_new(BIO_s_mem());
3✔
673
                if (!bio)
3✔
674
                        return log_oom();
×
675

676
                _cleanup_free_ char16_t *db16 = utf8_to_utf16(db, SIZE_MAX);
6✔
677
                if (!db16)
3✔
678
                        return log_oom();
×
679

680
                /* Don't count the trailing NUL terminator. */
681
                if (BIO_write(bio, db16, char16_strsize(db16) - sizeof(char16_t)) < 0)
3✔
682
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write variable name to bio");
×
683

684
                EFI_GUID *guid = STR_IN_SET(db, "PK", "KEK") ? &(EFI_GUID) EFI_GLOBAL_VARIABLE : &(EFI_GUID) EFI_IMAGE_SECURITY_DATABASE_GUID;
3✔
685

686
                if (BIO_write(bio, guid, sizeof(*guid)) < 0)
3✔
687
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write variable GUID to bio");
×
688

689
                if (BIO_write(bio, &attrs, sizeof(attrs)) < 0)
3✔
690
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write variable attributes to bio");
×
691

692
                if (BIO_write(bio, &timestamp, sizeof(timestamp)) < 0)
3✔
693
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write timestamp to bio");
×
694

695
                if (BIO_write(bio, siglist, siglistsz) < 0)
3✔
696
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to write signature list to bio");
×
697

698
                _cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
3✔
699
                p7 = PKCS7_sign(certificate, private_key, /*certs=*/ NULL, bio, PKCS7_DETACHED|PKCS7_NOATTR|PKCS7_BINARY|PKCS7_NOSMIMECAP);
3✔
700
                if (!p7)
3✔
701
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to calculate PKCS7 signature: %s",
×
702
                                               ERR_error_string(ERR_get_error(), NULL));
703

704
                _cleanup_free_ uint8_t *sig = NULL;
×
705
                int sigsz = i2d_PKCS7(p7, &sig);
3✔
706
                if (sigsz < 0)
3✔
707
                        return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to convert PKCS7 signature to DER: %s",
×
708
                                               ERR_error_string(ERR_get_error(), NULL));
709

710
                size_t authsz = offsetof(EFI_VARIABLE_AUTHENTICATION_2, AuthInfo.CertData) + sigsz;
3✔
711
                _cleanup_free_ EFI_VARIABLE_AUTHENTICATION_2 *auth = malloc(authsz);
×
712
                if (!auth)
3✔
713
                        return log_oom();
×
714

715
                *auth = (EFI_VARIABLE_AUTHENTICATION_2) {
3✔
716
                        .TimeStamp = timestamp,
717
                        .AuthInfo = {
718
                                .Hdr = {
719
                                        .dwLength = offsetof(WIN_CERTIFICATE_UEFI_GUID, CertData) + sigsz,
3✔
720
                                        .wRevision = 0x0200,
721
                                        .wCertificateType = 0x0EF1, /* WIN_CERT_TYPE_EFI_GUID */
722
                                },
723
                                .CertType = EFI_CERT_TYPE_PKCS7_GUID,
724
                        }
725
                };
726

727
                memcpy(auth->AuthInfo.CertData, sig, sigsz);
3✔
728

729
                _cleanup_free_ char *filename = strjoin(db, ".auth");
6✔
730
                if (!filename)
3✔
731
                        return log_oom();
×
732

733
                _cleanup_close_ int fd = openat(keys_fd, filename, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|O_WRONLY|O_CLOEXEC, 0600);
6✔
734
                if (fd < 0)
3✔
735
                        return log_error_errno(fd, "Failed to open secure boot auto-enrollment file for writing: %m");
×
736

737
                r = loop_write(fd, auth, authsz);
3✔
738
                if (r < 0)
3✔
739
                        return log_error_errno(r, "Failed to write authentication descriptor to secure boot auto-enrollment file: %m");
×
740

741
                r = loop_write(fd, siglist, siglistsz);
3✔
742
                if (r < 0)
3✔
743
                        return log_error_errno(r, "Failed to write signature list to secure boot auto-enrollment file: %m");
×
744

745
                if (fsync(fd) < 0 || fsync(keys_fd) < 0)
3✔
746
                        return log_error_errno(errno, "Failed to sync secure boot auto-enrollment file: %m");
×
747

748
                log_info("Secure boot auto-enrollment file %s/loader/keys/auto/%s successfully written.", esp, filename);
3✔
749
        }
750

751
        return 0;
1✔
752
#else
753
        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "OpenSSL is not supported, cannot set up secure boot auto-enrollment.");
754
#endif
755
}
756

757
static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
×
758
        _cleanup_free_ char *opath = NULL;
×
759
        sd_id128_t ouuid;
×
760
        int r;
×
761

762
        r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
×
763
        if (r < 0)
×
764
                return false;
765
        if (!sd_id128_equal(uuid, ouuid))
×
766
                return false;
×
767

768
        /* Some motherboards convert the path to uppercase under certain circumstances
769
         * (e.g. after booting into the Boot Menu in the ASUS ROG STRIX B350-F GAMING),
770
         * so use case-insensitive checking */
771
        if (!strcaseeq_ptr(path, opath))
×
772
                return false;
×
773

774
        return true;
775
}
776

777
static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
×
778
        _cleanup_free_ uint16_t *options = NULL;
×
779

780
        int n = efi_get_boot_options(&options);
×
781
        if (n < 0)
×
782
                return n;
783

784
        /* find already existing systemd-boot entry */
785
        for (int i = 0; i < n; i++)
×
786
                if (same_entry(options[i], uuid, path)) {
×
787
                        *id = options[i];
×
788
                        return 1;
×
789
                }
790

791
        /* find free slot in the sorted BootXXXX variable list */
792
        for (int i = 0; i < n; i++)
×
793
                if (i != options[i]) {
×
794
                        *id = i;
×
795
                        return 0;
×
796
                }
797

798
        /* use the next one */
799
        if (n == 0xffff)
×
800
                return -ENOSPC;
801
        *id = n;
×
802
        return 0;
×
803
}
804

805
static int insert_into_order(uint16_t slot, bool first) {
×
806
        _cleanup_free_ uint16_t *order = NULL;
×
807
        uint16_t *t;
×
808
        int n;
×
809

810
        n = efi_get_boot_order(&order);
×
811
        if (n <= 0)
×
812
                /* no entry, add us */
813
                return efi_set_boot_order(&slot, 1);
×
814

815
        /* are we the first and only one? */
816
        if (n == 1 && order[0] == slot)
×
817
                return 0;
818

819
        /* are we already in the boot order? */
820
        for (int i = 0; i < n; i++) {
×
821
                if (order[i] != slot)
×
822
                        continue;
×
823

824
                /* we do not require to be the first one, all is fine */
825
                if (!first)
×
826
                        return 0;
827

828
                /* move us to the first slot */
829
                memmove(order + 1, order, i * sizeof(uint16_t));
×
830
                order[0] = slot;
×
831
                return efi_set_boot_order(order, n);
×
832
        }
833

834
        /* extend array */
835
        t = reallocarray(order, n + 1, sizeof(uint16_t));
×
836
        if (!t)
×
837
                return -ENOMEM;
838
        order = t;
×
839

840
        /* add us to the top or end of the list */
841
        if (first) {
×
842
                memmove(order + 1, order, n * sizeof(uint16_t));
×
843
                order[0] = slot;
×
844
        } else
845
                order[n] = slot;
×
846

847
        return efi_set_boot_order(order, n + 1);
×
848
}
849

850
static int remove_from_order(uint16_t slot) {
×
851
        _cleanup_free_ uint16_t *order = NULL;
×
852
        int n;
×
853

854
        n = efi_get_boot_order(&order);
×
855
        if (n <= 0)
×
856
                return n;
857

858
        for (int i = 0; i < n; i++) {
×
859
                if (order[i] != slot)
×
860
                        continue;
×
861

862
                if (i + 1 < n)
×
863
                        memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
×
864
                return efi_set_boot_order(order, n - 1);
×
865
        }
866

867
        return 0;
868
}
869

870
static const char *pick_efi_boot_option_description(void) {
×
871
        return arg_efi_boot_option_description ?: "Linux Boot Manager";
×
872
}
873

874
static int install_variables(
×
875
                const char *esp_path,
876
                uint32_t part,
877
                uint64_t pstart,
878
                uint64_t psize,
879
                sd_id128_t uuid,
880
                const char *path,
881
                bool first,
882
                bool graceful) {
883

884
        uint16_t slot;
×
885
        int r;
×
886

887
        r = chase_and_access(path, esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, F_OK, NULL);
×
888
        if (r == -ENOENT)
×
889
                return 0;
×
890
        if (r < 0)
×
891
                return log_error_errno(r, "Cannot access \"%s/%s\": %m", esp_path, skip_leading_slash(path));
×
892

893
        r = find_slot(uuid, path, &slot);
×
894
        if (r < 0) {
×
895
                int level = graceful ? arg_quiet ? LOG_DEBUG : LOG_INFO : LOG_ERR;
×
896
                const char *skip = graceful ? ", skipping" : "";
897

898
                log_full_errno(level, r,
×
899
                               r == -ENOENT ?
900
                               "Failed to access EFI variables%s. Is the \"efivarfs\" filesystem mounted?" :
901
                               "Failed to determine current boot order%s: %m", skip);
902

903
                return graceful ? 0 : r;
×
904
        }
905

906
        if (first || r == 0) {
×
907
                r = efi_add_boot_option(slot, pick_efi_boot_option_description(),
×
908
                                        part, pstart, psize,
909
                                        uuid, path);
910
                if (r < 0) {
×
911
                        int level = graceful ? arg_quiet ? LOG_DEBUG : LOG_INFO : LOG_ERR;
×
912
                        const char *skip = graceful ? ", skipping" : "";
913

914
                        log_full_errno(level, r, "Failed to create EFI Boot variable entry%s: %m", skip);
×
915

916
                        return graceful ? 0 : r;
×
917
                }
918

919
                log_info("Created EFI boot entry \"%s\".", pick_efi_boot_option_description());
×
920
        }
921

922
        return insert_into_order(slot, first);
×
923
}
924

925
static int are_we_installed(const char *esp_path) {
138✔
926
        int r;
138✔
927

928
        /* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
929
         * check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
930
         * loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
931
         * should be a suitable and very minimal check for a number of reasons:
932
         *
933
         *  → The check is architecture independent (i.e. we check if any systemd-boot loader is installed,
934
         *    not a specific one.)
935
         *
936
         *  → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
937
         *    /EFI/BOOT/BOOT*.EFI fallback binary.
938
         *
939
         *  → It specifically checks for systemd-boot, not for other boot loaders (which a check for
940
         *    /boot/loader/entries would do). */
941

942
        _cleanup_free_ char *p = path_join(esp_path, "/EFI/systemd/");
276✔
943
        if (!p)
138✔
944
                return log_oom();
×
945

946
        log_debug("Checking whether %s contains any files%s", p, glyph(GLYPH_ELLIPSIS));
258✔
947
        r = dir_is_empty(p, /* ignore_hidden_or_backup= */ false);
138✔
948
        if (r < 0 && r != -ENOENT)
138✔
949
                return log_error_errno(r, "Failed to check whether %s contains any files: %m", p);
×
950

951
        return r == 0;
138✔
952
}
953

954
int verb_install(int argc, char *argv[], void *userdata) {
139✔
955
        _cleanup_(X509_freep) X509 *certificate = NULL;
139✔
956
        _cleanup_(openssl_ask_password_ui_freep) OpenSSLAskPasswordUI *ui = NULL;
139✔
957
        _cleanup_(EVP_PKEY_freep) EVP_PKEY *private_key = NULL;
139✔
958
        sd_id128_t uuid = SD_ID128_NULL;
139✔
959
        uint64_t pstart = 0, psize = 0;
139✔
960
        uint32_t part = 0;
139✔
961
        bool install, graceful;
139✔
962
        int r;
139✔
963

964
        /* Invoked for both "update" and "install" */
965

966
        install = streq(argv[0], "install");
139✔
967
        graceful = !install && arg_graceful; /* support graceful mode for updates */
139✔
968

969
        if (arg_secure_boot_auto_enroll) {
139✔
970
                if (arg_certificate_source_type == OPENSSL_CERTIFICATE_SOURCE_FILE) {
1✔
971
                        r = parse_path_argument(arg_certificate, /*suppress_root=*/ false, &arg_certificate);
1✔
972
                        if (r < 0)
1✔
973
                                return r;
×
974
                }
975

976
                r = openssl_load_x509_certificate(
1✔
977
                                arg_certificate_source_type,
978
                                arg_certificate_source,
979
                                arg_certificate,
980
                                &certificate);
981
                if (r < 0)
1✔
982
                        return log_error_errno(r, "Failed to load X.509 certificate from %s: %m", arg_certificate);
×
983

984
                if (arg_private_key_source_type == OPENSSL_KEY_SOURCE_FILE) {
1✔
985
                        r = parse_path_argument(arg_private_key, /* suppress_root= */ false, &arg_private_key);
1✔
986
                        if (r < 0)
1✔
987
                                return log_error_errno(r, "Failed to parse private key path %s: %m", arg_private_key);
×
988
                }
989

990
                r = openssl_load_private_key(
2✔
991
                                arg_private_key_source_type,
992
                                arg_private_key_source,
993
                                arg_private_key,
994
                                &(AskPasswordRequest) {
1✔
995
                                        .tty_fd = -EBADF,
996
                                        .id = "bootctl-private-key-pin",
997
                                        .keyring = arg_private_key,
998
                                        .credential = "bootctl.private-key-pin",
999
                                        .until = USEC_INFINITY,
1000
                                        .hup_fd = -EBADF,
1001
                                },
1002
                                &private_key,
1003
                                &ui);
1004
                if (r < 0)
1✔
1005
                        return log_error_errno(r, "Failed to load private key from %s: %m", arg_private_key);
×
1006
        }
1007

1008
        r = acquire_esp(/* unprivileged_mode= */ false, graceful, &part, &pstart, &psize, &uuid, NULL);
139✔
1009
        if (graceful && r == -ENOKEY)
139✔
1010
                return 0; /* If --graceful is specified and we can't find an ESP, handle this cleanly */
1011
        if (r < 0)
139✔
1012
                return r;
1013

1014
        if (!install) {
139✔
1015
                /* If we are updating, don't do anything if sd-boot wasn't actually installed. */
1016
                r = are_we_installed(arg_esp_path);
126✔
1017
                if (r < 0)
126✔
1018
                        return r;
1019
                if (r == 0) {
126✔
1020
                        log_debug("Skipping update because sd-boot is not installed in the ESP.");
×
1021
                        return 0;
×
1022
                }
1023
        }
1024

1025
        r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
139✔
1026
        if (r < 0)
139✔
1027
                return r;
1028

1029
        r = settle_make_entry_directory();
139✔
1030
        if (r < 0)
139✔
1031
                return r;
1032

1033
        const char *arch = arg_arch_all ? "" : get_efi_arch();
139✔
1034

1035
        WITH_UMASK(0002) {
278✔
1036
                if (install) {
139✔
1037
                        /* Don't create any of these directories when we are just updating. When we update
1038
                         * we'll drop-in our files (unless there are newer ones already), but we won't create
1039
                         * the directories for them in the first place. */
1040
                        r = create_subdirs(arg_esp_path, esp_subdirs);
13✔
1041
                        if (r < 0)
13✔
1042
                                return r;
1043

1044
                        r = create_subdirs(arg_dollar_boot_path(), dollar_boot_subdirs);
18✔
1045
                        if (r < 0)
13✔
1046
                                return r;
1047
                }
1048

1049
                r = install_binaries(arg_esp_path, arch, install);
139✔
1050
                if (r < 0)
139✔
1051
                        return r;
1052

1053
                if (install) {
136✔
1054
                        r = install_loader_config(arg_esp_path);
13✔
1055
                        if (r < 0)
13✔
1056
                                return r;
1057

1058
                        r = install_entry_directory(arg_dollar_boot_path());
18✔
1059
                        if (r < 0)
13✔
1060
                                return r;
1061

1062
                        r = install_entry_token();
13✔
1063
                        if (r < 0)
13✔
1064
                                return r;
1065

1066
                        if (arg_install_random_seed) {
13✔
1067
                                r = install_random_seed(arg_esp_path);
13✔
1068
                                if (r < 0)
13✔
1069
                                        return r;
1070
                        }
1071

1072
                        if (arg_secure_boot_auto_enroll) {
13✔
1073
                                r = install_secure_boot_auto_enroll(arg_esp_path, certificate, private_key);
1✔
1074
                                if (r < 0)
1✔
1075
                                        return r;
1076
                        }
1077
                }
1078

1079
                r = install_loader_specification(arg_dollar_boot_path());
207✔
1080
                if (r < 0)
136✔
1081
                        return r;
1082
        }
1083

1084
        (void) sync_everything();
136✔
1085

1086
        if (!touch_variables())
136✔
1087
                return 0;
1088

1089
        if (arg_arch_all) {
×
1090
                log_info("Not changing EFI variables with --all-architectures.");
×
1091
                return 0;
×
1092
        }
1093

1094
        char *path = strjoina("/EFI/systemd/systemd-boot", arch, ".efi");
×
1095
        return install_variables(arg_esp_path, part, pstart, psize, uuid, path, install, graceful);
×
1096
}
1097

1098
static int remove_boot_efi(const char *esp_path) {
13✔
1099
        _cleanup_closedir_ DIR *d = NULL;
13✔
1100
        _cleanup_free_ char *p = NULL;
13✔
1101
        int r, c = 0;
13✔
1102

1103
        r = chase_and_opendir("/EFI/BOOT", esp_path, CHASE_PREFIX_ROOT|CHASE_PROHIBIT_SYMLINKS, &p, &d);
13✔
1104
        if (r == -ENOENT)
13✔
1105
                return 0;
1106
        if (r < 0)
13✔
1107
                return log_error_errno(r, "Failed to open directory \"%s/EFI/BOOT\": %m", esp_path);
×
1108

1109
        FOREACH_DIRENT(de, d, break) {
63✔
1110
                _cleanup_close_ int fd = -EBADF;
24✔
1111
                _cleanup_free_ char *v = NULL;
24✔
1112

1113
                if (!endswith_no_case(de->d_name, ".efi"))
24✔
1114
                        continue;
×
1115

1116
                fd = xopenat_full(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_NOFOLLOW, XO_REGULAR, /* mode= */ 0);
24✔
1117
                if (fd < 0)
24✔
NEW
1118
                        return log_error_errno(fd, "Failed to open \"%s/%s\" for reading: %m", p, de->d_name);
×
1119

1120
                r = pe_is_native_fd(fd);
24✔
1121
                if (r < 0) {
24✔
NEW
1122
                        log_warning_errno(r, "Failed to detect if \"%s/%s\" is native architecture, ignoring: %m", p, de->d_name);
×
NEW
1123
                        continue;
×
1124
                }
1125
                if (r == 0)
24✔
1126
                        continue;
11✔
1127

1128
                r = get_file_version(fd, &v);
13✔
1129
                if (r == -ESRCH)
13✔
1130
                        continue;  /* No version information */
×
1131
                if (r < 0)
13✔
1132
                        return r;
1133
                if (startswith(v, "systemd-boot ")) {
13✔
1134
                        if (unlinkat(dirfd(d), de->d_name, 0) < 0)
13✔
UNCOV
1135
                                return log_error_errno(errno, "Failed to remove \"%s/%s\": %m", p, de->d_name);
×
1136

1137
                        log_info("Removed \"%s/%s\".", p, de->d_name);
13✔
1138
                }
1139

1140
                c++;
13✔
1141
        }
1142

1143
        return c;
1144
}
1145

1146
static int rmdir_one(const char *prefix, const char *suffix) {
172✔
1147
        _cleanup_free_ char *p = path_join(prefix, suffix);
344✔
1148
        if (!p)
172✔
1149
                return log_oom();
×
1150

1151
        if (rmdir(p) < 0) {
172✔
1152
                bool ignore = IN_SET(errno, ENOENT, ENOTEMPTY);
98✔
1153

1154
                log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, errno,
98✔
1155
                               "Failed to remove directory \"%s\": %m", p);
1156
                if (!ignore)
98✔
1157
                        return -errno;
×
1158
        } else
1159
                log_info("Removed \"%s\".", p);
74✔
1160

1161
        return 0;
1162
}
1163

1164
static int remove_subdirs(const char *root, const char *const *subdirs) {
183✔
1165
        int r, q;
183✔
1166

1167
        /* We use recursion here to destroy the directories in reverse order. Which should be safe given how
1168
         * short the array is. */
1169

1170
        if (!subdirs[0]) /* A the end of the list */
183✔
1171
                return 0;
1172

1173
        r = remove_subdirs(root, subdirs + 1);
149✔
1174
        q = rmdir_one(root, subdirs[0]);
149✔
1175

1176
        return r < 0 ? r : q;
149✔
1177
}
1178

1179
static int remove_entry_directory(const char *root) {
21✔
1180
        assert(root);
21✔
1181
        assert(arg_make_entry_directory >= 0);
21✔
1182

1183
        if (!arg_make_entry_directory || !arg_entry_token)
21✔
1184
                return 0;
1185

1186
        return rmdir_one(root, arg_entry_token);
10✔
1187
}
1188

1189
static int remove_binaries(const char *esp_path) {
13✔
1190
        int r, q;
13✔
1191

1192
        _cleanup_free_ char *p = path_join(esp_path, "/EFI/systemd");
26✔
1193
        if (!p)
13✔
1194
                return log_oom();
×
1195

1196
        r = rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL);
13✔
1197

1198
        q = remove_boot_efi(esp_path);
13✔
1199
        if (q < 0 && r == 0)
13✔
1200
                r = q;
×
1201

1202
        return r;
1203
}
1204

1205
static int remove_file(const char *root, const char *file) {
86✔
1206
        assert(root);
86✔
1207
        assert(file);
86✔
1208

1209
        _cleanup_free_ char *p = path_join(root, file);
172✔
1210
        if (!p)
86✔
1211
                return log_oom();
×
1212

1213
        if (unlink(p) < 0) {
86✔
1214
                log_full_errno(errno == ENOENT ? LOG_DEBUG : LOG_ERR, errno,
44✔
1215
                               "Failed to unlink file \"%s\": %m", p);
1216

1217
                return errno == ENOENT ? 0 : -errno;
44✔
1218
        }
1219

1220
        log_info("Removed \"%s\".", p);
42✔
1221
        return 1;
1222
}
1223

1224
static int remove_variables(sd_id128_t uuid, const char *path, bool in_order) {
×
1225
        uint16_t slot;
×
1226
        int r;
×
1227

1228
        r = find_slot(uuid, path, &slot);
×
1229
        if (r != 1)
×
1230
                return 0;
×
1231

1232
        r = efi_remove_boot_option(slot);
×
1233
        if (r < 0)
×
1234
                return r;
1235

1236
        if (in_order)
×
1237
                return remove_from_order(slot);
×
1238

1239
        return 0;
1240
}
1241

1242
static int remove_loader_variables(void) {
×
1243
        int r = 0;
×
1244

1245
        /* Remove all persistent loader variables we define */
1246

1247
        FOREACH_STRING(var,
×
1248
                       EFI_LOADER_VARIABLE_STR("LoaderConfigConsoleMode"),
1249
                       EFI_LOADER_VARIABLE_STR("LoaderConfigTimeout"),
1250
                       EFI_LOADER_VARIABLE_STR("LoaderConfigTimeoutOneShot"),
1251
                       EFI_LOADER_VARIABLE_STR("LoaderEntryDefault"),
1252
                       EFI_LOADER_VARIABLE_STR("LoaderEntrySysFail"),
1253
                       EFI_LOADER_VARIABLE_STR("LoaderEntryLastBooted"),
1254
                       EFI_LOADER_VARIABLE_STR("LoaderEntryOneShot"),
1255
                       EFI_LOADER_VARIABLE_STR("LoaderSystemToken")) {
1256

1257
                int q;
×
1258

1259
                q = efi_set_variable(var, NULL, 0);
×
1260
                if (q == -ENOENT)
×
1261
                        continue;
×
1262
                if (q < 0) {
×
1263
                        log_warning_errno(q, "Failed to remove EFI variable %s: %m", var);
×
1264
                        if (r >= 0)
×
1265
                                r = q;
×
1266
                } else
1267
                        log_info("Removed EFI variable %s.", var);
×
1268
        }
1269

1270
        return r;
×
1271
}
1272

1273
int verb_remove(int argc, char *argv[], void *userdata) {
13✔
1274
        sd_id128_t uuid = SD_ID128_NULL;
13✔
1275
        int r, q;
13✔
1276

1277
        r = acquire_esp(/* unprivileged_mode= */ false, /* graceful= */ false, NULL, NULL, NULL, &uuid, NULL);
13✔
1278
        if (r < 0)
13✔
1279
                return r;
13✔
1280

1281
        r = acquire_xbootldr(/* unprivileged_mode= */ false, NULL, NULL);
13✔
1282
        if (r < 0)
13✔
1283
                return r;
1284

1285
        r = settle_make_entry_directory();
13✔
1286
        if (r < 0)
13✔
1287
                return r;
1288

1289
        r = remove_binaries(arg_esp_path);
13✔
1290

1291
        q = remove_file(arg_esp_path, "/loader/loader.conf");
13✔
1292
        if (q < 0 && r >= 0)
13✔
1293
                r = q;
×
1294

1295
        q = remove_file(arg_esp_path, "/loader/random-seed");
13✔
1296
        if (q < 0 && r >= 0)
13✔
1297
                r = q;
×
1298

1299
        q = remove_file(arg_esp_path, "/loader/entries.srel");
13✔
1300
        if (q < 0 && r >= 0)
13✔
1301
                r = q;
×
1302

1303
        FOREACH_STRING(db, "PK.auth", "KEK.auth", "db.auth") {
52✔
1304
                _cleanup_free_ char *p = path_join("/loader/keys/auto", db);
78✔
1305
                if (!p)
39✔
1306
                        return log_oom();
×
1307

1308
                q = remove_file(arg_esp_path, p);
39✔
1309
                if (q < 0 && r >= 0)
39✔
1310
                        r = q;
×
1311
        }
1312

1313
        q = rmdir_one(arg_esp_path, "/loader/keys/auto");
13✔
1314
        if (q < 0 && r >= 0)
13✔
1315
                r = q;
×
1316

1317
        q = remove_subdirs(arg_esp_path, esp_subdirs);
13✔
1318
        if (q < 0 && r >= 0)
13✔
1319
                r = q;
×
1320

1321
        q = remove_subdirs(arg_esp_path, dollar_boot_subdirs);
13✔
1322
        if (q < 0 && r >= 0)
13✔
1323
                r = q;
×
1324

1325
        q = remove_entry_directory(arg_esp_path);
13✔
1326
        if (q < 0 && r >= 0)
13✔
1327
                r = q;
×
1328

1329
        if (arg_xbootldr_path) {
13✔
1330
                /* Remove a subset of these also from the XBOOTLDR partition if it exists */
1331

1332
                q = remove_file(arg_xbootldr_path, "/loader/entries.srel");
8✔
1333
                if (q < 0 && r >= 0)
8✔
1334
                        r = q;
×
1335

1336
                q = remove_subdirs(arg_xbootldr_path, dollar_boot_subdirs);
8✔
1337
                if (q < 0 && r >= 0)
8✔
1338
                        r = q;
×
1339

1340
                q = remove_entry_directory(arg_xbootldr_path);
8✔
1341
                if (q < 0 && r >= 0)
8✔
1342
                        r = q;
×
1343
        }
1344

1345
        (void) sync_everything();
13✔
1346

1347
        if (!touch_variables())
13✔
1348
                return r;
1349

1350
        if (arg_arch_all) {
×
1351
                log_info("Not changing EFI variables with --all-architectures.");
×
1352
                return r;
×
1353
        }
1354

1355
        char *path = strjoina("/EFI/systemd/systemd-boot", get_efi_arch(), ".efi");
×
1356
        q = remove_variables(uuid, path, true);
×
1357
        if (q < 0 && r >= 0)
×
1358
                r = q;
×
1359

1360
        q = remove_loader_variables();
×
1361
        if (q < 0 && r >= 0)
×
1362
                r = q;
×
1363

1364
        return r;
1365
}
1366

1367
int verb_is_installed(int argc, char *argv[], void *userdata) {
12✔
1368
        int r;
12✔
1369

1370
        r = acquire_esp(/* unprivileged_mode= */ false,
12✔
1371
                        /* graceful= */ arg_graceful,
1372
                        NULL, NULL, NULL, NULL, NULL);
1373
        if (r < 0)
12✔
1374
                return r;
1375

1376
        r = are_we_installed(arg_esp_path);
12✔
1377
        if (r < 0)
12✔
1378
                return r;
1379

1380
        if (r > 0) {
12✔
1381
                if (!arg_quiet)
6✔
1382
                        puts("yes");
6✔
1383
                return EXIT_SUCCESS;
6✔
1384
        } else {
1385
                if (!arg_quiet)
6✔
1386
                        puts("no");
6✔
1387
                return EXIT_FAILURE;
6✔
1388
        }
1389
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc