Debian Codegraph @

pkg/selinux/setroubleshoot-view.jsx

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 import React from "react";
9 import { Alert, AlertActionCloseButton, AlertGroup } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
10 import { Badge } from "@patternfly/react-core/dist/esm/components/Badge/index.js";
11 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
12 import { Divider } from "@patternfly/react-core/dist/esm/components/Divider/index.js";
13 import { Card, CardBody, CardHeader, CardTitle } from '@patternfly/react-core/dist/esm/components/Card/index.js';
14 import { ExpandableSection } from "@patternfly/react-core/dist/esm/components/ExpandableSection/index.js";
15 import { Flex } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
16 import { Page, PageSection } from "@patternfly/react-core/dist/esm/components/Page/index.js";
17 import { Switch } from "@patternfly/react-core/dist/esm/components/Switch/index.js";
18 import { Spinner } from "@patternfly/react-core/dist/esm/components/Spinner/index.js";
19 import { Stack, StackItem } from "@patternfly/react-core/dist/esm/layouts/Stack/index.js";
20 import { ExclamationCircleIcon, ExclamationTriangleIcon, InfoCircleIcon } from "@patternfly/react-icons";
21 import { Icon } from "@patternfly/react-core/dist/esm/components/Icon/index.js";
22 import { Content, ContentVariants } from "@patternfly/react-core/dist/esm/components/Content/index.js";
23 import { CodeBlock, CodeBlockCode } from "@patternfly/react-core/dist/esm/components/CodeBlock/index.js";
24
25 import { Modifications } from "cockpit-components-modifications";
26 import { EmptyStatePanel } from "cockpit-components-empty-state.jsx";
27 import { ListingTable } from "cockpit-components-table.jsx";
28 import { ListingPanel } from 'cockpit-components-listing-panel.jsx';
29 import * as timeformat from 'timeformat';
30 import { Title, TitleSizes } from "@patternfly/react-core/dist/esm/components/Title";
31
32 const _ = cockpit.gettext;
33
34 /* Show details for an alert, including possible solutions
35 * Props correspond to an item in the setroubleshoot dataStore
36 */
37 class SELinuxEventDetails extends React.Component {
38 runFix(itmIdx, runCommand) {
39 const localId = this.props.details.localId;
40 const analysisId = this.props.details.pluginAnalysis[itmIdx].analysisId;
41 this.props.runFix(localId, analysisId, itmIdx, runCommand);
42 }
43
44 render() {
45 if (!this.props.details) {
46 // details should be requested by default, so we just need to wait for them
47 if (this.props.details === undefined)
48 return <EmptyStatePanel loading title={ _("Waiting for details...") } />;
49 else
50 return <EmptyStatePanel icon={ExclamationCircleIcon} title={ _("Unable to get alert details.") } />;
51 }
52
53 const self = this;
54 const fixEntries = this.props.details.pluginAnalysis.map(function(itm, itmIdx) {
55 let fixit = null;
56 let fixit_command = null;
57 let msg = null;
58
59 /* some plugins like catchall_sebool don't report fixable as they offer multiple solutions;
60 * we can offer to run a single setsebool command for convenience */
61 let fixable = itm.fixable;
62 if (!fixable && itm.doText && itm.doText.startsWith("setsebool") && itm.doText.indexOf("\n") < 0) {
63 fixable = true;
64 fixit_command = itm.doText;
65 }
66
67 if (fixable) {
68 if ((itm.fix) && (itm.fix.plugin == itm.analysisId)) {
69 if (itm.fix.running) {
70 msg = (
71 <div>
72 <Spinner size="sm" className="setroubleshoot-progress-spinner" />
73 <span className="setroubleshoot-progress-message"> { _("Applying solution...") }</span>
74 </div>
75 );
76 } else {
77 if (itm.fix.success) {
78 msg = (
79 <Alert isInline variant="success" title={ _("Solution applied successfully") }>
80 {itm.fix.result}
81 </Alert>
82 );
83 } else {
84 msg = (
85 <Alert isInline variant="danger" title={ _("Solution failed") }>
86 {itm.fix.result}
87 </Alert>
88 );
89 }
90 }
91 }
92 if (!itm.fix) {
93 fixit = (
94 <div className="setroubleshoot-listing-action">
95 <Button variant="secondary" onClick={ self.runFix.bind(self, itmIdx, fixit_command) }>
96 { _("Apply this solution") }
97 </Button>
98 </div>
99 );
100 }
101 } else {
102 fixit = (
103 <div className="setroubleshoot-listing-action">
104 <span>{ _("Unable to apply this solution automatically") }</span>
105 </div>
106 );
107 }
108
109 function codeBlock(text, key) {
110 return (
111 <CodeBlock key={key} aria-label={_("solution")}>
112 <CodeBlockCode>{text}</CodeBlockCode>
113 </CodeBlock>
114 );
115 }
116
117 let doElement = "";
118
119 // One line usually means one command
120 if (itm.doText && itm.doText.indexOf("\n") < 0)
121 doElement = codeBlock(itm.doText);
122
123 // There can be text with commands. Command always starts on a new line with '#'
124 // Group subsequent commands into one `<CodeBlock>` element.
125 if (itm.doText && itm.doText.indexOf("\n") >= 0) {
126 const parts = [];
127 const lines = itm.doText.split("\n");
128 let lastCommand = false;
129 lines.forEach(l => {
130 if (l[0] == "#") { // command
131 if (lastCommand) // When appending command remove "# ". Only the first command keeps it and it is removed later on
132 parts[parts.length - 1] += ("\n" + l.substring(2));
133 else
134 parts.push(l);
135 lastCommand = true;
136 } else {
137 parts.push(l);
138 lastCommand = false;
139 }
140 });
141 doElement = parts.map((p, index) => p[0] == "#"
142 ? codeBlock(p.substring(2), index)
143 : <span key={p}>{p}</span>);
144 }
145
146 return (
147 <StackItem key={itm.analysisId + (itm.ifText || "") + (itm.doText || "")}>
148 <div className="selinux-details" data-solution-id={itmIdx}>
149 <div>
150 <div>
151 <span>{itm.ifText}</span>
152 </div>
153 <div>
154 {itm.thenText}
155 </div>
156 <ExpandableSection toggleText={_("solution details")}>
157 {doElement}
158 </ExpandableSection>
159 {msg}
160 </div>
161 {fixit}
162 </div>
163 {itmIdx != self.props.details.pluginAnalysis.length - 1 && <Divider />}
164 </StackItem>
165 );
166 });
167 return <Stack hasGutter>{fixEntries}</Stack>;
168 }
169 }
170
171 /* Show the audit log events for an alert */
172 const SELinuxEventLog = ({ details }) => {
173 if (!details) {
174 // details should be requested by default, so we just need to wait for them
175 if (details === undefined)
176 return <EmptyStatePanel loading title={ _("Waiting for details...") } />;
177 else
178 return <EmptyStatePanel icon={ExclamationCircleIcon} title={ _("Unable to get alert details.") } />;
179 }
180
181 const logEntries = details.auditEvent.map((itm, idx) => {
182 // use the alert id and index in the event log array as the data key for react
183 // if the log becomes dynamic, the entire log line might need to be considered as the key
184 return <div key={ details.localId + "." + idx }>{itm}</div>;
185 });
186 return <div className="setroubleshoot-log">{logEntries}</div>;
187 };
188
189 /* Component to show a dismissable error, message as child text
190 * dismissError callback function triggered when the close button is pressed
191 */
192 class DismissableError extends React.Component {
193 constructor(props) {
194 super(props);
195 this.handleDismissError = this.handleDismissError.bind(this);
196 }
197
198 handleDismissError(e) {
199 // only consider primary mouse button
200 if (!e || e.button !== 0)
201 return;
202 if (this.props.dismissError)
203 this.props.dismissError();
204 e.stopPropagation();
205 }
206
207 render() {
208 return (
209 <Alert isInline
210 variant='danger' title={this.props.children}
211 actionClose={<AlertActionCloseButton onClose={this.handleDismissError} />} />
212 );
213 }
214 }
215
216 /* Component to show selinux status and offer an option to change it
217 * selinuxStatus status of selinux on the system, properties as defined in selinux-client.js
218 * selinuxStatusError error message from reading or setting selinux status/mode
219 * changeSelinuxMode function to use for changing the selinux enforcing mode
220 * dismissError function to dismiss the error message
221 */
222 const SELinuxStatus = ({ selinuxStatus, selinuxStatusError, changeSelinuxMode, dismissError }) => {
223 const errorMessage = selinuxStatusError
224 ? <DismissableError dismissError={dismissError}>{selinuxStatusError}</DismissableError>
225 : null;
226
227 if (selinuxStatus.enabled === undefined) {
228 return (
229 <div>
230 {errorMessage}
231 <h3>{_("SELinux system status is unknown.")}</h3>
232 </div>
233 );
234 } else if (!selinuxStatus.enabled) {
235 return (
236 <div>
237 {errorMessage}
238 <h3>{_("SELinux is disabled on the system.")}</h3>
239 </div>
240 );
241 }
242 const configUnknown = (selinuxStatus.configEnforcing === undefined);
243 let note = null;
244 if (configUnknown)
245 note = _("The configured state is unknown, it might change on the next boot.");
246 else if (!configUnknown && selinuxStatus.enforcing !== selinuxStatus.configEnforcing)
247 note = _("Setting deviates from the configured state and will revert on the next boot.");
248
249 return (
250 <Stack hasGutter className="selinux-policy-ct">
251 <Flex spaceItems={{ default: 'spaceItemsMd' }} alignItems={{ default: 'alignItemsCenter' }}>
252 <Title headingLevel="h2" size={TitleSizes['3xl']}>
253 {_("SELinux policy")}
254 </Title>
255 <Switch isChecked={selinuxStatus.enforcing}
256 label={_("Enforcing")}
257 onChange={changeSelinuxMode} />
258 </Flex>
259 { note !== null &&
260 <Content component={ContentVariants.p}>
261 <Icon isInline status="info"><InfoCircleIcon /></Icon>
262 { "\n" }
263 { note }
264 </Content>
265 }
266 {errorMessage}
267 </Stack>
268 );
269 };
270
271 /* The listing only shows if we have a connection to the dbus API
272 * Otherwise we have blank slate: trying to connect, error
273 * Expected properties:
274 * connected true if the client is connected to setroubleshoot-server via dbus
275 * error error message to show (in EmptyState if not connected, as a dismissable alert otherwise
276 * dismissError callback, triggered for the dismissable error in connected state
277 * deleteAlert callback, triggered with an alert id as parameter to trigger deletion
278 * entries setroubleshoot entries
279 * - runFix function to run fix
280 * - details fix details as provided by the setroubleshoot client
281 * - description brief description of the error
282 * - count how many times (>= 1) this alert occurred
283 * selinuxStatus status of selinux on the system, properties as defined in selinux-client.js
284 * selinuxStatusError error message from reading or setting selinux status/mode
285 * changeSelinuxMode function to use for changing the selinux enforcing mode
286 * dismissStatusError function that is triggered to dismiss the selinux status error
287 */
288 export class SETroubleshootPage extends React.Component {
289 constructor(props) {
290 super(props);
291 this.state = { selected: {} };
292 this.handleDismissError = this.handleDismissError.bind(this);
293 this.onSelect = this.onSelect.bind(this);
294 }
295
296 handleDismissError(e) {
297 // only consider primary mouse button
298 if (!e || e.button !== 0)
299 return;
300 if (this.props.dismissError)
301 this.props.dismissError();
302 e.stopPropagation();
303 }
304
305 onSelect(_, isSelected, rowId) {
306 this.setState(prevState => ({
307 selected: { ...prevState.selected, [this.props.entries[rowId].key]: isSelected }
308 }));
309 }
310
311 render() {
312 // if selinux is disabled, we only show EmptyState
313 if (this.props.selinuxStatus.enabled === false) {
314 return <EmptyStatePanel icon={ ExclamationCircleIcon } title={ _("SELinux is disabled on the system") } />;
315 }
316 const self = this;
317 const title = _("SELinux access control errors");
318 const emptyCaption = _("No SELinux alerts.");
319 let emptyState;
320 let entries;
321 if (!this.props.connected) {
322 if (this.props.connecting) {
323 emptyState = <EmptyStatePanel paragraph={ _("Connecting to SETroubleshoot daemon...") } loading />;
324 } else {
325 // if we don't have setroubleshoot-server, be more subtle about saying that
326 emptyState = <EmptyStatePanel icon={ InfoCircleIcon }
327 paragraph={_("Install setroubleshoot-server to troubleshoot SELinux events.")} />;
328 }
329 } else {
330 entries = this.props.entries.map(function(itm, index) {
331 itm.runFix = self.props.runFix;
332 let listingDetail;
333 if (itm.details && 'firstSeen' in itm.details) {
334 if (itm.details.reportCount >= 2) {
335 listingDetail = cockpit.format(_("Occurred between $0 and $1"),
336 timeformat.dateTime(itm.details.firstSeen),
337 timeformat.dateTime(itm.details.lastSeen)
338 );
339 } else {
340 listingDetail = cockpit.format(_("Occurred $0"), timeformat.dateTime(itm.details.firstSeen));
341 }
342 }
343 const tabRenderers = [
344 {
345 name: _("Solutions"),
346 renderer: SELinuxEventDetails,
347 data: itm,
348 },
349 {
350 name: _("Audit log"),
351 renderer: SELinuxEventLog,
352 data: itm,
353 },
354 ];
355 // if the alert has level "red", it's critical
356 const criticalAlert = (itm.details && 'level' in itm.details && itm.details.level == "red")
357 ? <ExclamationTriangleIcon className="ct-icon-exclamation-triangle pf-v6-c-icon pf-m-lg" />
358 : null;
359 const columns = [
360 { title: criticalAlert },
361 { title: itm.description }
362 ];
363 if (itm.count > 1) {
364 columns.push({ title: <Badge isRead>{itm.count}</Badge>, props: { className: "pf-v6-c-table__action" } });
365 } else {
366 columns.push({ title: <span />, props: { className: "pf-v6-c-table__action" } });
367 }
368 const rowId = itm.details ? itm.details.localId : index;
369 return ({
370 props: { key: rowId, "data-row-id": rowId },
371 selected: self.state.selected[itm.details ? itm.details.localId : index],
372 disableSelection: !itm.details,
373 columns,
374 expandedContent: <ListingPanel tabRenderers={tabRenderers}
375 listingDetail={listingDetail} />
376 });
377 });
378 }
379 let selectedCnt = 0;
380 for (const k in this.state.selected) if (this.state.selected[k]) selectedCnt++;
381 const onDeleteClick = () => {
382 for (const k in this.state.selected)
383 if (this.state.selected[k])
384 this.props.deleteAlert(k).then(() => this.setState(prevState => ({ selected: { ...prevState.selected, [k]: false } })));
385 };
386 const actions = (
387 !emptyState
388 ? <Button className="selinux-alert-dismiss"
389 variant="danger"
390 onClick={onDeleteClick}
391 isDisabled={ !this.props.deleteAlert || !selectedCnt}>
392 {selectedCnt ? cockpit.format(cockpit.ngettext("Dismiss $0 alert", "Dismiss $0 alerts", selectedCnt), selectedCnt) : _("Dismiss selected alerts")}
393 </Button>
394 : null
395 );
396 const troubleshooting = (
397 <Card isPlain>
398 <CardHeader actions={{ actions }}>
399 <CardTitle component="h2">{title}</CardTitle>
400 </CardHeader>
401 <CardBody className="contains-list">
402 {!emptyState
403 ? <ListingTable aria-label={ title }
404 id="selinux-alerts"
405 onSelect={this.onSelect}
406 gridBreakPoint=''
407 emptyCaption={ emptyCaption }
408 columns={[{ title: _("Alert") }, { title: _("Error message"), header: true }, { title: _("Occurrences") }]}
409 showHeader={false}
410 variant="compact"
411 rows={entries} />
412 : emptyState}
413 </CardBody>
414 </Card>
415 );
416
417 const modifications = (
418 <Modifications
419 title={ _("System modifications") }
420 permitted={ this.props.selinuxStatus.permitted }
421 shell={ "semanage import <<EOF\n" + this.props.selinuxStatus.shell.trim() + "\nEOF" }
422 ansible={ this.props.selinuxStatus.ansible }
423 entries={ this.props.selinuxStatus.modifications }
424 failed={this.props.selinuxStatus.failed ? _("Error running semanage to discover system modifications") : null}
425 />
426 );
427
428 let errorMessage;
429 if (this.props.error) {
430 errorMessage = (
431 <AlertGroup isToast>
432 <Alert
433 isLiveRegion
434 variant='danger' title={this.props.error}
435 actionClose={<AlertActionCloseButton onClose={this.handleDismissError} />} />
436 </AlertGroup>
437 );
438 }
439
440 return (
441 <>
442 {errorMessage}
443 <Page className="pf-m-no-sidebar">
444 <PageSection hasBodyWrapper={false} padding={{ default: "padding" }}>
445 <SELinuxStatus
446 selinuxStatus={this.props.selinuxStatus}
447 selinuxStatusError={this.props.selinuxStatusError}
448 changeSelinuxMode={this.props.changeSelinuxMode}
449 dismissError={this.props.dismissStatusError}
450 />
451 </PageSection>
452 <PageSection hasBodyWrapper={false}>
453 <Stack hasGutter>
454 <StackItem>{modifications}</StackItem>
455 <StackItem>{troubleshooting}</StackItem>
456 </Stack>
457 </PageSection>
458 </Page>
459 </>
460 );
461 }
462 }