HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/analyze/analyze-security.c

124,777 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 3289ae8f47f753b1bf609aed4c5a9040bd9fa2e9

Lines 2001–2984 of 2,984

 
        info->restrict_namespaces = (unsigned long long) namespaces;
 
        return 0;
}
 
static int property_read_umask(
                sd_bus *bus,
                const char *member,
                sd_bus_message *m,
                sd_bus_error *error,
                void *userdata) {
 
        SecurityInfo *info = ASSERT_PTR(userdata);
        int r;
        uint32_t umask;
 
        assert(bus);
        assert(member);
        assert(m);
 
        r = sd_bus_message_read(m, "u", &umask);
        if (r < 0)
                return r;
 
        info->_umask = (mode_t) umask;
 
        return 0;
}
 
static int property_read_restrict_address_families(
                sd_bus *bus,
                const char *member,
                sd_bus_message *m,
                sd_bus_error *error,
                void *userdata) {
 
        SecurityInfo *info = userdata;
        int allow_list, r;
 
        assert(bus);
        assert(member);
        assert(m);
 
        r = sd_bus_message_enter_container(m, 'r', "bas");
        if (r < 0)
                return r;
 
        r = sd_bus_message_read(m, "b", &allow_list);
        if (r < 0)
                return r;
 
        info->restrict_address_family_inet =
                info->restrict_address_family_unix =
                info->restrict_address_family_netlink =
                info->restrict_address_family_packet =
                info->restrict_address_family_other = allow_list;
 
        r = sd_bus_message_enter_container(m, 'a', "s");
        if (r < 0)
                return r;
 
        for (;;) {
                const char *name;
 
                r = sd_bus_message_read(m, "s", &name);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                if (STR_IN_SET(name, "AF_INET", "AF_INET6"))
                        info->restrict_address_family_inet = !allow_list;
                else if (streq(name, "AF_UNIX"))
                        info->restrict_address_family_unix = !allow_list;
                else if (streq(name, "AF_NETLINK"))
                        info->restrict_address_family_netlink = !allow_list;
                else if (streq(name, "AF_PACKET"))
                        info->restrict_address_family_packet = !allow_list;
                else
                        info->restrict_address_family_other = !allow_list;
        }
 
        r = sd_bus_message_exit_container(m);
        if (r < 0)
                return r;
 
        return sd_bus_message_exit_container(m);
}
 
static int property_read_syscall_archs(
                sd_bus *bus,
                const char *member,
                sd_bus_message *m,
                sd_bus_error *error,
                void *userdata) {
 
        SecurityInfo *info = ASSERT_PTR(userdata);
        int r;
 
        assert(bus);
        assert(member);
        assert(m);
 
        r = sd_bus_message_enter_container(m, 'a', "s");
        if (r < 0)
                return r;
 
        for (;;) {
                const char *name;
 
                r = sd_bus_message_read(m, "s", &name);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                r = set_put_strdup(&info->system_call_architectures, name);
                if (r < 0)
                        return r;
        }
 
        return sd_bus_message_exit_container(m);
}
 
static int property_read_system_call_filter(
                sd_bus *bus,
                const char *member,
                sd_bus_message *m,
                sd_bus_error *error,
                void *userdata) {
 
        SecurityInfo *info = userdata;
        int allow_list, r;
 
        assert(bus);
        assert(member);
        assert(m);
 
        r = sd_bus_message_enter_container(m, 'r', "bas");
        if (r < 0)
                return r;
 
        r = sd_bus_message_read(m, "b", &allow_list);
        if (r < 0)
                return r;
 
        info->system_call_filter_allow_list = allow_list;
 
        r = sd_bus_message_enter_container(m, 'a', "s");
        if (r < 0)
                return r;
 
        for (;;) {
                const char *name;
 
                r = sd_bus_message_read(m, "s", &name);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                /* ignore errno or action after colon */
                r = set_put_strndup(&info->system_call_filter, name, strchrnul(name, ':') - name);
                if (r < 0)
                        return r;
        }
 
        r = sd_bus_message_exit_container(m);
        if (r < 0)
                return r;
 
        return sd_bus_message_exit_container(m);
}
 
static int property_read_ip_address_allow(
                sd_bus *bus,
                const char *member,
                sd_bus_message *m,
                sd_bus_error *error,
                void *userdata) {
 
        SecurityInfo *info = userdata;
        bool deny_ipv4 = false, deny_ipv6 = false;
        int r;
 
        assert(bus);
        assert(member);
        assert(m);
 
        r = sd_bus_message_enter_container(m, 'a', "(iayu)");
        if (r < 0)
                return r;
 
        for (;;) {
                const void *data;
                size_t size;
                int32_t family;
                uint32_t prefixlen;
 
                r = sd_bus_message_enter_container(m, 'r', "iayu");
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                r = sd_bus_message_read(m, "i", &family);
                if (r < 0)
                        return r;
 
                r = sd_bus_message_read_array(m, 'y', &data, &size);
                if (r < 0)
                        return r;
 
                r = sd_bus_message_read(m, "u", &prefixlen);
                if (r < 0)
                        return r;
 
                r = sd_bus_message_exit_container(m);
                if (r < 0)
                        return r;
 
                if (streq(member, "IPAddressAllow")) {
                        union in_addr_union u;
 
                        if (family == AF_INET && size == 4 && prefixlen == 8)
                                memcpy(&u.in, data, size);
                        else if (family == AF_INET6 && size == 16 && prefixlen == 128)
                                memcpy(&u.in6, data, size);
                        else {
                                info->ip_address_allow_other = true;
                                continue;
                        }
 
                        if (in_addr_is_localhost(family, &u))
                                info->ip_address_allow_localhost = true;
                        else
                                info->ip_address_allow_other = true;
                } else {
                        assert(streq(member, "IPAddressDeny"));
 
                        if (family == AF_INET && size == 4 && prefixlen == 0)
                                deny_ipv4 = true;
                        else if (family == AF_INET6 && size == 16 && prefixlen == 0)
                                deny_ipv6 = true;
                }
        }
 
        info->ip_address_deny_all = deny_ipv4 && deny_ipv6;
 
        return sd_bus_message_exit_container(m);
}
 
static int property_read_ip_filters(
                sd_bus *bus,
                const char *member,
                sd_bus_message *m,
                sd_bus_error *error,
                void *userdata) {
 
        SecurityInfo *info = userdata;
        _cleanup_strv_free_ char **l = NULL;
        int r;
 
        assert(bus);
        assert(member);
        assert(m);
 
        r = sd_bus_message_read_strv(m, &l);
        if (r < 0)
                return r;
 
        if (streq(member, "IPIngressFilterPath"))
                info->ip_filters_custom_ingress = !strv_isempty(l);
        else if (streq(member, "IPEgressFilterPath"))
                info->ip_filters_custom_egress = !strv_isempty(l);
 
        return 0;
}
 
static int property_read_device_allow(
                sd_bus *bus,
                const char *member,
                sd_bus_message *m,
                sd_bus_error *error,
                void *userdata) {
 
        SecurityInfo *info = userdata;
        int r;
 
        assert(bus);
        assert(member);
        assert(m);
 
        r = sd_bus_message_enter_container(m, 'a', "(ss)");
        if (r < 0)
                return r;
 
        for (;;) {
                const char *name, *policy;
 
                r = sd_bus_message_read(m, "(ss)", &name, &policy);
                if (r < 0)
                        return r;
                if (r == 0)
                        break;
 
                r = strv_extendf(&info->device_allow, "%s:%s", name, policy);
                if (r < 0)
                        return r;
        }
 
        return sd_bus_message_exit_container(m);
}
 
static int acquire_security_info(sd_bus *bus, const char *name, SecurityInfo *info, RuntimeScope scope, AnalyzeSecurityFlags flags) {
 
        static const struct bus_properties_map security_map[] = {
                { "AmbientCapabilities",     "t",       NULL,                                    offsetof(SecurityInfo, ambient_capabilities)      },
                { "CapabilityBoundingSet",   "t",       NULL,                                    offsetof(SecurityInfo, capability_bounding_set)   },
                { "DefaultDependencies",     "b",       NULL,                                    offsetof(SecurityInfo, default_dependencies)      },
                { "Delegate",                "b",       NULL,                                    offsetof(SecurityInfo, delegate)                  },
                { "DeviceAllow",             "a(ss)",   property_read_device_allow,              0                                                 },
                { "DevicePolicy",            "s",       NULL,                                    offsetof(SecurityInfo, device_policy)             },
                { "DynamicUser",             "b",       NULL,                                    offsetof(SecurityInfo, dynamic_user)              },
                { "FragmentPath",            "s",       NULL,                                    offsetof(SecurityInfo, fragment_path)             },
                { "IPAddressAllow",          "a(iayu)", property_read_ip_address_allow,          0                                                 },
                { "IPAddressDeny",           "a(iayu)", property_read_ip_address_allow,          0                                                 },
                { "IPIngressFilterPath",     "as",      property_read_ip_filters,                0                                                 },
                { "IPEgressFilterPath",      "as",      property_read_ip_filters,                0                                                 },
                { "Id",                      "s",       NULL,                                    offsetof(SecurityInfo, id)                        },
                { "KeyringMode",             "s",       NULL,                                    offsetof(SecurityInfo, keyring_mode)              },
                { "ProtectProc",             "s",       NULL,                                    offsetof(SecurityInfo, protect_proc)              },
                { "ProcSubset",              "s",       NULL,                                    offsetof(SecurityInfo, proc_subset)               },
                { "LoadState",               "s",       NULL,                                    offsetof(SecurityInfo, load_state)                },
                { "LockPersonality",         "b",       NULL,                                    offsetof(SecurityInfo, lock_personality)          },
                { "MemoryDenyWriteExecute",  "b",       NULL,                                    offsetof(SecurityInfo, memory_deny_write_execute) },
                { "NoNewPrivileges",         "b",       NULL,                                    offsetof(SecurityInfo, no_new_privileges)         },
                { "NotifyAccess",            "s",       NULL,                                    offsetof(SecurityInfo, notify_access)             },
                { "PrivateDevices",          "b",       NULL,                                    offsetof(SecurityInfo, private_devices)           },
                { "PrivateMounts",           "b",       NULL,                                    offsetof(SecurityInfo, private_mounts)            },
                { "PrivateNetwork",          "b",       NULL,                                    offsetof(SecurityInfo, private_network)           },
                { "PrivateTmp",              "b",       NULL,                                    offsetof(SecurityInfo, private_tmp)               },
                { "PrivateUsers",            "b",       NULL,                                    offsetof(SecurityInfo, private_users)             },
                { "ProtectControlGroups",    "b",       NULL,                                    offsetof(SecurityInfo, protect_control_groups)    },
                { "ProtectHome",             "s",       NULL,                                    offsetof(SecurityInfo, protect_home)              },
                { "ProtectHostname",         "b",       NULL,                                    offsetof(SecurityInfo, protect_hostname)          },
                { "ProtectKernelModules",    "b",       NULL,                                    offsetof(SecurityInfo, protect_kernel_modules)    },
                { "ProtectKernelTunables",   "b",       NULL,                                    offsetof(SecurityInfo, protect_kernel_tunables)   },
                { "ProtectKernelLogs",       "b",       NULL,                                    offsetof(SecurityInfo, protect_kernel_logs)       },
                { "ProtectClock",            "b",       NULL,                                    offsetof(SecurityInfo, protect_clock)             },
                { "ProtectSystem",           "s",       NULL,                                    offsetof(SecurityInfo, protect_system)            },
                { "RemoveIPC",               "b",       NULL,                                    offsetof(SecurityInfo, remove_ipc)                },
                { "RestrictAddressFamilies", "(bas)",   property_read_restrict_address_families, 0                                                 },
                { "RestrictNamespaces",      "t",       property_read_restrict_namespaces,       0                                                 },
                { "RestrictRealtime",        "b",       NULL,                                    offsetof(SecurityInfo, restrict_realtime)         },
                { "RestrictSUIDSGID",        "b",       NULL,                                    offsetof(SecurityInfo, restrict_suid_sgid)        },
                { "RootDirectory",           "s",       NULL,                                    offsetof(SecurityInfo, root_directory)            },
                { "RootImage",               "s",       NULL,                                    offsetof(SecurityInfo, root_image)                },
                { "SupplementaryGroups",     "as",      NULL,                                    offsetof(SecurityInfo, supplementary_groups)      },
                { "SystemCallArchitectures", "as",      property_read_syscall_archs,             0                                                 },
                { "SystemCallFilter",        "(bas)",   property_read_system_call_filter,        0                                                 },
                { "Type",                    "s",       NULL,                                    offsetof(SecurityInfo, type)                      },
                { "UMask",                   "u",       property_read_umask,                     0                                                 },
                { "User",                    "s",       NULL,                                    offsetof(SecurityInfo, user)                      },
                {}
        };
 
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        _cleanup_free_ char *path = NULL;
        int r;
 
        /* Note: this mangles *info on failure! */
 
        assert(bus);
        assert(name);
        assert(info);
 
        path = unit_dbus_path_from_name(name);
        if (!path)
                return log_oom();
 
        r = bus_map_all_properties(
                        bus,
                        "org.freedesktop.systemd1",
                        path,
                        security_map,
                        BUS_MAP_STRDUP | BUS_MAP_BOOLEAN_AS_BOOL,
                        &error,
                        NULL,
                        info);
        if (r < 0)
                return log_error_errno(r, "Failed to get unit properties: %s", bus_error_message(&error, r));
 
        if (!streq_ptr(info->load_state, "loaded")) {
 
                if (FLAGS_SET(flags, ANALYZE_SECURITY_ONLY_LOADED))
                        return -EMEDIUMTYPE;
 
                if (streq_ptr(info->load_state, "not-found"))
                        log_error("Unit %s not found, cannot analyze.", name);
                else if (streq_ptr(info->load_state, "masked"))
                        log_error("Unit %s is masked, cannot analyze.", name);
                else
                        log_error("Unit %s not loaded properly, cannot analyze.", name);
 
                return -EINVAL;
        }
 
        if (FLAGS_SET(flags, ANALYZE_SECURITY_ONLY_LONG_RUNNING) && streq_ptr(info->type, "oneshot"))
                return -EMEDIUMTYPE;
 
        if (info->private_devices ||
            info->private_tmp ||
            info->protect_control_groups ||
            info->protect_kernel_tunables ||
            info->protect_kernel_modules ||
            !streq_ptr(info->protect_home, "no") ||
            !streq_ptr(info->protect_system, "no") ||
            info->root_image)
                info->private_mounts = true;
 
        if (info->protect_kernel_modules)
                info->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYS_MODULE);
 
        if (info->protect_kernel_logs)
                info->capability_bounding_set &= ~(UINT64_C(1) << CAP_SYSLOG);
 
        if (info->protect_clock)
                info->capability_bounding_set &= ~((UINT64_C(1) << CAP_SYS_TIME) |
                                                   (UINT64_C(1) << CAP_WAKE_ALARM));
 
        if (info->private_devices)
                info->capability_bounding_set &= ~((UINT64_C(1) << CAP_MKNOD) |
                                                   (UINT64_C(1) << CAP_SYS_RAWIO));
 
        info->runtime_scope = scope;
 
        return 0;
}
 
static int analyze_security_one(sd_bus *bus,
                                const char *name,
                                Table *overview_table,
                                RuntimeScope scope,
                                AnalyzeSecurityFlags flags,
                                unsigned threshold,
                                sd_json_variant *policy,
                                PagerFlags pager_flags,
                                sd_json_format_flags_t json_format_flags) {
 
        _cleanup_(security_info_freep) SecurityInfo *info = security_info_new();
        if (!info)
                return log_oom();
 
        int r;
 
        assert(bus);
        assert(name);
 
        r = acquire_security_info(bus, name, info, scope, flags);
        if (r == -EMEDIUMTYPE) /* Ignore this one because not loaded or Type is oneshot */
                return 0;
        if (r < 0)
                return r;
 
        r = assess(info, overview_table, flags, threshold, policy, pager_flags, json_format_flags);
        if (r < 0)
                return r;
 
        return 0;
}
 
/* Refactoring SecurityInfo so that it can make use of existing struct variables instead of reading from dbus */
static int get_security_info(Unit *u, ExecContext *c, CGroupContext *g, RuntimeScope scope, SecurityInfo **ret_info) {
        assert(ret_info);
 
        _cleanup_(security_info_freep) SecurityInfo *info = security_info_new();
        if (!info)
                return log_oom();
 
        info->runtime_scope = scope;
 
        if (u) {
                if (u->id) {
                        info->id = strdup(u->id);
                        if (!info->id)
                                return log_oom();
                }
                if (unit_type_to_string(u->type)) {
                        info->type = strdup(unit_type_to_string(u->type));
                        if (!info->type)
                                return log_oom();
                }
                if (unit_load_state_to_string(u->load_state)) {
                        info->load_state = strdup(unit_load_state_to_string(u->load_state));
                        if (!info->load_state)
                                return log_oom();
                }
                if (u->fragment_path) {
                        info->fragment_path = strdup(u->fragment_path);
                        if (!info->fragment_path)
                                return log_oom();
                }
                info->default_dependencies = u->default_dependencies;
                if (u->type == UNIT_SERVICE && notify_access_to_string(SERVICE(u)->notify_access)) {
                        info->notify_access = strdup(notify_access_to_string(SERVICE(u)->notify_access));
                        if (!info->notify_access)
                                return log_oom();
                }
        }
 
        if (c) {
                info->ambient_capabilities = c->capability_ambient_set;
                info->capability_bounding_set = c->capability_bounding_set;
                if (c->user) {
                        info->user = strdup(c->user);
                        if (!info->user)
                                return log_oom();
                }
                if (c->supplementary_groups) {
                        info->supplementary_groups = strv_copy(c->supplementary_groups);
                        if (!info->supplementary_groups)
                                return log_oom();
                }
                info->dynamic_user = c->dynamic_user;
                if (exec_keyring_mode_to_string(c->keyring_mode)) {
                        info->keyring_mode = strdup(exec_keyring_mode_to_string(c->keyring_mode));
                        if (!info->keyring_mode)
                                return log_oom();
                }
                if (protect_proc_to_string(c->protect_proc)) {
                        info->protect_proc = strdup(protect_proc_to_string(c->protect_proc));
                        if (!info->protect_proc)
                                return log_oom();
                }
                if (proc_subset_to_string(c->proc_subset)) {
                        info->proc_subset = strdup(proc_subset_to_string(c->proc_subset));
                        if (!info->proc_subset)
                                return log_oom();
                }
                info->lock_personality = c->lock_personality;
                info->memory_deny_write_execute = c->memory_deny_write_execute;
                info->no_new_privileges = c->no_new_privileges;
                info->protect_hostname = c->protect_hostname;
                info->private_devices = c->private_devices;
                info->private_mounts = c->private_mounts;
                info->private_network = c->private_network;
                info->private_tmp = c->private_tmp;
                info->private_users = c->private_users;
                info->protect_control_groups = c->protect_control_groups;
                info->protect_kernel_modules = c->protect_kernel_modules;
                info->protect_kernel_tunables = c->protect_kernel_tunables;
                info->protect_kernel_logs = c->protect_kernel_logs;
                info->protect_clock = c->protect_clock;
                if (protect_home_to_string(c->protect_home)) {
                        info->protect_home = strdup(protect_home_to_string(c->protect_home));
                        if (!info->protect_home)
                                return log_oom();
                }
                if (protect_system_to_string(c->protect_system)) {
                        info->protect_system = strdup(protect_system_to_string(c->protect_system));
                        if (!info->protect_system)
                                return log_oom();
                }
                info->remove_ipc = c->remove_ipc;
                info->restrict_address_family_inet =
                        info->restrict_address_family_unix =
                        info->restrict_address_family_netlink =
                        info->restrict_address_family_packet =
                        info->restrict_address_family_other =
                        c->address_families_allow_list;
 
                void *key;
                SET_FOREACH(key, c->address_families) {
                        int family = PTR_TO_INT(key);
                        if (family == 0)
                                continue;
                        if (IN_SET(family, AF_INET, AF_INET6))
                                info->restrict_address_family_inet = !c->address_families_allow_list;
                        else if (family == AF_UNIX)
                                info->restrict_address_family_unix = !c->address_families_allow_list;
                        else if (family == AF_NETLINK)
                                info->restrict_address_family_netlink = !c->address_families_allow_list;
                        else if (family == AF_PACKET)
                                info->restrict_address_family_packet = !c->address_families_allow_list;
                        else
                                info->restrict_address_family_other = !c->address_families_allow_list;
                }
 
                info->restrict_namespaces = c->restrict_namespaces;
                info->restrict_realtime = c->restrict_realtime;
                info->restrict_suid_sgid = c->restrict_suid_sgid;
                if (c->root_directory) {
                        info->root_directory = strdup(c->root_directory);
                        if (!info->root_directory)
                                return log_oom();
                }
                if (c->root_image) {
                        info->root_image = strdup(c->root_image);
                        if (!info->root_image)
                                return log_oom();
                }
                info->_umask = c->umask;
 
#if HAVE_SECCOMP
                if (dlopen_libseccomp(LOG_DEBUG) >= 0) {
                        SET_FOREACH(key, c->syscall_archs) {
                                const char *name;
 
                                name = seccomp_arch_to_string(PTR_TO_UINT32(key) - 1);
                                if (!name)
                                        continue;
 
                                if (set_put_strdup(&info->system_call_architectures, name) < 0)
                                        return log_oom();
                        }
 
                        info->system_call_filter_allow_list = c->syscall_allow_list;
 
                        void *id, *num;
                        HASHMAP_FOREACH_KEY(num, id, c->syscall_filter) {
                                _cleanup_free_ char *name = NULL;
 
                                if (info->system_call_filter_allow_list && PTR_TO_INT(num) >= 0)
                                        continue;
 
                                name = sym_seccomp_syscall_resolve_num_arch(SCMP_ARCH_NATIVE, PTR_TO_INT(id) - 1);
                                if (!name)
                                        continue;
 
                                if (set_ensure_consume(&info->system_call_filter, &string_hash_ops_free, TAKE_PTR(name)) < 0)
                                        return log_oom();
                        }
                }
#endif
        }
 
        if (g) {
                info->delegate = g->delegate;
                if (cgroup_device_policy_to_string(g->device_policy)) {
                        info->device_policy = strdup(cgroup_device_policy_to_string(g->device_policy));
                        if (!info->device_policy)
                                return log_oom();
                }
 
                struct in_addr_prefix *i;
                bool deny_ipv4 = false, deny_ipv6 = false;
 
                SET_FOREACH(i, g->ip_address_deny) {
                        if (i->family == AF_INET && i->prefixlen == 0)
                                deny_ipv4 = true;
                        else if (i->family == AF_INET6 && i->prefixlen == 0)
                                deny_ipv6 = true;
                }
                info->ip_address_deny_all = deny_ipv4 && deny_ipv6;
 
                info->ip_address_allow_localhost = info->ip_address_allow_other = false;
                SET_FOREACH(i, g->ip_address_allow) {
                        if (in_addr_is_localhost(i->family, &i->address))
                                info->ip_address_allow_localhost = true;
                        else
                                info->ip_address_allow_other = true;
                }
 
                info->ip_filters_custom_ingress = !strv_isempty(g->ip_filters_ingress);
                info->ip_filters_custom_egress = !strv_isempty(g->ip_filters_egress);
 
                LIST_FOREACH(device_allow, a, g->device_allow)
                        if (strv_extendf(&info->device_allow,
                                         "%s:%s",
                                         a->path,
                                         cgroup_device_permissions_to_string(a->permissions)) < 0)
                                return log_oom();
        }
 
        *ret_info = TAKE_PTR(info);
 
        return 0;
}
 
static int offline_security_check(Unit *u,
                                  RuntimeScope scope,
                                  unsigned threshold,
                                  sd_json_variant *policy,
                                  PagerFlags pager_flags,
                                  sd_json_format_flags_t json_format_flags) {
 
        _cleanup_(table_unrefp) Table *overview_table = NULL;
        AnalyzeSecurityFlags flags = 0;
        _cleanup_(security_info_freep) SecurityInfo *info = NULL;
        int r;
 
        assert(u);
 
        if (DEBUG_LOGGING)
                unit_dump(u, stdout, "\t");
 
        r = get_security_info(u, unit_get_exec_context(u), unit_get_cgroup_context(u), scope, &info);
        if (r < 0)
              return r;
 
        return assess(info, overview_table, flags, threshold, policy, pager_flags, json_format_flags);
}
 
static int offline_security_checks(
                char **filenames,
                sd_json_variant *policy,
                RuntimeScope scope,
                bool check_man,
                bool run_generators,
                unsigned threshold,
                const char *root,
                const char *profile,
                PagerFlags pager_flags,
                sd_json_format_flags_t json_format_flags) {
 
        const ManagerTestRunFlags flags =
                MANAGER_TEST_RUN_MINIMAL |
                MANAGER_TEST_RUN_ENV_GENERATORS |
                MANAGER_TEST_RUN_IGNORE_DEPENDENCIES |
                MANAGER_TEST_DONT_OPEN_EXECUTOR |
                run_generators * MANAGER_TEST_RUN_GENERATORS;
 
        _cleanup_(manager_freep) Manager *m = NULL;
        Unit *units[strv_length(filenames)];
        int r, k;
        size_t count = 0;
 
        if (strv_isempty(filenames))
                return 0;
 
        r = verify_set_unit_path(filenames);
        if (r < 0)
                return log_error_errno(r, "Failed to set unit load path: %m");
 
        r = manager_new(scope, flags, &m);
        if (r < 0)
                return log_error_errno(r, "Failed to initialize manager: %m");
 
        log_debug("Starting manager...");
 
        r = manager_startup(m, /* serialization= */ NULL, /* fds= */ NULL, /* named_listen_fds= */ NULL, root);
        if (r < 0)
                return r;
 
        if (profile) {
                /* Ensure the temporary directory is in the search path, so that we can add drop-ins. */
                r = strv_extend(&m->lookup_paths.search_path, m->lookup_paths.temporary_dir);
                if (r < 0)
                        return log_oom();
        }
 
        log_debug("Loading remaining units from the command line...");
 
        STRV_FOREACH(filename, filenames) {
                _cleanup_free_ char *prepared = NULL;
 
                log_debug("Handling %s...", *filename);
 
                k = verify_prepare_filename(*filename, &prepared);
                if (k < 0) {
                        log_warning_errno(k, "Failed to prepare filename %s: %m", *filename);
                        RET_GATHER(r, k);
                        continue;
                }
 
                /* When a portable image is analyzed, the profile is what provides a good chunk of
                 * the security-related settings, but they are obviously not shipped with the image.
                 * This allows them to be taken into consideration. */
                if (profile) {
                        _cleanup_free_ char *unit_name = NULL, *dropin = NULL, *profile_path = NULL;
 
                        r = path_extract_filename(prepared, &unit_name);
                        if (r < 0)
                                return log_oom();
 
                        dropin = strjoin(m->lookup_paths.temporary_dir, "/", unit_name, ".d/profile.conf");
                        if (!dropin)
                                return log_oom();
                        (void) mkdir_parents(dropin, 0755);
 
                        if (!is_path(profile)) {
                                r = find_portable_profile(scope, profile, unit_name, &profile_path);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to find portable profile %s: %m", profile);
                                profile = profile_path;
                        }
 
                        r = copy_file(profile, dropin, 0, 0644, 0);
                        if (r < 0)
                                return log_error_errno(r, "Failed to copy: %m");
                }
 
                k = manager_load_startable_unit_or_warn(m, /* name= */ NULL, prepared, LOG_ERR, &units[count]);
                if (k < 0) {
                        RET_GATHER(r, k);
                        continue;
                }
 
                count++;
        }
 
        for (size_t i = 0; i < count; i++)
                RET_GATHER(r, offline_security_check(units[i], scope, threshold, policy, pager_flags, json_format_flags));
 
        return r;
}
 
static int analyze_security(sd_bus *bus,
                     char **units,
                     sd_json_variant *policy,
                     RuntimeScope scope,
                     bool check_man,
                     bool run_generators,
                     bool offline,
                     unsigned threshold,
                     const char *root,
                     const char *profile,
                     sd_json_format_flags_t json_format_flags,
                     PagerFlags pager_flags,
                     AnalyzeSecurityFlags flags) {
 
        _cleanup_(table_unrefp) Table *overview_table = NULL;
        int ret = 0, r;
 
        assert(!!bus != offline);
 
        if (offline)
                return offline_security_checks(units, policy, scope, check_man, run_generators, threshold, root, profile, pager_flags, json_format_flags);
 
        if (strv_length(units) != 1) {
                overview_table = table_new("unit", "exposure", "predicate", "happy");
                if (!overview_table)
                        return log_oom();
        }
 
        if (strv_isempty(units)) {
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
                _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
                _cleanup_strv_free_ char **list = NULL;
                size_t n = 0;
 
                r = bus_call_method(
                                bus,
                                bus_systemd_mgr,
                                "ListUnits",
                                &error,
                                &reply,
                                NULL);
                if (r < 0)
                        return log_error_errno(r, "Failed to list units: %s", bus_error_message(&error, r));
 
                r = sd_bus_message_enter_container(reply, SD_BUS_TYPE_ARRAY, "(ssssssouso)");
                if (r < 0)
                        return bus_log_parse_error(r);
 
                for (;;) {
                        UnitInfo info;
 
                        r = bus_parse_unit_info(reply, &info);
                        if (r < 0)
                                return bus_log_parse_error(r);
                        if (r == 0)
                                break;
 
                        if (!endswith(info.id, ".service"))
                                continue;
 
                        if (!GREEDY_REALLOC(list, n + 2))
                                return log_oom();
 
                        r = strdup_to(&list[n], info.id);
                        if (r < 0)
                                return r;
 
                        list[++n] = NULL;
                }
 
                strv_sort(list);
 
                flags |= ANALYZE_SECURITY_SHORT|ANALYZE_SECURITY_ONLY_LOADED|ANALYZE_SECURITY_ONLY_LONG_RUNNING;
 
                STRV_FOREACH(i, list) {
                        r = analyze_security_one(bus, *i, overview_table, scope, flags, threshold, policy, pager_flags, json_format_flags);
                        if (r < 0 && ret >= 0)
                                ret = r;
                }
 
        } else
                STRV_FOREACH(i, units) {
                        _cleanup_free_ char *mangled = NULL, *instance = NULL;
                        const char *name;
 
                        if (!FLAGS_SET(flags, ANALYZE_SECURITY_SHORT) && i != units) {
                                putc('\n', stdout);
                                fflush(stdout);
                        }
 
                        r = unit_name_mangle(*i, 0, &mangled);
                        if (r < 0)
                                return log_error_errno(r, "Failed to mangle unit name '%s': %m", *i);
 
                        if (!endswith(mangled, ".service"))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Unit %s is not a service unit, refusing.",
                                                       *i);
 
                        if (unit_name_is_valid(mangled, UNIT_NAME_TEMPLATE)) {
                                r = unit_name_replace_instance(mangled, arg_instance, &instance);
                                if (r < 0)
                                        return log_oom();
 
                                name = instance;
                        } else
                                name = mangled;
 
                        r = analyze_security_one(bus, name, overview_table, scope, flags, threshold, policy, pager_flags, json_format_flags);
                        if (r < 0 && ret >= 0)
                                ret = r;
                }
 
        if (overview_table) {
                if (!FLAGS_SET(flags, ANALYZE_SECURITY_SHORT)) {
                        putc('\n', stdout);
                        fflush(stdout);
                }
 
                r = table_print_with_pager(overview_table, json_format_flags, pager_flags, /* show_header= */ true);
                if (r < 0)
                        return r;
        }
        return ret;
}
 
int verb_security(int argc, char *argv[], uintptr_t _data, void *userdata) {
        _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *policy = NULL;
        int r;
 
        if (!arg_offline) {
                r = acquire_bus(&bus, NULL);
                if (r < 0)
                        return bus_log_connect_error(r, arg_transport, arg_runtime_scope);
        }
 
        pager_open(arg_pager_flags);
 
        unsigned line = 0, column = 0;
        if (arg_security_policy) {
                r = sd_json_parse_file(/* f= */ NULL, arg_security_policy, SD_JSON_PARSE_MUST_BE_OBJECT, &policy, &line, &column);
                if (r < 0)
                        return log_error_errno(r, "Failed to parse '%s' at %u:%u: %m", arg_security_policy, line, column);
        } else {
                _cleanup_fclose_ FILE *f = NULL;
                _cleanup_free_ char *pp = NULL;
 
                r = search_and_fopen_nulstr("systemd-analyze-security.policy", "re", /* root= */ NULL, CONF_PATHS_NULSTR("systemd"), &f, &pp);
                if (r < 0 && r != -ENOENT)
                        return r;
 
                if (f) {
                        r = sd_json_parse_file(f, pp, SD_JSON_PARSE_MUST_BE_OBJECT, &policy, &line, &column);
                        if (r < 0)
                                return log_error_errno(r, "[%s:%u:%u] Failed to parse JSON policy: %m", pp, line, column);
                }
        }
 
        return analyze_security(
                        bus,
                        strv_skip(argv, 1),
                        policy,
                        arg_runtime_scope,
                        arg_man,
                        arg_generators,
                        arg_offline,
                        arg_threshold,
                        arg_root,
                        arg_profile,
                        arg_json_format_flags,
                        arg_pager_flags,
                        /* flags= */ 0);
}