Debian Codegraph @

src/core/ima-setup.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2 /***
3 Copyright © 2012 Roberto Sassu - Politecnico di Torino, Italy
4 TORSEC group — http://security.polito.it
5 ***/
6
7 #include <fcntl.h>
8 #include <unistd.h>
9
10 #include "alloc-util.h"
11 #include "fd-util.h"
12 #include "fileio.h"
13 #include "ima-setup.h"
14 #include "log.h"
15
16 #define IMA_SECFS_DIR "/sys/kernel/security/ima"
17 #define IMA_SECFS_POLICY IMA_SECFS_DIR "/policy"
18 #define IMA_POLICY_PATH "/etc/ima/ima-policy"
19
20 int ima_setup(void) {
21 #if ENABLE_IMA
22 _cleanup_fclose_ FILE *input = NULL;
23 _cleanup_close_ int imafd = -EBADF;
24 unsigned lineno = 0;
25 int r;
26
27 if (access(IMA_SECFS_DIR, F_OK) < 0) {
28 log_debug_errno(errno, "IMA support is disabled in the kernel, ignoring: %m");
29 return 0;
30 }
31
32 if (access(IMA_SECFS_POLICY, W_OK) < 0) {
33 log_warning_errno(errno, "Another IMA custom policy has already been loaded, ignoring: %m");
34 return 0;
35 }
36
37 if (access(IMA_POLICY_PATH, F_OK) < 0) {
38 log_debug_errno(errno, "No IMA custom policy file "IMA_POLICY_PATH", ignoring: %m");
39 return 0;
40 }
41
42 imafd = open(IMA_SECFS_POLICY, O_WRONLY|O_CLOEXEC);
43 if (imafd < 0) {
44 log_error_errno(errno, "Failed to open the IMA kernel interface "IMA_SECFS_POLICY", ignoring: %m");
45 return 0;
46 }
47
48 /* attempt to write the name of the policy file into sysfs file */
49 if (write(imafd, IMA_POLICY_PATH, STRLEN(IMA_POLICY_PATH)) > 0)
50 goto done;
51
52 /* fall back to copying the policy line-by-line */
53 input = fopen(IMA_POLICY_PATH, "re");
54 if (!input) {
55 log_warning_errno(errno, "Failed to open the IMA custom policy file "IMA_POLICY_PATH", ignoring: %m");
56 return 0;
57 }
58
59 safe_close(imafd);
60
61 imafd = open(IMA_SECFS_POLICY, O_WRONLY|O_CLOEXEC);
62 if (imafd < 0) {
63 log_error_errno(errno, "Failed to open the IMA kernel interface "IMA_SECFS_POLICY", ignoring: %m");
64 return 0;
65 }
66
67 for (;;) {
68 _cleanup_free_ char *line = NULL;
69 size_t len;
70
71 r = read_line(input, LONG_LINE_MAX, &line);
72 if (r < 0)
73 return log_error_errno(r, "Failed to read the IMA custom policy file "IMA_POLICY_PATH": %m");
74 if (r == 0)
75 break;
76
77 len = strlen(line);
78 lineno++;
79
80 if (len > 0 && write(imafd, line, len) < 0)
81 return log_error_errno(errno, "Failed to load the IMA custom policy file "IMA_POLICY_PATH"%u: %m",
82 lineno);
83 }
84
85 done:
86 log_info("Successfully loaded the IMA custom policy "IMA_POLICY_PATH".");
87 #endif /* ENABLE_IMA */
88 return 0;
89 }