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