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