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