HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/bootctl/bootctl-install.c
Git blob: f04157a70f5e2faf2d187583688156373f6e2a3e
Lines 1001–2000 of 2,206
return 0;
assert(c->entry_token);
int dollar_boot_fd = acquire_dollar_boot_fd(c);
if (dollar_boot_fd < 0)
return dollar_boot_fd;
_cleanup_free_ char *j = path_join(c->root, dollar_boot_path(c));
if (!j)
return log_oom();
return mkdir_one(j, dollar_boot_fd, c->entry_token);
}
static int install_entry_token(InstallContext *c) {
int r;
assert(c);
assert(c->make_entry_directory >= 0);
assert(c->entry_token);
/* Let's save the used entry token in /etc/kernel/entry-token if we used it to create the entry
* directory, or if anything else but the machine ID */
if (!c->make_entry_directory && c->entry_token_type == BOOT_ENTRY_TOKEN_MACHINE_ID)
return 0;
const char *confdir = secure_getenv("KERNEL_INSTALL_CONF_ROOT") ?: "/etc/kernel/";
_cleanup_free_ char *j = path_join(c->root, confdir);
if (!j)
return log_oom();
_cleanup_close_ int dfd = -EBADF;
r = chaseat(c->root_fd,
c->root_fd,
confdir,
CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY,
/* ret_path= */ NULL,
&dfd);
if (r < 0)
return log_error_errno(r, "Failed to open '%s': %m", j);
r = write_string_file_at(dfd, "entry-token", c->entry_token, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC|WRITE_STRING_FILE_MKDIR_0755);
if (r < 0)
return log_error_errno(r, "Failed to write entry token '%s' to '%s/entry-token': %m", c->entry_token, j);
return 0;
}
#if HAVE_OPENSSL
static int efi_timestamp(EFI_TIME *ret) {
struct tm tm = {};
int r;
assert(ret);
r = localtime_or_gmtime_usec(source_date_epoch_or_now(), /* utc= */ true, &tm);
if (r < 0)
return log_error_errno(r, "Failed to convert timestamp to calendar time: %m");
*ret = (EFI_TIME) {
.Year = 1900 + tm.tm_year,
/* tm_mon starts at 0, EFI_TIME months start at 1. */
.Month = tm.tm_mon + 1,
.Day = tm.tm_mday,
.Hour = tm.tm_hour,
.Minute = tm.tm_min,
.Second = tm.tm_sec,
};
return 0;
}
#endif
static int install_secure_boot_auto_enroll(InstallContext *c) {
#if HAVE_OPENSSL
int r;
#endif
if (!arg_secure_boot_auto_enroll)
return 0;
#if HAVE_OPENSSL
if (!c->secure_boot_certificate || !c->secure_boot_private_key)
return 0;
r = dlopen_libcrypto(LOG_DEBUG);
if (r < 0)
return r;
_cleanup_free_ uint8_t *dercert = NULL;
int dercertsz;
dercertsz = sym_i2d_X509(c->secure_boot_certificate, &dercert);
if (dercertsz < 0)
return log_openssl_errors(LOG_ERR, "Failed to convert X.509 certificate to DER");
if (c->esp_fd < 0)
return c->esp_fd;
_cleanup_free_ char *j = path_join(c->root, c->esp_path);
if (!j)
return log_oom();
_cleanup_close_ int keys_fd = -EBADF;
r = chaseat(c->esp_fd,
c->esp_fd,
"loader/keys/auto",
CHASE_PROHIBIT_SYMLINKS|CHASE_MKDIR_0755|CHASE_MUST_BE_DIRECTORY,
/* ret_path= */ NULL,
&keys_fd);
if (r < 0)
return log_error_errno(r, "Failed to chase /loader/keys/auto/ below '%s': %m", j);
uint32_t siglistsz = offsetof(EFI_SIGNATURE_LIST, Signatures) + offsetof(EFI_SIGNATURE_DATA, SignatureData) + dercertsz;
/* We use malloc0() to zero-initialize the SignatureOwner field of Signatures[0]. */
_cleanup_free_ EFI_SIGNATURE_LIST *siglist = malloc0(siglistsz);
if (!siglist)
return log_oom();
*siglist = (EFI_SIGNATURE_LIST) {
.SignatureType = EFI_CERT_X509_GUID,
.SignatureListSize = siglistsz,
.SignatureSize = offsetof(EFI_SIGNATURE_DATA, SignatureData) + dercertsz,
};
memcpy(siglist->Signatures[0].SignatureData, dercert, dercertsz);
EFI_TIME timestamp;
r = efi_timestamp(×tamp);
if (r < 0)
return r;
uint32_t attrs =
EFI_VARIABLE_NON_VOLATILE|
EFI_VARIABLE_BOOTSERVICE_ACCESS|
EFI_VARIABLE_RUNTIME_ACCESS|
EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS;
FOREACH_STRING(db, "PK", "KEK", "db") {
_cleanup_(BIO_freep) BIO *bio = NULL;
bio = sym_BIO_new(sym_BIO_s_mem());
if (!bio)
return log_oom();
_cleanup_free_ char16_t *db16 = utf8_to_utf16(db, SIZE_MAX);
if (!db16)
return log_oom();
/* Don't count the trailing NUL terminator. */
if (sym_BIO_write(bio, db16, char16_strsize(db16) - sizeof(char16_t)) < 0)
return log_openssl_errors(LOG_ERR, "Failed to write variable name to bio");
EFI_GUID *guid = STR_IN_SET(db, "PK", "KEK") ? &(EFI_GUID) EFI_GLOBAL_VARIABLE : &(EFI_GUID) EFI_IMAGE_SECURITY_DATABASE_GUID;
if (sym_BIO_write(bio, guid, sizeof(*guid)) < 0)
return log_openssl_errors(LOG_ERR, "Failed to write variable GUID to bio");
if (sym_BIO_write(bio, &attrs, sizeof(attrs)) < 0)
return log_openssl_errors(LOG_ERR, "Failed to write variable attributes to bio");
if (sym_BIO_write(bio, ×tamp, sizeof(timestamp)) < 0)
return log_openssl_errors(LOG_ERR, "Failed to write timestamp to bio");
if (sym_BIO_write(bio, siglist, siglistsz) < 0)
return log_openssl_errors(LOG_ERR, "Failed to write signature list to bio");
_cleanup_(PKCS7_freep) PKCS7 *p7 = NULL;
p7 = sym_PKCS7_sign(c->secure_boot_certificate, c->secure_boot_private_key, /* certs= */ NULL, bio, PKCS7_DETACHED|PKCS7_NOATTR|PKCS7_BINARY|PKCS7_NOSMIMECAP);
if (!p7)
return log_openssl_errors(LOG_ERR, "Failed to calculate PKCS7 signature");
_cleanup_free_ uint8_t *sig = NULL;
int sigsz = sym_i2d_PKCS7(p7, &sig);
if (sigsz < 0)
return log_openssl_errors(LOG_ERR, "Failed to convert PKCS7 signature to DER");
size_t authsz = offsetof(EFI_VARIABLE_AUTHENTICATION_2, AuthInfo.CertData) + sigsz;
_cleanup_free_ EFI_VARIABLE_AUTHENTICATION_2 *auth = malloc(authsz);
if (!auth)
return log_oom();
*auth = (EFI_VARIABLE_AUTHENTICATION_2) {
.TimeStamp = timestamp,
.AuthInfo = {
.Hdr = {
.dwLength = offsetof(WIN_CERTIFICATE_UEFI_GUID, CertData) + sigsz,
.wRevision = 0x0200,
.wCertificateType = 0x0EF1, /* WIN_CERT_TYPE_EFI_GUID */
},
.CertType = EFI_CERT_TYPE_PKCS7_GUID,
}
};
memcpy(auth->AuthInfo.CertData, sig, sigsz);
_cleanup_free_ char *filename = strjoin(db, ".auth");
if (!filename)
return log_oom();
_cleanup_free_ char *t = NULL;
_cleanup_close_ int fd = open_tmpfile_linkable_at(keys_fd, filename, O_WRONLY|O_CLOEXEC, &t);
if (fd < 0)
return log_error_errno(fd, "Failed to open secure boot auto-enrollment file for writing: %m");
CLEANUP_TMPFILE_AT(keys_fd, t);
r = loop_write(fd, auth, authsz);
if (r < 0)
return log_error_errno(r, "Failed to write authentication descriptor to secure boot auto-enrollment file: %m");
r = loop_write(fd, siglist, siglistsz);
if (r < 0)
return log_error_errno(r, "Failed to write signature list to secure boot auto-enrollment file: %m");
r = link_tmpfile_at(fd, keys_fd, t, filename, LINK_TMPFILE_SYNC);
if (r < 0)
return log_error_errno(r, "Failed to link secure boot auto-enrollment file: %m");
t = mfree(t); /* Disarm CLEANUP_TMPFILE_AT() */
log_info("Secure boot auto-enrollment file '%s/loader/keys/auto/%s' successfully written.", j, filename);
}
return 0;
#else
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Built without OpenSSL support, cannot set up auto-enrollment.");
#endif
}
static bool same_entry(uint16_t id, sd_id128_t uuid, const char *path) {
_cleanup_free_ char *opath = NULL;
sd_id128_t ouuid;
int r;
r = efi_get_boot_option(id, NULL, &ouuid, &opath, NULL);
if (r < 0)
return false;
if (!sd_id128_equal(uuid, ouuid))
return false;
/* Some motherboards convert the path to uppercase under certain circumstances
* (e.g. after booting into the Boot Menu in the ASUS ROG STRIX B350-F GAMING),
* so use case-insensitive checking */
if (!strcaseeq_ptr(path, opath))
return false;
return true;
}
static int find_slot(sd_id128_t uuid, const char *path, uint16_t *id) {
_cleanup_free_ uint16_t *options = NULL;
assert(id);
int n = efi_get_boot_options(&options);
if (n < 0)
return n;
/* find already existing systemd-boot entry */
for (int i = 0; i < n; i++)
if (same_entry(options[i], uuid, path)) {
*id = options[i];
return 1;
}
/* find free slot in the sorted BootXXXX variable list */
for (int i = 0; i < n; i++)
if (i != options[i]) {
*id = i;
return 0;
}
/* use the next one */
if (n == 0xffff)
return -ENOSPC;
*id = n;
return 0;
}
static int insert_into_order(InstallContext *c, uint16_t slot, uint16_t after_slot) {
_cleanup_free_ uint16_t *order = NULL;
uint16_t *t;
int n;
assert(c);
n = efi_get_boot_order(&order);
if (n <= 0)
/* no entry, add us */
return efi_set_boot_order(&slot, 1);
/* are we the first and only one? */
if (n == 1 && order[0] == slot)
return 0;
/* are we already in the boot order? */
for (int i = 0; i < n; i++) {
if (order[i] != slot)
continue;
/* we do not require to be the first one, all is fine */
/* if after_slot is set, leave existing position alone to preserve user reordering. */
if (i == 0 || c->operation != INSTALL_NEW || after_slot != UINT16_MAX)
return 0;
/* move us to the first slot */
memmove(order + 1, order, i * sizeof(uint16_t));
order[0] = slot;
return efi_set_boot_order(order, n);
}
/* slot is not yet in the order, so insert after a specific slot if requested */
if (after_slot != UINT16_MAX) {
t = reallocarray(order, n + 1, sizeof(uint16_t));
if (!t)
return -ENOMEM;
order = t;
for (int i = 0; i < n; i++) {
if (order[i] != after_slot)
continue;
memmove(order + i + 2, order + i + 1, (n - i - 1) * sizeof(uint16_t));
order[i + 1] = slot;
return efi_set_boot_order(order, n + 1);
}
log_warning("Boot entry %04" PRIx16 " not found in BootOrder, appending new entry at the end.", after_slot);
order[n] = slot;
return efi_set_boot_order(order, n + 1);
}
/* extend array */
t = reallocarray(order, n + 1, sizeof(uint16_t));
if (!t)
return -ENOMEM;
order = t;
/* add us to the top or end of the list */
if (c->operation == INSTALL_NEW) {
memmove(order + 1, order, n * sizeof(uint16_t));
order[0] = slot;
} else
order[n] = slot;
return efi_set_boot_order(order, n + 1);
}
static int remove_from_order(uint16_t slot) {
_cleanup_free_ uint16_t *order = NULL;
int n;
n = efi_get_boot_order(&order);
if (n <= 0)
return n;
for (int i = 0; i < n; i++) {
if (order[i] != slot)
continue;
if (i + 1 < n)
memmove(order + i, order + i+1, (n - i) * sizeof(uint16_t));
return efi_set_boot_order(order, n - 1);
}
return 0;
}
static int pick_efi_boot_option_description(int esp_fd, char **ret) {
int r;
assert(esp_fd >= 0);
assert(ret);
/* early declarations, so that they are definitely initialized even if we follow any of the gotos */
_cleanup_(sd_device_unrefp) sd_device *d = NULL;
_cleanup_free_ char *j = NULL;
const char *b = arg_efi_boot_option_description ?: "Linux Boot Manager";
if (!arg_efi_boot_option_description_with_device)
goto fallback;
r = block_device_new_from_fd(
esp_fd,
BLOCK_DEVICE_LOOKUP_WHOLE_DISK|BLOCK_DEVICE_LOOKUP_BACKING,
&d);
if (r < 0) {
log_debug_errno(r, "Failed to find backing device of ESP: %m");
goto fallback;
}
const char *serial;
r = sd_device_get_property_value(d, "ID_SERIAL", &serial);
if (r < 0) {
log_debug_errno(r, "Unable to read ID_SERIAL field of backing device of ESP: %m");
goto fallback;
}
j = strjoin(b, " (", serial, ")");
if (!j)
return log_oom();
if (strlen(j) > EFI_BOOT_OPTION_DESCRIPTION_MAX) {
log_debug("Boot option string suffixed with device serial would be too long, skipping: %s", j);
j = mfree(j);
goto fallback;
}
*ret = TAKE_PTR(j);
return 0;
fallback:
j = strdup(b);
if (!j)
return log_oom();
*ret = TAKE_PTR(j);
return 0;
}
static int install_boot_option(
InstallContext *c,
const char *path,
const char *description,
bool require_existing,
uint16_t after_slot,
uint16_t *ret_slot) {
uint16_t slot;
int r;
assert(c);
assert(path);
assert(description);
if (c->esp_fd < 0)
return c->esp_fd;
_cleanup_free_ char *j = path_join(c->root, c->esp_path);
if (!j)
return log_oom();
r = chase_and_accessat(
c->esp_fd,
c->esp_fd,
path,
CHASE_PROHIBIT_SYMLINKS|CHASE_MUST_BE_REGULAR,
F_OK,
/* ret_path= */ NULL);
if (r == -ENOENT && require_existing)
return 0;
if (r < 0 && r != -ENOENT)
return log_error_errno(r, "Cannot access \"%s/%s\": %m", j, skip_leading_slash(path));
r = find_slot(c->esp_uuid, path, &slot);
if (r < 0) {
int level = c->graceful ? arg_quiet ? LOG_DEBUG : LOG_INFO : LOG_ERR;
const char *skip = c->graceful ? ", skipping" : "";
log_full_errno(level, r,
r == -ENOENT ?
"Failed to access EFI variables%s. Is the \"efivarfs\" filesystem mounted?" :
"Failed to determine current boot order%s: %m", skip);
return c->graceful ? 0 : r;
}
bool existing = r > 0;
if (c->operation == INSTALL_NEW || !existing) {
r = efi_add_boot_option(
slot,
description,
c->esp_part,
c->esp_pstart,
c->esp_psize,
c->esp_uuid,
path);
if (r < 0) {
int level = c->graceful ? arg_quiet ? LOG_DEBUG : LOG_INFO : LOG_ERR;
const char *skip = c->graceful ? ", skipping" : "";
log_full_errno(level, r, "Failed to create EFI Boot variable entry%s: %m", skip);
return c->graceful ? 0 : r;
}
log_info("%s EFI boot entry \"%s\".",
existing ? "Updated" : "Created",
description);
}
r = insert_into_order(c, slot, after_slot);
if (r < 0)
return r;
if (ret_slot)
*ret_slot = slot;
return 0;
}
static int are_we_installed(InstallContext *c) {
int r;
assert(c);
/* Tests whether systemd-boot is installed. It's not obvious what to use as check here: we could
* check EFI variables, we could check what binary /EFI/BOOT/BOOT*.EFI points to, or whether the
* loader entries directory exists. Here we opted to check whether /EFI/systemd/ is non-empty, which
* should be a suitable and very minimal check for a number of reasons:
*
* → The check is architecture independent (i.e. we check if any systemd-boot loader is installed,
* not a specific one.)
*
* → It doesn't assume we are the only boot loader (i.e doesn't check if we own the main
* /EFI/BOOT/BOOT*.EFI fallback binary.
*
* → It specifically checks for systemd-boot, not for other boot loaders (which a check for
* /boot/loader/entries would do). */
_cleanup_free_ char *p = path_join(c->esp_path, "/EFI/systemd");
if (!p)
return log_oom();
if (c->esp_fd < 0)
return c->esp_fd;
_cleanup_close_ int fd = chase_and_openat(
c->esp_fd,
c->esp_fd,
"/EFI/systemd",
CHASE_PROHIBIT_SYMLINKS|CHASE_MUST_BE_DIRECTORY,
O_RDONLY|O_CLOEXEC|O_DIRECTORY,
/* ret_path= */ NULL);
if (fd == -ENOENT)
return 0;
if (fd < 0)
return log_error_errno(fd, "Failed to open '%s': %m", p);
log_debug("Checking whether '%s' contains any files%s", p, glyph(GLYPH_ELLIPSIS));
r = dir_is_empty_at(fd, /* path= */ NULL, /* ignore_hidden_or_backup= */ false);
if (r < 0 && r != -ENOENT)
return log_error_errno(r, "Failed to check whether '%s' contains any files: %m", p);
return r == 0;
}
#if HAVE_OPENSSL
static int load_secure_boot_auto_enroll(
X509 **ret_certificate,
EVP_PKEY **ret_private_key,
OpenSSLAskPasswordUI **ret_ui) {
int r;
assert(ret_certificate);
assert(ret_private_key);
assert(ret_ui);
if (!arg_secure_boot_auto_enroll) {
*ret_certificate = NULL;
*ret_private_key = NULL;
return 0;
}
if (arg_certificate_source_type == OPENSSL_CERTIFICATE_SOURCE_FILE) {
r = parse_path_argument(arg_certificate, /* suppress_root= */ false, &arg_certificate);
if (r < 0)
return r;
}
_cleanup_(X509_freep) X509 *certificate = NULL;
r = openssl_load_x509_certificate(
arg_certificate_source_type,
arg_certificate_source,
arg_certificate,
&certificate);
if (r < 0)
return log_error_errno(r, "Failed to load X.509 certificate from %s: %m", arg_certificate);
if (arg_private_key_source_type == OPENSSL_KEY_SOURCE_FILE) {
r = parse_path_argument(arg_private_key, /* suppress_root= */ false, &arg_private_key);
if (r < 0)
return r;
}
r = openssl_load_private_key(
arg_private_key_source_type,
arg_private_key_source,
arg_private_key,
&(AskPasswordRequest) {
.tty_fd = -EBADF,
.id = "bootctl-private-key-pin",
.keyring = arg_private_key,
.credential = "bootctl.private-key-pin",
.until = USEC_INFINITY,
.hup_fd = -EBADF,
},
ret_private_key,
ret_ui);
if (r < 0)
return log_error_errno(r, "Failed to load private key from %s: %m", arg_private_key);
*ret_certificate = TAKE_PTR(certificate);
return 0;
}
#endif
static int install_variables(InstallContext *c, const char *arch) {
int r;
assert(c);
const char *path = strjoina("/EFI/systemd/systemd-boot", arch, ".efi");
_cleanup_free_ char *description = NULL;
r = pick_efi_boot_option_description(c->esp_fd, &description);
if (r < 0)
return r;
uint16_t primary_slot = UINT16_MAX;
r = install_boot_option(c, path, description, /* require_existing= */ true, /* after_slot= */ UINT16_MAX, &primary_slot);
if (r < 0)
return r;
/* If primary registration was skipped (e.g. binary not on ESP), skip the fallback too
* or else it would land at position 0 in BootOrder with no primary ahead of it. */
if (primary_slot == UINT16_MAX)
return 0;
const char *fallback_path = strjoina("/EFI/systemd/systemd-boot-fallback", arch, ".efi");
_cleanup_free_ char *fallback_description = strjoin("Fallback ", description);
if (!fallback_description)
return log_oom();
strshorten(fallback_description, EFI_BOOT_OPTION_DESCRIPTION_MAX);
return install_boot_option(c, fallback_path, fallback_description, /* require_existing= */ false, /* after_slot= */ primary_slot, /* ret_slot= */ NULL);
}
static int run_install(InstallContext *c) {
int r;
assert(c);
assert(c->operation >= 0);
if (c->operation == INSTALL_UPDATE) {
/* If we are updating, don't do anything if sd-boot wasn't actually installed. */
r = are_we_installed(c);
if (r < 0)
return r;
if (r == 0) {
log_debug("Skipping update because sd-boot is not installed in the ESP.");
return 0;
}
}
r = settle_make_entry_directory(c);
if (r < 0)
return r;
const char *arch = arg_arch_all ? "" : get_efi_arch();
if (c->esp_fd < 0)
return c->esp_fd;
_cleanup_free_ char *j = path_join(c->root, c->esp_path);
if (!j)
return log_oom();
int dollar_boot_fd = acquire_dollar_boot_fd(c);
if (dollar_boot_fd < 0)
return dollar_boot_fd;
_cleanup_free_ char *w = path_join(c->root, dollar_boot_path(c));
if (!w)
return log_oom();
WITH_UMASK(0002) {
if (c->operation == INSTALL_NEW) {
/* Don't create any of these directories when we are just updating. When we update
* we'll drop-in our files (unless there are newer ones already), but we won't create
* the directories for them in the first place. */
r = create_subdirs(j, c->esp_fd, esp_subdirs);
if (r < 0)
return r;
r = create_subdirs(w, dollar_boot_fd, dollar_boot_subdirs);
if (r < 0)
return r;
}
r = install_binaries(c, arch);
if (r < 0)
return r;
if (c->operation == INSTALL_NEW) {
r = install_loader_config(c);
if (r < 0)
return r;
r = install_entry_directory(c);
if (r < 0)
return r;
r = install_entry_token(c);
if (r < 0)
return r;
if (arg_install_random_seed && !c->root) {
r = install_random_seed(c->esp_path, c->esp_fd);
if (r < 0)
return r;
}
r = install_secure_boot_auto_enroll(c);
if (r < 0)
return r;
}
r = install_loader_specification(c);
if (r < 0)
return r;
}
(void) sync_everything();
if (!should_touch_install_variables(c))
return 0;
if (arg_arch_all) {
log_info("Not changing EFI variables with --all-architectures.");
return 0;
}
return install_variables(c, arch);
}
int verb_install(int argc, char *argv[], uintptr_t _data, void *userdata) {
int r;
/* Invoked for both "update" and "install" */
_cleanup_(install_context_done) InstallContext c = INSTALL_CONTEXT_NULL;
r = install_context_from_cmdline(&c, streq(argv[0], "install") ? INSTALL_NEW : INSTALL_UPDATE);
if (r < 0)
return r;
if (r == 0) {
log_debug("No ESP found and operating in graceful mode, skipping.");
return 0;
}
#if HAVE_OPENSSL
_cleanup_(openssl_ask_password_ui_freep) OpenSSLAskPasswordUI *ui = NULL;
r = load_secure_boot_auto_enroll(&c.secure_boot_certificate, &c.secure_boot_private_key, &ui);
if (r < 0)
return r;
#endif
return run_install(&c);
}
static int remove_boot_efi(InstallContext *c) {
int r, n = 0;
assert(c);
if (c->esp_fd < 0)
return c->esp_fd;
_cleanup_free_ char *w = path_join(c->root, c->esp_path);
if (!w)
return log_oom();
_cleanup_closedir_ DIR *d = NULL;
_cleanup_free_ char *p = NULL;
r = chase_and_opendirat(
c->esp_fd,
c->esp_fd,
"/EFI/BOOT",
CHASE_PROHIBIT_SYMLINKS|CHASE_MUST_BE_DIRECTORY,
&p,
&d);
if (r == -ENOENT)
return 0;
if (r < 0)
return log_error_errno(r, "Failed to open directory \"%s/EFI/BOOT\": %m", w);
_cleanup_free_ char *j = path_join(w, p);
if (!j)
return log_oom();
FOREACH_DIRENT(de, d, break) {
_cleanup_close_ int fd = -EBADF;
if (!endswith_no_case(de->d_name, ".efi"))
continue;
_cleanup_free_ char *z = path_join(j, de->d_name);
if (!z)
return log_oom();
fd = xopenat_full(dirfd(d), de->d_name, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY|O_NOFOLLOW, XO_REGULAR, /* mode= */ MODE_INVALID);
if (fd == -ENOENT)
continue;
if (fd < 0)
return log_error_errno(fd, "Failed to open '%s' for reading: %m", z);
r = pe_is_native_fd(fd);
if (r < 0) {
log_warning_errno(r, "Failed to detect if '%s' is native architecture, ignoring: %m", z);
continue;
}
if (r == 0)
continue;
_cleanup_free_ char *v = NULL;
r = get_file_version(fd, &v);
if (r == -ESRCH)
continue; /* No version information */
if (r < 0) {
log_warning_errno(r, "Failed to get file version of '%s', skipping: %m", de->d_name);
continue;
}
if (!startswith(v, "systemd-boot "))
continue;
if (unlinkat(dirfd(d), de->d_name, 0) < 0)
return log_error_errno(errno, "Failed to remove '%s': %m", z);
log_info("Removed '%s'.", z);
n++;
}
log_debug("Removed %i EFI binaries from '%s'.", n, j);
return n;
}
static int unlink_inode(const char *root, int root_fd, const char *path, mode_t type) {
int r;
assert(root);
assert(root_fd >= 0);
assert(path);
assert(IN_SET(type, S_IFREG, S_IFDIR));
_cleanup_free_ char *p = path_join(empty_to_root(root), path);
if (!p)
return log_oom();
r = chase_and_unlinkat(
root_fd,
root_fd,
path,
CHASE_PROHIBIT_SYMLINKS,
S_ISDIR(type) ? AT_REMOVEDIR : 0,
/* ret_path= */ NULL);
if (r < 0) {
bool ignore = IN_SET(r, -ENOENT, -ENOTEMPTY);
log_full_errno(ignore ? LOG_DEBUG : LOG_ERR, r, "Failed to remove '%s': %m", p);
return ignore ? 0 : r;
}
log_info("Removed %s\"%s\".", S_ISDIR(type) ? "directory " : "", p);
return 0;
}
static int remove_subdirs(const char *root, int root_fd, const char *const *subdirs) {
int r = 0;
assert(root);
assert(root_fd);
STRV_FOREACH_BACKWARDS(i, (char**) subdirs)
RET_GATHER(r, unlink_inode(root, root_fd, *i, S_IFDIR));
return r;
}
static int remove_entry_directory(InstallContext *c, const char *path, int fd) {
assert(c);
assert(c->make_entry_directory >= 0);
assert(path);
assert(fd >= 0);
if (!c->make_entry_directory || !c->entry_token)
return 0;
return unlink_inode(path, fd, c->entry_token, S_IFDIR);
}
static int remove_binaries(InstallContext *c) {
int r;
_cleanup_free_ char *p = path_join(c->root, "/EFI/systemd");
if (!p)
return log_oom();
_cleanup_close_ int efi_fd = -EBADF;
r = chaseat(c->esp_fd,
c->esp_fd,
"EFI",
CHASE_PROHIBIT_SYMLINKS|CHASE_MUST_BE_DIRECTORY,
/* ret_path= */ NULL,
&efi_fd);
if (r < 0) {
if (r != -ENOENT)
return log_error_errno(r, "Failed to remove '%s': %m", p);
r = 0;
} else
r = rm_rf_at(efi_fd, "systemd", REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_MISSING_OK);
return RET_GATHER(r, remove_boot_efi(c));
}
static int remove_boot_option(sd_id128_t uuid, const char *path, bool in_order) {
uint16_t slot;
int r;
r = find_slot(uuid, path, &slot);
if (r != 1)
return 0;
r = efi_remove_boot_option(slot);
if (r < 0)
return r;
if (in_order)
return remove_from_order(slot);
return 0;
}
static int remove_loader_variables(void) {
int r = 0;
/* Remove all persistent loader variables we define */
FOREACH_STRING(var,
EFI_LOADER_VARIABLE_STR("LoaderConfigConsoleMode"),
EFI_LOADER_VARIABLE_STR("LoaderConfigTimeout"),
EFI_LOADER_VARIABLE_STR("LoaderConfigTimeoutOneShot"),
EFI_LOADER_VARIABLE_STR("LoaderEntryPreferred"),
EFI_LOADER_VARIABLE_STR("LoaderEntryDefault"),
EFI_LOADER_VARIABLE_STR("LoaderEntrySysFail"),
EFI_LOADER_VARIABLE_STR("LoaderEntryLastBooted"),
EFI_LOADER_VARIABLE_STR("LoaderEntryOneShot"),
EFI_LOADER_VARIABLE_STR("LoaderSystemToken")) {
int q;
q = efi_set_variable(var, NULL, 0);
if (q == -ENOENT)
continue;
if (q < 0)
RET_GATHER(r, log_warning_errno(q, "Failed to remove EFI variable %s: %m", var));
else
log_info("Removed EFI variable %s.", var);
}
return r;
}
static int remove_variables(sd_id128_t uuid) {
int r = 0;
const char *path = strjoina("/EFI/systemd/systemd-boot", get_efi_arch(), ".efi");
RET_GATHER(r, remove_boot_option(uuid, path, /* in_order= */ true));
const char *fallback_path = strjoina("/EFI/systemd/systemd-boot-fallback", get_efi_arch(), ".efi");
RET_GATHER(r, remove_boot_option(uuid, fallback_path, /* in_order= */ true));
return RET_GATHER(r, remove_loader_variables());
}
int verb_remove(int argc, char *argv[], uintptr_t _data, void *userdata) {
int r;
_cleanup_(install_context_done) InstallContext c = INSTALL_CONTEXT_NULL;
r = install_context_from_cmdline(&c, INSTALL_REMOVE);
if (r < 0)
return r;
if (r == 0) {
log_debug("No ESP found and operating in graceful mode, skipping.");
return 0;
}
r = settle_make_entry_directory(&c);
if (r < 0)
return r;
if (c.esp_fd < 0)