From: Roberto Sassu <[email protected]>

ima_read_policy() reads the policy file with kernel_read_file_from_path()
and splits it into rules with strsep(). However, the buffer allocated by
kernel_read_file_from_path() is exactly the size of the file and is not
NUL-terminated. If the policy file does not end with a newline, strsep()
scans past the end of the buffer while looking for the next separator. If
the file size is a multiple of PAGE_SIZE, the scan reaches the vmalloc
guard page and the kernel oopses.

If the last byte of the policy is not a newline, parse a NUL-terminated
copy of the buffer obtained with kmemdup_nul() instead, and account for
the NUL terminator in the remaining size, since ima_parse_add_rule()
counts it in the length of the last rule.

As a side effect, a policy whose last rule is not followed by a newline
is now loaded, instead of being rejected with -EINVAL due to the
terminator being counted in the length of the last rule but not in the
file size.

Fixes: 7429b092811f ("ima: load policy using path")
Reported-by: Fabrice Derepas <[email protected]>
Closes: 
https://lore.kernel.org/linux-integrity/[email protected]/
Signed-off-by: Roberto Sassu <[email protected]>
---
 security/integrity/ima/ima_fs.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)

diff --git a/security/integrity/ima/ima_fs.c b/security/integrity/ima/ima_fs.c
index 2a0bca554316..6d5e061f88c2 100644
--- a/security/integrity/ima/ima_fs.c
+++ b/security/integrity/ima/ima_fs.c
@@ -528,7 +528,7 @@ static const struct file_operations 
ima_ascii_measurements_staged_ops = {
 static ssize_t ima_read_policy(char *path)
 {
        void *data = NULL;
-       char *datap;
+       char *datap, *buf = NULL;
        size_t size;
        int rc, pathlen = strlen(path);
 
@@ -548,6 +548,23 @@ static ssize_t ima_read_policy(char *path)
        rc = 0;
 
        datap = data;
+
+       /*
+        * kernel_read_file_from_path() does not NUL-terminate the buffer.
+        * If the policy does not end with a newline, parse a NUL-terminated
+        * copy, so that strsep() does not scan past the end of the buffer.
+        */
+       if (size && datap[size - 1] != '\n') {
+               buf = kmemdup_nul(data, size, GFP_KERNEL);
+               if (!buf) {
+                       vfree(data);
+                       return -ENOMEM;
+               }
+               datap = buf;
+               /* Count the NUL terminator, included in ima_parse_add_rule(). 
*/
+               size++;
+       }
+
        while (size > 0 && (p = strsep(&datap, "\n"))) {
                pr_debug("rule: %s\n", p);
                rc = ima_parse_add_rule(p);
@@ -557,6 +574,7 @@ static ssize_t ima_read_policy(char *path)
        }
 
        vfree(data);
+       kfree(buf);
        if (rc < 0)
                return rc;
        else if (size)
-- 
2.43.0


Reply via email to