]> git.ipfire.org Git - thirdparty/systemd.git/blobdiff - src/portable/portable.c
strv: make iterator in STRV_FOREACH() declaread in the loop
[thirdparty/systemd.git] / src / portable / portable.c
index 5afb008bb8f2737d5dcad8902a213a9a7739606a..a07a95a229f47882cb59307f1cdfc7ce5173b041 100644 (file)
@@ -4,6 +4,7 @@
 
 #include "bus-common-errors.h"
 #include "bus-error.h"
+#include "chase-symlinks.h"
 #include "conf-files.h"
 #include "copy.h"
 #include "data-fd-util.h"
 #include "dirent-util.h"
 #include "discover-image.h"
 #include "dissect-image.h"
+#include "env-file.h"
+#include "env-util.h"
 #include "errno-list.h"
 #include "escape.h"
+#include "extension-release.h"
 #include "fd-util.h"
 #include "fileio.h"
 #include "fs-util.h"
@@ -26,6 +30,7 @@
 #include "path-lookup.h"
 #include "portable.h"
 #include "process-util.h"
+#include "selinux-util.h"
 #include "set.h"
 #include "signal-util.h"
 #include "socket-util.h"
@@ -35,8 +40,6 @@
 #include "tmpfile-util.h"
 #include "user-util.h"
 
-static const char profile_dirs[] = CONF_PATHS_NULSTR("systemd/portable/profile");
-
 /* Markers used in the first line of our 20-portable.conf unit file drop-in to determine, that a) the unit file was
  * dropped there by the portable service logic and b) for which image it was dropped there. */
 #define PORTABLE_DROPIN_MARKER_BEGIN "# Drop-in created for image '"
@@ -55,7 +58,6 @@ static bool prefix_match(const char *unit, const char *prefix) {
 
 static bool unit_match(const char *unit, char **matches) {
         const char *dot;
-        char **i;
 
         dot = strrchr(unit, '.');
         if (!dot)
@@ -76,7 +78,7 @@ static bool unit_match(const char *unit, char **matches) {
         return false;
 }
 
-static PortableMetadata *portable_metadata_new(const char *name, const char *path, int fd) {
+static PortableMetadata *portable_metadata_new(const char *name, const char *path, const char *selinux_label, int fd) {
         PortableMetadata *m;
 
         m = malloc0(offsetof(PortableMetadata, name) + strlen(name) + 1);
@@ -90,6 +92,15 @@ static PortableMetadata *portable_metadata_new(const char *name, const char *pat
                         return mfree(m);
         }
 
+        /* The metadata file might have SELinux labels, we need to carry them and reapply them */
+        if (!isempty(selinux_label)) {
+                m->selinux_label = strdup(selinux_label);
+                if (!m->selinux_label) {
+                        free(m->image_path);
+                        return mfree(m);
+                }
+        }
+
         strcpy(m->name, name);
         m->fd = fd;
 
@@ -103,6 +114,7 @@ PortableMetadata *portable_metadata_unref(PortableMetadata *i) {
         safe_close(i->fd);
         free(i->source);
         free(i->image_path);
+        free(i->selinux_label);
 
         return mfree(i);
 }
@@ -132,96 +144,23 @@ int portable_metadata_hashmap_to_sorted_array(Hashmap *unit_files, PortableMetad
         return 0;
 }
 
-static int send_item(
+static int send_one_fd_iov_with_data_fd(
                 int socket_fd,
-                const char *name,
+                const struct iovec *iov,
+                size_t iovlen,
                 int fd) {
 
-        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control = {};
-        struct iovec iovec;
-        struct msghdr mh = {
-                .msg_control = &control,
-                .msg_controllen = sizeof(control),
-                .msg_iov = &iovec,
-                .msg_iovlen = 1,
-        };
-        struct cmsghdr *cmsg;
         _cleanup_close_ int data_fd = -1;
 
+        assert(iov || iovlen == 0);
         assert(socket_fd >= 0);
-        assert(name);
         assert(fd >= 0);
 
         data_fd = copy_data_fd(fd);
         if (data_fd < 0)
                 return data_fd;
 
-        cmsg = CMSG_FIRSTHDR(&mh);
-        cmsg->cmsg_level = SOL_SOCKET;
-        cmsg->cmsg_type = SCM_RIGHTS;
-        cmsg->cmsg_len = CMSG_LEN(sizeof(int));
-        memcpy(CMSG_DATA(cmsg), &data_fd, sizeof(int));
-
-        iovec = IOVEC_MAKE_STRING(name);
-
-        if (sendmsg(socket_fd, &mh, MSG_NOSIGNAL) < 0)
-                return -errno;
-
-        return 0;
-}
-
-static int recv_item(
-                int socket_fd,
-                char **ret_name,
-                int *ret_fd) {
-
-        CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(int))) control;
-        char buffer[PATH_MAX+2];
-        struct iovec iov = IOVEC_INIT(buffer, sizeof(buffer)-1);
-        struct msghdr mh = {
-                .msg_control = &control,
-                .msg_controllen = sizeof(control),
-                .msg_iov = &iov,
-                .msg_iovlen = 1,
-        };
-        struct cmsghdr *cmsg;
-        _cleanup_close_ int found_fd = -1;
-        char *copy;
-        ssize_t n;
-
-        assert(socket_fd >= 0);
-        assert(ret_name);
-        assert(ret_fd);
-
-        n = recvmsg_safe(socket_fd, &mh, MSG_CMSG_CLOEXEC);
-        if (n < 0)
-                return (int) n;
-
-        CMSG_FOREACH(cmsg, &mh) {
-                if (cmsg->cmsg_level == SOL_SOCKET &&
-                    cmsg->cmsg_type == SCM_RIGHTS) {
-
-                        if (cmsg->cmsg_len == CMSG_LEN(sizeof(int))) {
-                                assert(found_fd < 0);
-                                found_fd = *(int*) CMSG_DATA(cmsg);
-                                break;
-                        }
-
-                        cmsg_close_all(&mh);
-                        return -EIO;
-                }
-        }
-
-        buffer[n] = 0;
-
-        copy = strdup(buffer);
-        if (!copy)
-                return -ENOMEM;
-
-        *ret_name = copy;
-        *ret_fd = TAKE_FD(found_fd);
-
-        return 0;
+        return send_one_fd_iov(socket_fd, data_fd, iov, iovlen, 0);
 }
 
 DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(portable_metadata_hash_ops, char, string_hash_func, string_compare_func,
@@ -230,6 +169,8 @@ DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(portable_metadata_hash_ops, char,
 static int extract_now(
                 const char *where,
                 char **matches,
+                const char *image_name,
+                bool path_is_extension,
                 int socket_fd,
                 PortableMetadata **ret_os_release,
                 Hashmap **ret_unit_files) {
@@ -239,7 +180,7 @@ static int extract_now(
         _cleanup_(lookup_paths_free) LookupPaths paths = {};
         _cleanup_close_ int os_release_fd = -1;
         _cleanup_free_ char *os_release_path = NULL;
-        char **i;
+        const char *os_release_id;
         int r;
 
         /* Extracts the metadata from a directory tree 'where'. Extracts two kinds of information: the /etc/os-release
@@ -253,19 +194,32 @@ static int extract_now(
 
         assert(where);
 
-        /* First, find /etc/os-release and send it upstream (or just save it). */
-        r = open_os_release(where, &os_release_path, &os_release_fd);
+        /* First, find os-release/extension-release and send it upstream (or just save it). */
+        if (path_is_extension) {
+                os_release_id = strjoina("/usr/lib/extension-release.d/extension-release.", image_name);
+                r = open_extension_release(where, image_name, &os_release_path, &os_release_fd);
+        } else {
+                os_release_id = "/etc/os-release";
+                r = open_os_release(where, &os_release_path, &os_release_fd);
+        }
         if (r < 0)
-                log_debug_errno(r, "Couldn't acquire os-release file, ignoring: %m");
+                log_debug_errno(r,
+                                "Couldn't acquire %s file, ignoring: %m",
+                                path_is_extension ? "extension-release " : "os-release");
         else {
                 if (socket_fd >= 0) {
-                        r = send_item(socket_fd, "/etc/os-release", os_release_fd);
+                        struct iovec iov[] = {
+                                IOVEC_MAKE_STRING(os_release_id),
+                                IOVEC_MAKE((char *)"\0", sizeof(char)),
+                        };
+
+                        r = send_one_fd_iov_with_data_fd(socket_fd, iov, ELEMENTSOF(iov), os_release_fd);
                         if (r < 0)
                                 return log_debug_errno(r, "Failed to send os-release file: %m");
                 }
 
                 if (ret_os_release) {
-                        os_release = portable_metadata_new("/etc/os-release", NULL, os_release_fd);
+                        os_release = portable_metadata_new(os_release_id, NULL, NULL, os_release_fd);
                         if (!os_release)
                                 return -ENOMEM;
 
@@ -288,7 +242,6 @@ static int extract_now(
         STRV_FOREACH(i, paths.search_path) {
                 _cleanup_free_ char *resolved = NULL;
                 _cleanup_closedir_ DIR *d = NULL;
-                struct dirent *de;
 
                 r = chase_symlinks_and_opendir(*i, where, 0, &resolved, &d);
                 if (r < 0) {
@@ -298,6 +251,7 @@ static int extract_now(
 
                 FOREACH_DIRENT(de, d, return log_debug_errno(errno, "Failed to read directory: %m")) {
                         _cleanup_(portable_metadata_unrefp) PortableMetadata *m = NULL;
+                        _cleanup_(mac_selinux_freep) char *con = NULL;
                         _cleanup_close_ int fd = -1;
 
                         if (!unit_name_is_valid(de->d_name, UNIT_NAME_ANY))
@@ -319,13 +273,28 @@ static int extract_now(
                                 continue;
                         }
 
+#if HAVE_SELINUX
+                        /* The units will be copied on the host's filesystem, so if they had a SELinux label
+                         * we have to preserve it. Copy it out so that it can be applied later. */
+
+                        r = fgetfilecon_raw(fd, &con);
+                        if (r < 0 && errno != ENODATA)
+                                log_debug_errno(errno, "Failed to get SELinux file context from '%s', ignoring: %m", de->d_name);
+#endif
+
                         if (socket_fd >= 0) {
-                                r = send_item(socket_fd, de->d_name, fd);
+                                struct iovec iov[] = {
+                                        IOVEC_MAKE_STRING(de->d_name),
+                                        IOVEC_MAKE((char *)"\0", sizeof(char)),
+                                        IOVEC_MAKE_STRING(strempty(con)),
+                                };
+
+                                r = send_one_fd_iov_with_data_fd(socket_fd, iov, ELEMENTSOF(iov), fd);
                                 if (r < 0)
                                         return log_debug_errno(r, "Failed to send unit metadata to parent: %m");
                         }
 
-                        m = portable_metadata_new(de->d_name, NULL, fd);
+                        m = portable_metadata_new(de->d_name, where, con, fd);
                         if (!m)
                                 return -ENOMEM;
                         fd = -1;
@@ -351,7 +320,7 @@ static int extract_now(
 
 static int portable_extract_by_path(
                 const char *path,
-                bool extract_os_release,
+                bool path_is_extension,
                 char **matches,
                 PortableMetadata **ret_os_release,
                 Hashmap **ret_unit_files,
@@ -366,10 +335,16 @@ static int portable_extract_by_path(
 
         r = loop_device_make_by_path(path, O_RDONLY, LO_FLAGS_PARTSCAN, &d);
         if (r == -EISDIR) {
+                _cleanup_free_ char *image_name = NULL;
+
                 /* We can't turn this into a loop-back block device, and this returns EISDIR? Then this is a directory
                  * tree and not a raw device. It's easy then. */
 
-                r = extract_now(path, matches, -1, &os_release, &unit_files);
+                r = path_extract_filename(path, &image_name);
+                if (r < 0)
+                        return log_error_errno(r, "Failed to extract image name from path '%s': %m", path);
+
+                r = extract_now(path, matches, image_name, path_is_extension, -1, &os_release, &unit_files);
                 if (r < 0)
                         return r;
 
@@ -393,6 +368,7 @@ static int portable_extract_by_path(
                 r = dissect_image(
                                 d->fd,
                                 NULL, NULL,
+                                d->diskseq,
                                 d->uevent_seqnum_not_before,
                                 d->timestamp_not_before,
                                 DISSECT_IMAGE_READ_ONLY |
@@ -422,15 +398,22 @@ static int portable_extract_by_path(
                 if (r < 0)
                         return r;
                 if (r == 0) {
+                        DissectImageFlags flags = DISSECT_IMAGE_READ_ONLY;
+
                         seq[0] = safe_close(seq[0]);
 
-                        r = dissected_image_mount(m, tmpdir, UID_INVALID, UID_INVALID, DISSECT_IMAGE_READ_ONLY);
+                        if (path_is_extension)
+                                flags |= DISSECT_IMAGE_VALIDATE_OS_EXT;
+                        else
+                                flags |= DISSECT_IMAGE_VALIDATE_OS;
+
+                        r = dissected_image_mount(m, tmpdir, UID_INVALID, UID_INVALID, flags);
                         if (r < 0) {
                                 log_debug_errno(r, "Failed to mount dissected image: %m");
                                 goto child_finish;
                         }
 
-                        r = extract_now(tmpdir, matches, seq[1], NULL, NULL);
+                        r = extract_now(tmpdir, matches, m->image_name, path_is_extension, seq[1], NULL, NULL);
 
                 child_finish:
                         _exit(r < 0 ? EXIT_FAILURE : EXIT_SUCCESS);
@@ -444,23 +427,37 @@ static int portable_extract_by_path(
 
                 for (;;) {
                         _cleanup_(portable_metadata_unrefp) PortableMetadata *add = NULL;
-                        _cleanup_free_ char *name = NULL;
                         _cleanup_close_ int fd = -1;
-
-                        r = recv_item(seq[0], &name, &fd);
-                        if (r < 0)
-                                return log_debug_errno(r, "Failed to receive item: %m");
+                        /* We use NAME_MAX space for the SELinux label here. The kernel currently enforces no limit, but
+                         * according to suggestions from the SELinux people this will change and it will probably be
+                         * identical to NAME_MAX. For now we use that, but this should be updated one day when the final
+                         * limit is known. */
+                        char iov_buffer[PATH_MAX + NAME_MAX + 2];
+                        struct iovec iov = IOVEC_INIT(iov_buffer, sizeof(iov_buffer));
+
+                        ssize_t n = receive_one_fd_iov(seq[0], &iov, 1, 0, &fd);
+                        if (n == -EIO)
+                                break;
+                        if (n < 0)
+                                return log_debug_errno(n, "Failed to receive item: %m");
+                        iov_buffer[n] = 0;
 
                         /* We can't really distinguish a zero-length datagram without any fds from EOF (both are signalled the
                          * same way by recvmsg()). Hence, accept either as end notification. */
-                        if (isempty(name) && fd < 0)
+                        if (isempty(iov_buffer) && fd < 0)
                                 break;
 
-                        if (isempty(name) || fd < 0)
+                        if (isempty(iov_buffer) || fd < 0)
                                 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
                                                        "Invalid item sent from child.");
 
-                        add = portable_metadata_new(name, path, fd);
+                        /* Given recvmsg cannot be used with multiple io vectors if you don't know the size in advance,
+                         * use a marker to separate the name and the optional SELinux context. */
+                        char *selinux_label = memchr(iov_buffer, 0, n);
+                        assert(selinux_label);
+                        selinux_label++;
+
+                        add = portable_metadata_new(iov_buffer, path, selinux_label, fd);
                         if (!add)
                                 return -ENOMEM;
                         fd = -1;
@@ -476,12 +473,12 @@ static int portable_extract_by_path(
 
                                 add = NULL;
 
-                        } else if (PORTABLE_METADATA_IS_OS_RELEASE(add)) {
+                        } else if (PORTABLE_METADATA_IS_OS_RELEASE(add) || PORTABLE_METADATA_IS_EXTENSION_RELEASE(add)) {
 
                                 assert(!os_release);
                                 os_release = TAKE_PTR(add);
                         } else
-                                assert_not_reached("Unexpected metadata item from child.");
+                                assert_not_reached();
                 }
 
                 r = wait_for_terminate_and_check("(sd-dissect)", child, 0);
@@ -490,13 +487,12 @@ static int portable_extract_by_path(
                 child = 0;
         }
 
-        /* When the portable image is layered, the image with units will not
-         * have a full filesystem, so no os-release - it will be in the root layer */
-        if (extract_os_release && !os_release)
-                return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Image '%s' lacks os-release data, refusing.", path);
-
-        if (!extract_os_release && hashmap_isempty(unit_files))
-                return sd_bus_error_setf(error, SD_BUS_ERROR_INVALID_ARGS, "Couldn't find any matching unit files in image '%s', refusing.", path);
+        if (!os_release)
+                return sd_bus_error_setf(error,
+                                         SD_BUS_ERROR_INVALID_ARGS,
+                                         "Image '%s' lacks %s data, refusing.",
+                                         path,
+                                         path_is_extension ? "extension-release" : "os-release");
 
         if (ret_unit_files)
                 *ret_unit_files = TAKE_PTR(unit_files);
@@ -507,34 +503,46 @@ static int portable_extract_by_path(
         return 0;
 }
 
-int portable_extract(
+static int extract_image_and_extensions(
                 const char *name_or_path,
                 char **matches,
                 char **extension_image_paths,
+                bool validate_sysext,
+                Image **ret_image,
+                OrderedHashmap **ret_extension_images,
+                OrderedHashmap **ret_extension_releases,
                 PortableMetadata **ret_os_release,
                 Hashmap **ret_unit_files,
+                char ***ret_valid_prefixes,
                 sd_bus_error *error) {
 
+        _cleanup_free_ char *id = NULL, *version_id = NULL, *sysext_level = NULL;
         _cleanup_(portable_metadata_unrefp) PortableMetadata *os_release = NULL;
-        _cleanup_ordered_hashmap_free_ OrderedHashmap *extension_images = NULL;
+        _cleanup_ordered_hashmap_free_ OrderedHashmap *extension_images = NULL, *extension_releases = NULL;
         _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
+        _cleanup_strv_free_ char **valid_prefixes = NULL;
         _cleanup_(image_unrefp) Image *image = NULL;
         Image *ext;
         int r;
 
         assert(name_or_path);
+        assert(matches);
 
         r = image_find_harder(IMAGE_PORTABLE, name_or_path, NULL, &image);
         if (r < 0)
                 return r;
 
         if (!strv_isempty(extension_image_paths)) {
-                char **p;
-
                 extension_images = ordered_hashmap_new(&image_hash_ops);
                 if (!extension_images)
                         return -ENOMEM;
 
+                if (ret_extension_releases) {
+                        extension_releases = ordered_hashmap_new(&portable_metadata_hash_ops);
+                        if (!extension_releases)
+                                return -ENOMEM;
+                }
+
                 STRV_FOREACH(p, extension_image_paths) {
                         _cleanup_(image_unrefp) Image *new = NULL;
 
@@ -549,23 +557,170 @@ int portable_extract(
                 }
         }
 
-        r = portable_extract_by_path(image->path, true, matches, &os_release, &unit_files, error);
+        r = portable_extract_by_path(image->path, /* path_is_extension= */ false, matches, &os_release, &unit_files, error);
         if (r < 0)
                 return r;
 
+        /* If we are layering extension images on top of a runtime image, check that the os-release and
+         * extension-release metadata match, otherwise reject it immediately as invalid, or it will fail when
+         * the units are started. Also, collect valid portable prefixes if caller requested that. */
+        if (validate_sysext || ret_valid_prefixes) {
+                _cleanup_fclose_ FILE *f = NULL;
+                _cleanup_free_ char *prefixes = NULL;
+
+                r = take_fdopen_unlocked(&os_release->fd, "r", &f);
+                if (r < 0)
+                        return r;
+
+                r = parse_env_file(f, os_release->name,
+                                   "ID", &id,
+                                   "VERSION_ID", &version_id,
+                                   "SYSEXT_LEVEL", &sysext_level,
+                                   "PORTABLE_PREFIXES", &prefixes);
+                if (r < 0)
+                        return r;
+
+                if (prefixes) {
+                        valid_prefixes = strv_split(prefixes, WHITESPACE);
+                        if (!valid_prefixes)
+                                return -ENOMEM;
+                }
+        }
+
         ORDERED_HASHMAP_FOREACH(ext, extension_images) {
+                _cleanup_(portable_metadata_unrefp) PortableMetadata *extension_release_meta = NULL;
                 _cleanup_hashmap_free_ Hashmap *extra_unit_files = NULL;
+                _cleanup_strv_free_ char **extension_release = NULL;
+                _cleanup_close_ int extension_release_fd = -1;
+                _cleanup_fclose_ FILE *f = NULL;
+                const char *e;
 
-                r = portable_extract_by_path(ext->path, false, matches, NULL, &extra_unit_files, error);
+                r = portable_extract_by_path(ext->path, /* path_is_extension= */ true, matches, &extension_release_meta, &extra_unit_files, error);
                 if (r < 0)
                         return r;
+
                 r = hashmap_move(unit_files, extra_unit_files);
                 if (r < 0)
                         return r;
+
+                if (!validate_sysext && !ret_valid_prefixes && !ret_extension_releases)
+                        continue;
+
+                /* We need to keep the fd valid, to return the PortableMetadata to the caller. */
+                extension_release_fd = fd_reopen(extension_release_meta->fd, O_CLOEXEC|O_RDONLY);
+                if (extension_release_fd < 0)
+                        return extension_release_fd;
+
+                r = take_fdopen_unlocked(&extension_release_fd, "r", &f);
+                if (r < 0)
+                        return r;
+
+                r = load_env_file_pairs(f, extension_release_meta->name, &extension_release);
+                if (r < 0)
+                        return r;
+
+                if (validate_sysext) {
+                        r = extension_release_validate(ext->path, id, version_id, sysext_level, "portable", extension_release);
+                        if (r == 0)
+                                return sd_bus_error_set_errnof(error, SYNTHETIC_ERRNO(ESTALE), "Image %s extension-release metadata does not match the root's", ext->path);
+                        if (r < 0)
+                                return sd_bus_error_set_errnof(error, r, "Failed to compare image %s extension-release metadata with the root's os-release: %m", ext->path);
+                }
+
+                e = strv_env_pairs_get(extension_release, "PORTABLE_PREFIXES");
+                if (e) {
+                        _cleanup_strv_free_ char **l = NULL;
+
+                        l = strv_split(e, WHITESPACE);
+                        if (!l)
+                                return -ENOMEM;
+
+                        r = strv_extend_strv(&valid_prefixes, l, true);
+                        if (r < 0)
+                                return r;
+                }
+
+                if (ret_extension_releases) {
+                        r = ordered_hashmap_put(extension_releases, ext->name, extension_release_meta);
+                        if (r < 0)
+                                return r;
+                        TAKE_PTR(extension_release_meta);
+                }
         }
 
-        *ret_os_release = TAKE_PTR(os_release);
-        *ret_unit_files = TAKE_PTR(unit_files);
+        strv_sort(valid_prefixes);
+
+        if (ret_image)
+                *ret_image = TAKE_PTR(image);
+        if (ret_extension_images)
+                *ret_extension_images = TAKE_PTR(extension_images);
+        if (ret_extension_releases)
+                *ret_extension_releases = TAKE_PTR(extension_releases);
+        if (ret_os_release)
+                *ret_os_release = TAKE_PTR(os_release);
+        if (ret_unit_files)
+                *ret_unit_files = TAKE_PTR(unit_files);
+        if (ret_valid_prefixes)
+                *ret_valid_prefixes = TAKE_PTR(valid_prefixes);
+
+        return 0;
+}
+
+int portable_extract(
+                const char *name_or_path,
+                char **matches,
+                char **extension_image_paths,
+                PortableMetadata **ret_os_release,
+                OrderedHashmap **ret_extension_releases,
+                Hashmap **ret_unit_files,
+                char ***ret_valid_prefixes,
+                sd_bus_error *error) {
+
+        _cleanup_(portable_metadata_unrefp) PortableMetadata *os_release = NULL;
+        _cleanup_ordered_hashmap_free_ OrderedHashmap *extension_images = NULL, *extension_releases = NULL;
+        _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
+        _cleanup_(strv_freep) char **valid_prefixes = NULL;
+        _cleanup_(image_unrefp) Image *image = NULL;
+        int r;
+
+        assert(name_or_path);
+
+        r = extract_image_and_extensions(
+                        name_or_path,
+                        matches,
+                        extension_image_paths,
+                        /* validate_sysext= */ false,
+                        &image,
+                        &extension_images,
+                        &extension_releases,
+                        &os_release,
+                        &unit_files,
+                        ret_valid_prefixes ? &valid_prefixes : NULL,
+                        error);
+        if (r < 0)
+                return r;
+
+        if (hashmap_isempty(unit_files)) {
+                _cleanup_free_ char *extensions = strv_join(extension_image_paths, ", ");
+                if (!extensions)
+                        return -ENOMEM;
+
+                return sd_bus_error_setf(error,
+                                         SD_BUS_ERROR_INVALID_ARGS,
+                                         "Couldn't find any matching unit files in image '%s%s%s', refusing.",
+                                         image->path,
+                                         isempty(extensions) ? "" : "' or any of its extensions '",
+                                         isempty(extensions) ? "" : extensions);
+        }
+
+        if (ret_os_release)
+                *ret_os_release = TAKE_PTR(os_release);
+        if (ret_extension_releases)
+                *ret_extension_releases = TAKE_PTR(extension_releases);
+        if (ret_unit_files)
+                *ret_unit_files = TAKE_PTR(unit_files);
+        if (ret_valid_prefixes)
+                *ret_valid_prefixes = TAKE_PTR(valid_prefixes);
 
         return 0;
 }
@@ -631,7 +786,7 @@ static int unit_file_is_active(
                 at = strchr(name, '@');
                 assert(at);
 
-                prefix = strndupa(name, at + 1 - name);
+                prefix = strndupa_safe(name, at + 1 - name);
                 joined = strjoina(prefix, "*", at + 1);
 
                 r = sd_bus_message_append_strv(m, STRV_MAKE(joined));
@@ -746,6 +901,10 @@ static const char *root_setting_from_image(ImageType type) {
         return IN_SET(type, IMAGE_DIRECTORY, IMAGE_SUBVOLUME) ? "RootDirectory=" : "RootImage=";
 }
 
+static const char *extension_setting_from_image(ImageType type) {
+        return IN_SET(type, IMAGE_DIRECTORY, IMAGE_SUBVOLUME) ? "ExtensionDirectories=" : "ExtensionImages=";
+}
+
 static int make_marker_text(const char *image_path, OrderedHashmap *extension_images, char **ret_text) {
         _cleanup_free_ char *text = NULL, *escaped_image_path = NULL;
         Image *ext;
@@ -792,7 +951,6 @@ static int install_chroot_dropin(
                 size_t *n_changes) {
 
         _cleanup_free_ char *text = NULL, *dropin = NULL;
-        Image *ext;
         int r;
 
         assert(image_path);
@@ -810,6 +968,7 @@ static int install_chroot_dropin(
         if (endswith(m->name, ".service")) {
                 const char *os_release_source, *root_type;
                 _cleanup_free_ char *base_name = NULL;
+                Image *ext;
 
                 root_type = root_setting_from_image(type);
 
@@ -836,7 +995,7 @@ static int install_chroot_dropin(
 
                 if (m->image_path && !path_equal(m->image_path, image_path))
                         ORDERED_HASHMAP_FOREACH(ext, extension_images)
-                                if (!strextend(&text, "ExtensionImages=", ext->path, "\n"))
+                                if (!strextend(&text, extension_setting_from_image(ext->type), ext->path, "\n"))
                                         return -ENOMEM;
         }
 
@@ -852,33 +1011,6 @@ static int install_chroot_dropin(
         return 0;
 }
 
-static int find_profile(const char *name, const char *unit, char **ret) {
-        const char *p, *dot;
-
-        assert(name);
-        assert(ret);
-
-        assert_se(dot = strrchr(unit, '.'));
-
-        NULSTR_FOREACH(p, profile_dirs) {
-                _cleanup_free_ char *joined = NULL;
-
-                joined = strjoin(p, "/", name, "/", dot + 1, ".conf");
-                if (!joined)
-                        return -ENOMEM;
-
-                if (laccess(joined, F_OK) >= 0) {
-                        *ret = TAKE_PTR(joined);
-                        return 0;
-                }
-
-                if (errno != ENOENT)
-                        return -errno;
-        }
-
-        return -ENOENT;
-}
-
 static int install_profile_dropin(
                 const char *image_path,
                 const PortableMetadata *m,
@@ -899,7 +1031,7 @@ static int install_profile_dropin(
         if (!profile)
                 return 0;
 
-        r = find_profile(profile, m->name, &from);
+        r = find_portable_profile(profile, m->name, &from);
         if (r < 0) {
                 if (r != -ENOENT)
                         return log_debug_errno(errno, "Profile '%s' is not accessible: %m", profile);
@@ -916,14 +1048,14 @@ static int install_profile_dropin(
 
                 r = copy_file_atomic(from, dropin, 0644, 0, 0, COPY_REFLINK);
                 if (r < 0)
-                        return log_debug_errno(r, "Failed to copy %s %s %s: %m", from, special_glyph(SPECIAL_GLYPH_ARROW), dropin);
+                        return log_debug_errno(r, "Failed to copy %s %s %s: %m", from, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), dropin);
 
                 (void) portable_changes_add(changes, n_changes, PORTABLE_COPY, dropin, from);
 
         } else {
 
                 if (symlink(from, dropin) < 0)
-                        return log_debug_errno(errno, "Failed to link %s %s %s: %m", from, special_glyph(SPECIAL_GLYPH_ARROW), dropin);
+                        return log_debug_errno(errno, "Failed to link %s %s %s: %m", from, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), dropin);
 
                 (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, dropin, from);
         }
@@ -1012,7 +1144,10 @@ static int attach_unit_file(
                 _cleanup_(unlink_and_freep) char *tmp = NULL;
                 _cleanup_close_ int fd = -1;
 
+                (void) mac_selinux_create_file_prepare_label(path, m->selinux_label);
+
                 fd = open_tmpfile_linkable(path, O_WRONLY|O_CLOEXEC, &tmp);
+                mac_selinux_create_file_clear(); /* Clear immediately in case of errors */
                 if (fd < 0)
                         return log_debug_errno(fd, "Failed to create unit file '%s': %m", path);
 
@@ -1090,7 +1225,7 @@ static int install_image_symlink(
         (void) mkdir_parents(sl, 0755);
 
         if (symlink(image_path, sl) < 0)
-                return log_debug_errno(errno, "Failed to link %s %s %s: %m", image_path, special_glyph(SPECIAL_GLYPH_ARROW), sl);
+                return log_debug_errno(errno, "Failed to link %s %s %s: %m", image_path, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), sl);
 
         (void) portable_changes_add(changes, n_changes, PORTABLE_SYMLINK, sl, image_path);
         return 0;
@@ -1121,6 +1256,16 @@ static int install_image_and_extensions_symlinks(
         return 0;
 }
 
+static bool prefix_matches_compatible(char **matches, char **valid_prefixes) {
+        /* Checks if all 'matches' are included in the list of 'valid_prefixes' */
+
+        STRV_FOREACH(m, matches)
+                if (!strv_contains(valid_prefixes, *m))
+                        return false;
+
+        return true;
+}
+
 int portable_attach(
                 sd_bus *bus,
                 const char *name_or_path,
@@ -1135,49 +1280,64 @@ int portable_attach(
         _cleanup_ordered_hashmap_free_ OrderedHashmap *extension_images = NULL;
         _cleanup_hashmap_free_ Hashmap *unit_files = NULL;
         _cleanup_(lookup_paths_free) LookupPaths paths = {};
+        _cleanup_strv_free_ char **valid_prefixes = NULL;
         _cleanup_(image_unrefp) Image *image = NULL;
         PortableMetadata *item;
-        Image *ext;
-        char **p;
         int r;
 
-        assert(name_or_path);
-
-        r = image_find_harder(IMAGE_PORTABLE, name_or_path, NULL, &image);
+        r = extract_image_and_extensions(
+                        name_or_path,
+                        matches,
+                        extension_image_paths,
+                        /* validate_sysext= */ true,
+                        &image,
+                        &extension_images,
+                        /* extension_releases= */ NULL,
+                        /* os_release= */ NULL,
+                        &unit_files,
+                        &valid_prefixes,
+                        error);
         if (r < 0)
                 return r;
-        if (!strv_isempty(extension_image_paths)) {
-                extension_images = ordered_hashmap_new(&image_hash_ops);
-                if (!extension_images)
+
+        if (valid_prefixes && !prefix_matches_compatible(matches, valid_prefixes)) {
+                _cleanup_free_ char *matches_joined = NULL, *extensions_joined = NULL, *valid_prefixes_joined = NULL;
+
+                matches_joined = strv_join(matches, "', '");
+                if (!matches_joined)
                         return -ENOMEM;
 
-                STRV_FOREACH(p, extension_image_paths) {
-                        _cleanup_(image_unrefp) Image *new = NULL;
+                extensions_joined = strv_join(extension_image_paths, ", ");
+                if (!extensions_joined)
+                        return -ENOMEM;
 
-                        r = image_find_harder(IMAGE_PORTABLE, *p, NULL, &new);
-                        if (r < 0)
-                                return r;
+                valid_prefixes_joined = strv_join(valid_prefixes, ", ");
+                if (!valid_prefixes_joined)
+                        return -ENOMEM;
 
-                        r = ordered_hashmap_put(extension_images, new->name, new);
-                        if (r < 0)
-                                return r;
-                        TAKE_PTR(new);
-                }
+                return sd_bus_error_setf(
+                                error,
+                                SD_BUS_ERROR_INVALID_ARGS,
+                                "Selected matches '%s' are not compatible with portable service image '%s%s%s', refusing. (Acceptable prefix matches are: %s)",
+                                matches_joined,
+                                image->path,
+                                isempty(extensions_joined) ? "" : "' or any of its extensions '",
+                                strempty(extensions_joined),
+                                valid_prefixes_joined);
         }
 
-        r = portable_extract_by_path(image->path, true, matches, NULL, &unit_files, error);
-        if (r < 0)
-                return r;
-
-        ORDERED_HASHMAP_FOREACH(ext, extension_images) {
-                _cleanup_hashmap_free_ Hashmap *extra_unit_files = NULL;
+        if (hashmap_isempty(unit_files)) {
+                _cleanup_free_ char *extensions_joined = strv_join(extension_image_paths, ", ");
+                if (!extensions_joined)
+                        return -ENOMEM;
 
-                r = portable_extract_by_path(ext->path, false, matches, NULL, &extra_unit_files, error);
-                if (r < 0)
-                        return r;
-                r = hashmap_move(unit_files, extra_unit_files);
-                if (r < 0)
-                        return r;
+                return sd_bus_error_setf(
+                                error,
+                                SD_BUS_ERROR_INVALID_ARGS,
+                                "Couldn't find any matching unit files in image '%s%s%s', refusing.",
+                                image->path,
+                                isempty(extensions_joined) ? "" : "' or any of its extensions '",
+                                strempty(extensions_joined));
         }
 
         r = lookup_paths_init(&paths, UNIT_FILE_SYSTEM, LOOKUP_PATHS_SPLIT_USR, NULL);
@@ -1214,7 +1374,6 @@ int portable_attach(
 
 static bool marker_matches_images(const char *marker, const char *name_or_path, char **extension_image_paths) {
         _cleanup_strv_free_ char **root_and_extensions = NULL;
-        char **image_name_or_path;
         const char *a;
         int r;
 
@@ -1363,7 +1522,6 @@ int portable_detach(
         _cleanup_set_free_ Set *unit_files = NULL, *markers = NULL;
         _cleanup_closedir_ DIR *d = NULL;
         const char *where, *item;
-        struct dirent *de;
         int ret = 0;
         int r;
 
@@ -1524,6 +1682,7 @@ not_found:
 static int portable_get_state_internal(
                 sd_bus *bus,
                 const char *name_or_path,
+                char **extension_image_paths,
                 PortableFlags flags,
                 PortableState *ret,
                 sd_bus_error *error) {
@@ -1533,7 +1692,6 @@ static int portable_get_state_internal(
         _cleanup_set_free_ Set *unit_files = NULL;
         _cleanup_closedir_ DIR *d = NULL;
         const char *where;
-        struct dirent *de;
         int r;
 
         assert(name_or_path);
@@ -1569,7 +1727,7 @@ static int portable_get_state_internal(
                 if (!IN_SET(de->d_type, DT_LNK, DT_REG))
                         continue;
 
-                r = test_chroot_dropin(d, where, de->d_name, name_or_path, NULL, NULL);
+                r = test_chroot_dropin(d, where, de->d_name, name_or_path, extension_image_paths, NULL);
                 if (r < 0)
                         return r;
                 if (r == 0)
@@ -1602,6 +1760,7 @@ static int portable_get_state_internal(
 int portable_get_state(
                 sd_bus *bus,
                 const char *name_or_path,
+                char **extension_image_paths,
                 PortableFlags flags,
                 PortableState *ret,
                 sd_bus_error *error) {
@@ -1615,12 +1774,12 @@ int portable_get_state(
         /* We look for matching units twice: once in the regular directories, and once in the runtime directories — but
          * the latter only if we didn't find anything in the former. */
 
-        r = portable_get_state_internal(bus, name_or_path, flags & ~PORTABLE_RUNTIME, &state, error);
+        r = portable_get_state_internal(bus, name_or_path, extension_image_paths, flags & ~PORTABLE_RUNTIME, &state, error);
         if (r < 0)
                 return r;
 
         if (state == PORTABLE_DETACHED) {
-                r = portable_get_state_internal(bus, name_or_path, flags | PORTABLE_RUNTIME, &state, error);
+                r = portable_get_state_internal(bus, name_or_path, extension_image_paths, flags | PORTABLE_RUNTIME, &state, error);
                 if (r < 0)
                         return r;
         }
@@ -1632,7 +1791,7 @@ int portable_get_state(
 int portable_get_profiles(char ***ret) {
         assert(ret);
 
-        return conf_files_list_nulstr(ret, NULL, NULL, CONF_FILES_DIRECTORY|CONF_FILES_BASENAME|CONF_FILES_FILTER_MASKED, profile_dirs);
+        return conf_files_list_nulstr(ret, NULL, NULL, CONF_FILES_DIRECTORY|CONF_FILES_BASENAME|CONF_FILES_FILTER_MASKED, PORTABLE_PROFILE_DIRS);
 }
 
 static const char* const portable_change_type_table[_PORTABLE_CHANGE_TYPE_MAX] = {