]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/ima-setup.c
resolve: set IP_RECVERR
[thirdparty/systemd.git] / src / core / ima-setup.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
81611586 2/***
810adae9
LP
3 Copyright © 2012 Roberto Sassu - Politecnico di Torino, Italy
4 TORSEC group — http://security.polito.it
81611586
RS
5***/
6
81611586 7#include <errno.h>
cf0fbc49 8#include <unistd.h>
81611586 9
3ffd4af2 10#include "fd-util.h"
0d39fa9c 11#include "fileio.h"
81611586 12#include "ima-setup.h"
81611586 13#include "log.h"
3ffd4af2 14#include "util.h"
81611586
RS
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
20int ima_setup(void) {
392fd235 21#if ENABLE_IMA
92994160
ZJS
22 _cleanup_fclose_ FILE *input = NULL;
23 _cleanup_close_ int imafd = -1;
24 unsigned lineno = 0;
25 char line[page_size()];
4ab72d6f 26
4dfb1892 27 if (access(IMA_SECFS_DIR, F_OK) < 0) {
4ab72d6f
WW
28 log_debug("IMA support is disabled in the kernel, ignoring.");
29 return 0;
30 }
31
e8e42b31
SB
32 if (access(IMA_SECFS_POLICY, W_OK) < 0) {
33 log_warning("Another IMA custom policy has already been loaded, ignoring.");
34 return 0;
35 }
36
a2c74c0c
BG
37 if (access(IMA_POLICY_PATH, F_OK) < 0) {
38 log_debug("No IMA custom policy file "IMA_POLICY_PATH", ignoring.");
39 return 0;
40 }
41
e8e42b31
SB
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 */
fbd0b64f 49 if (write(imafd, IMA_POLICY_PATH, STRLEN(IMA_POLICY_PATH)) > 0)
e8e42b31
SB
50 goto done;
51
52 /* fall back to copying the policy line-by-line */
92994160
ZJS
53 input = fopen(IMA_POLICY_PATH, "re");
54 if (!input) {
a2c74c0c 55 log_warning_errno(errno, "Failed to open the IMA custom policy file "IMA_POLICY_PATH", ignoring: %m");
4ab72d6f
WW
56 return 0;
57 }
58
e8e42b31 59 close(imafd);
4ab72d6f
WW
60
61 imafd = open(IMA_SECFS_POLICY, O_WRONLY|O_CLOEXEC);
62 if (imafd < 0) {
4dfb1892
ZJS
63 log_error_errno(errno, "Failed to open the IMA kernel interface "IMA_SECFS_POLICY", ignoring: %m");
64 return 0;
4ab72d6f
WW
65 }
66
92994160
ZJS
67 FOREACH_LINE(line, input,
68 return log_error_errno(errno, "Failed to read the IMA custom policy file "IMA_POLICY_PATH": %m")) {
69 size_t len;
116b6c86 70
92994160
ZJS
71 len = strlen(line);
72 lineno++;
116b6c86 73
92994160
ZJS
74 if (len > 0 && write(imafd, line, len) < 0)
75 return log_error_errno(errno, "Failed to load the IMA custom policy file "IMA_POLICY_PATH"%u: %m",
76 lineno);
77 }
4ab72d6f 78
e8e42b31 79done:
92994160 80 log_info("Successfully loaded the IMA custom policy "IMA_POLICY_PATH".");
392fd235 81#endif /* ENABLE_IMA */
92994160 82 return 0;
81611586 83}