1 // SPDX-License-Identifier: GPL-2.0+
3 * Copyright (C) 2021 Microsoft Corporation
5 * Author: Lakshmi Ramasubramanian (nramas@linux.microsoft.com)
7 * Measure critical data structures maintainted by SELinux
10 #include <linux/vmalloc.h>
11 #include <linux/ima.h>
16 * selinux_ima_collect_state - Read selinux configuration settings
18 * @state: selinux_state
20 * On success returns the configuration settings string.
21 * On error, returns NULL.
23 static char *selinux_ima_collect_state(struct selinux_state *state)
25 const char *on = "=1;", *off = "=0;";
27 int buf_len, len, i, rc;
29 buf_len = strlen("initialized=0;enforcing=0;checkreqprot=0;") + 1;
32 for (i = 0; i < __POLICYDB_CAP_MAX; i++)
33 buf_len += strlen(selinux_policycap_names[i]) + len;
35 buf = kzalloc(buf_len, GFP_KERNEL);
39 rc = strscpy(buf, "initialized", buf_len);
42 rc = strlcat(buf, selinux_initialized(state) ? on : off, buf_len);
43 WARN_ON(rc >= buf_len);
45 rc = strlcat(buf, "enforcing", buf_len);
46 WARN_ON(rc >= buf_len);
48 rc = strlcat(buf, enforcing_enabled(state) ? on : off, buf_len);
49 WARN_ON(rc >= buf_len);
51 rc = strlcat(buf, "checkreqprot", buf_len);
52 WARN_ON(rc >= buf_len);
54 rc = strlcat(buf, checkreqprot_get(state) ? on : off, buf_len);
55 WARN_ON(rc >= buf_len);
57 for (i = 0; i < __POLICYDB_CAP_MAX; i++) {
58 rc = strlcat(buf, selinux_policycap_names[i], buf_len);
59 WARN_ON(rc >= buf_len);
61 rc = strlcat(buf, state->policycap[i] ? on : off, buf_len);
62 WARN_ON(rc >= buf_len);
69 * selinux_ima_measure_state_locked - Measure SELinux state and hash of policy
71 * @state: selinux state struct
73 void selinux_ima_measure_state_locked(struct selinux_state *state)
75 char *state_str = NULL;
80 lockdep_assert_held(&state->policy_mutex);
82 state_str = selinux_ima_collect_state(state);
84 pr_err("SELinux: %s: failed to read state.\n", __func__);
88 ima_measure_critical_data("selinux", "selinux-state",
89 state_str, strlen(state_str), false,
95 * Measure SELinux policy only after initialization is completed.
97 if (!selinux_initialized(state))
100 rc = security_read_state_kernel(state, &policy, &policy_len);
102 pr_err("SELinux: %s: failed to read policy %d.\n", __func__, rc);
106 ima_measure_critical_data("selinux", "selinux-policy-hash",
107 policy, policy_len, true,
114 * selinux_ima_measure_state - Measure SELinux state and hash of policy
116 * @state: selinux state struct
118 void selinux_ima_measure_state(struct selinux_state *state)
120 lockdep_assert_not_held(&state->policy_mutex);
122 mutex_lock(&state->policy_mutex);
123 selinux_ima_measure_state_locked(state);
124 mutex_unlock(&state->policy_mutex);