Debian Codegraph @

pkg/selinux/selinux-client.js

raw
1 /*
2 * Copyright (C) 2016 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from 'cockpit';
7
8 /* until we have a good dbus interface to get selinux status updates,
9 * we resort to polling
10 */
11
12 // how often to check the status [milliseconds]
13 const pollingInterval = 10000;
14
15 const statusCommand = "sestatus";
16
17 // currentStatus reflects the status of SELinux on the system
18 const status = {
19 enabled: undefined,
20 enforcing: false,
21 configEnforcing: false, // configured mode at boot time
22 shell: "",
23 ansible: "",
24 modifications: null,
25 permitted: true,
26 failed: false,
27 };
28
29 /* initializes the selinux status updating, returns initial status
30 * statusChangedCallback parameters (status, errorMessage)
31 * status with the following properties:
32 * - enabled: undefined (couldn't get info), true (enabled) or false (disabled)
33 * cannot be changed without a reboot
34 * - enforcing: boolean (current selinux mode of the system, false if permissive or selinux disabled)
35 * - configEnforcing: boolean (mode the system is configured to boot in, may differ from current mode)
36 * - shell: Output of `semanage export`
37 * - ansible: Ansible script for setting up local modifications
38 * - modifications: List of all local modifications in selinux policy
39 * - permitted: Set to false if user is not allowed to see local modifications
40 * - failed: Reading of modifications failed in unexpected way
41 * errorMessage: optional, if getting the status failed, here will be additional info
42 *
43 * Since we're screenscraping we need to run this in LC_ALL=C mode
44 */
45 export function init(statusChangedCallback) {
46 const refreshInfo = function() {
47 cockpit.spawn(statusCommand, { err: 'message', environ: ["LC_ALL=C"], superuser: "try" }).then(
48 function(output) {
49 /* parse output that looks like this:
50 * SELinux status: enabled
51 * SELinuxfs mount: /sys/fs/selinux
52 * SELinux root directory: /etc/selinux
53 * Loaded policy name: targeted
54 * Current mode: enforcing
55 * Mode from config file: enforcing
56 * Policy MLS status: enabled
57 * Policy deny_unknown status: allowed
58 * Max kernel policy version: 30
59 * We want the lines 'SELinux status', 'Current mode' and 'Mode from config file'
60 */
61
62 const lines = output.split("\n");
63 lines.forEach(function(itm) {
64 const items = itm.trim().split(":");
65 if (items.length !== 2)
66 return;
67 const key = items[0].trim();
68 const value = items[1].trim();
69 if (key == "SELinux status") {
70 status.enabled = (value == "enabled");
71 } else if (key == "Current mode") {
72 status.enforcing = (value == "enforcing");
73 } else if (key == "Mode from config file") {
74 if (value == 'error (Permission denied)') {
75 status.configEnforcing = undefined;
76 } else {
77 status.configEnforcing = (value == "enforcing");
78 }
79 }
80 });
81 if (statusChangedCallback)
82 statusChangedCallback(status, undefined);
83 },
84 function(error) {
85 if (status === undefined)
86 return;
87 if (statusChangedCallback) {
88 status.enabled = undefined;
89 statusChangedCallback(status, error.message);
90 }
91 }
92 );
93 };
94
95 let polling = null;
96
97 function setupPolling() {
98 if (cockpit.hidden) {
99 window.clearInterval(polling);
100 polling = null;
101 } else if (polling === null) {
102 polling = window.setInterval(refreshInfo, pollingInterval);
103 refreshInfo();
104 getModifications(statusChangedCallback);
105 }
106 }
107
108 cockpit.addEventListener("visibilitychange", setupPolling);
109 setupPolling();
110
111 /* The first time */
112 if (polling === null)
113 refreshInfo();
114
115 return status;
116 }
117
118 function parseBoolean(result, item) {
119 // Example:
120 // authlogin_nsswitch_use_ldap (on , on) Allow authlogin to nsswitch use ldap
121 // Split by first ')', as the name cannot contain ')'
122 if (item) {
123 const match = item.match(/(\S*)\s*\((\S*)\s*,.*\)\s*(.*)/);
124 if (match) {
125 let description = match[3];
126 let enable_val = "--on";
127 if (match[2] !== "on") {
128 enable_val = "--off";
129 description = description.replace("Allow", "Disallow");
130 }
131 // We want to support Ansible Core, the `seboolean:` module is not a builtin
132 const ansible = `
133 - name: ${description}
134 command: semanage boolean -m ${enable_val} ${match[1]}
135 `;
136 result.push({ description, ansible });
137 }
138 }
139 return result;
140 }
141
142 export function getModifications(statusChangedCallback) {
143 // List of items we know how to parse
144 const manageditems_callbacks = [["boolean", parseBoolean]];
145 const manageditems = manageditems_callbacks.map(item => item[0]);
146
147 // Building a query to get information from semanage
148 // Use `semanage export` to show shell script (and parse types we yet don't parse explicitly)
149 // Use `semanage <type> --list -C` to get better readable and parsable local changes
150 // Use `echo '~~~~~'` as separator, so we don't need to execute multiple commands
151 let script = "semanage export";
152 manageditems.forEach(item => { script += " && echo '~~~~~' && semanage " + item + " --list -C --noheading" });
153 cockpit.script(script, [], { err: 'message', environ: ["LC_MESSAGES=C"], superuser: "try" })
154 .then(output => {
155 output = output.split("~~~~~");
156 status.shell = output[0];
157 status.modifications = [];
158 status.ansible = "";
159
160 for (let i = 1; i < output.length; i++) {
161 const parsed = output[i].trim().split("\n")
162 .reduce(manageditems_callbacks[i - 1][1], []);
163 parsed.forEach(p => {
164 status.modifications.push(p.description);
165 status.ansible += p.ansible;
166 });
167 }
168
169 const shell_rules = {};
170 // As long as we don't parse all items, we need to get some from general export
171 // Once we can parse all types, this can be dropped
172 status.modifications.push(...(output[0].split("\n").reduce(function (result, mod) {
173 mod = mod.trim();
174 if (mod === "")
175 return result;
176
177 const items = mod.split(" ");
178
179 // Skip enumeration of types, e.g. 'boolean -D'
180 if (items.length === 2 && items[1] == "-D")
181 return result;
182
183 if (manageditems.indexOf(items[0]) < 0) {
184 if (items[0] in shell_rules)
185 shell_rules[items[0]].push(" semanage " + mod);
186 else
187 shell_rules[items[0]] = [" semanage " + mod];
188 result.push(mod);
189 }
190 return result;
191 }, [])));
192
193 // Create shell rule for every ansible group separately
194 Object.keys(shell_rules).forEach(t => {
195 const rules = shell_rules[t].join("\n");
196 status.ansible += `
197 - name: Set up ${t} customizations
198 shell: |
199 semanage ${t} -D
200 ${rules}
201 `;
202 });
203
204 statusChangedCallback(status, undefined);
205 })
206 .catch(e => {
207 status.modifications = [];
208 if (e.message.indexOf("ValueError:") >= 0) {
209 status.permitted = false;
210 statusChangedCallback(status, undefined);
211 } else {
212 status.failed = true;
213 statusChangedCallback(status, e.message);
214 }
215 });
216 }
217
218 // returns a promise of the command used to set enforcing mode
219 export function setEnforcing(enforcingMode) {
220 const command = ["setenforce", (enforcingMode ? "1" : "0")];
221 return cockpit.spawn(command, { superuser: "require", err: "message" });
222 }