Debian Codegraph @

pkg/networkmanager/firewall.jsx

raw
1 /*
2 * Copyright (C) 2018 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import '../lib/patternfly/patternfly-6-cockpit.scss';
7 import 'cockpit-dark-theme'; // once per page
8 import cockpit from "cockpit";
9 import React from 'react';
10 import { createRoot } from "react-dom/client";
11 import { Alert } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
12 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
13 import { Breadcrumb, BreadcrumbItem } from "@patternfly/react-core/dist/esm/components/Breadcrumb/index.js";
14 import { Checkbox } from "@patternfly/react-core/dist/esm/components/Checkbox/index.js";
15 import { Card, CardBody, CardHeader, CardTitle } from '@patternfly/react-core/dist/esm/components/Card/index.js';
16 import { DataList, DataListCell, DataListCheck, DataListItem, DataListItemCells, DataListItemRow } from "@patternfly/react-core/dist/esm/components/DataList/index.js";
17 import { DropdownItem } from '@patternfly/react-core/dist/esm/components/Dropdown/index.js';
18 import { Flex, FlexItem } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
19 import { Form, FormGroup, FormHelperText } from "@patternfly/react-core/dist/esm/components/Form/index.js";
20 import { Radio } from "@patternfly/react-core/dist/esm/components/Radio/index.js";
21 import { Stack } from "@patternfly/react-core/dist/esm/layouts/Stack/index.js";
22 import { TextInput } from "@patternfly/react-core/dist/esm/components/TextInput/index.js";
23 import { Title } from "@patternfly/react-core/dist/esm/components/Title/index.js";
24 import { Toolbar, ToolbarContent, ToolbarItem } from "@patternfly/react-core/dist/esm/components/Toolbar/index.js";
25 import { Page, PageBreadcrumb, PageSection, } from "@patternfly/react-core/dist/esm/components/Page/index.js";
26 import {
27 Modal, ModalBody, ModalFooter, ModalHeader
28 } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
29 import { ExclamationCircleIcon } from '@patternfly/react-icons';
30
31 import firewall from "./firewall-client.js";
32 import { FormHelper } from "cockpit-components-form-helper";
33 import { ListingTable } from 'cockpit-components-table.jsx';
34 import { ModalError } from "cockpit-components-inline-notification.jsx";
35 import { EmptyStatePanel } from "cockpit-components-empty-state.jsx";
36 import { FirewallSwitch } from "./firewall-switch.jsx";
37
38 import { superuser } from "superuser";
39 import { WithDialogs, DialogsContext } from "dialogs.jsx";
40
41 import { KebabDropdown } from "cockpit-components-dropdown";
42
43 import "./networking.scss";
44
45 const _ = cockpit.gettext;
46
47 superuser.reload_page_on_change();
48
49 const upperCaseFirstLetter = text => text[0].toUpperCase() + text.slice(1);
50
51 const DeleteDropdown = ({ items }) => {
52 const dropdown_items = items.map(item => <DropdownItem key={item.text}
53 className={item.danger ? "pf-m-danger" : ""}
54 aria-label={item.ariaLabel}
55 onClick={item.handleClick}>
56 {item.text}
57 </DropdownItem>);
58
59 return <KebabDropdown dropdownItems={dropdown_items} />;
60 };
61
62 function serviceRow(props) {
63 let tcp = props.service.ports.filter(p => p.protocol.toUpperCase() == 'TCP');
64 let udp = props.service.ports.filter(p => p.protocol.toUpperCase() == 'UDP');
65
66 for (const s of props.service.includes) {
67 if (firewall.services[s]) {
68 tcp = tcp.concat(firewall.services[s].ports.filter(p => p.protocol.toUpperCase() == 'TCP'));
69 udp = udp.concat(firewall.services[s].ports.filter(p => p.protocol.toUpperCase() == 'UDP'));
70 }
71 }
72
73 function onRemoveService(event) {
74 props.onRemoveService(props.service.id);
75 event.stopPropagation();
76 }
77
78 function onEditService(event) {
79 props.onEditService(props.service.id);
80 event.stopPropagation();
81 }
82
83 const columns = [
84 {
85 title: props.service.id, header: true
86 },
87 {
88 title: <div key={props.service.id + "tcp"}>
89 { tcp.map(p => p.port).join(', ') }
90 </div>
91 },
92 {
93 title: <div key={props.service.id + "udp"}>
94 { udp.map(p => p.port).join(', ') }
95 </div>
96 },
97 ];
98
99 if (!props.readonly) {
100 // Only allow editing manually created services - no name is a decent (and only) indicator
101 const items = [];
102 if (!props.service.name)
103 items.push({ text: _("Edit"), ariaLabel: cockpit.format(_("Edit service $0"), props.service.id), handleClick: onEditService });
104
105 items.push({ text: _("Delete"), danger: true, ariaLabel: cockpit.format(_("Remove service $0"), props.service.id), handleClick: onRemoveService });
106
107 columns.push({
108 title: <DeleteDropdown items={items} />
109 });
110 }
111
112 let description;
113 let includes;
114 if (props.service.description)
115 description = <p>{props.service.description}</p>;
116
117 if (props.service.includes.length > 0) {
118 includes = <>
119 <h5>{_("Included Services")}</h5>
120 <ul>{props.service.includes.map(s => {
121 const service = firewall.services[s];
122 if (service && service.description)
123 return <li key={service.id}><strong>{service.id}</strong>: {service.description}</li>;
124 else
125 return null;
126 })} </ul></>;
127 }
128
129 return ({
130 props: { key: props.service.id, 'data-row-id': props.service.id },
131 columns,
132 hasPadding: true,
133 expandedContent: <>{description}{includes}</>,
134 });
135 }
136
137 function portRow(props) {
138 function onRemovePort(event) {
139 props.onRemovePort(props.port);
140 event.stopPropagation();
141 }
142
143 const columns = [
144 {
145 title: <i key={props.key + "-additional-port"}>{ _("Additional port") }</i>
146 },
147
148 { title: props.port.protocol === "tcp" ? props.port.port : "" },
149 { title: props.port.protocol === "udp" ? props.port.port : "" },
150
151 { title: <DeleteDropdown items={[{ text: _("Delete"), danger: true, ariaLabel: _("Remove additional port"), handleClick: onRemovePort }]} /> }
152 ];
153 return ({
154 props: { key: props.key + "-port", 'data-row-id': props.key + "-port" },
155 columns
156 });
157 }
158
159 function ZoneSection(props) {
160 function onRemoveZone(event) {
161 event.stopPropagation();
162 props.onRemoveZone(props.zone.id);
163 }
164
165 const deleteButton = (<DeleteDropdown items={[{ text: _("Delete"), danger: true, ariaLabel: cockpit.format(_("Remove zone $0"), props.zone.id), handleClick: onRemoveZone }]} id={`dropdown-${props.zone.id}`} />);
166 const addServiceAction = (
167 <Button variant="primary" onClick={() => props.openServicesDialog(props.zone.id, props.zone.id)} className="add-services-button" aria-label={cockpit.format(_("Add services to zone $0"), props.zone.id)}>
168 {_("Add services")}
169 </Button>
170 );
171
172 const actions = !firewall.readonly && <div className="zone-section-buttons">{addServiceAction}{deleteButton}</div>;
173
174 /** @type {import('cockpit-components-table.jsx').ListingTableColumnProps[]} */
175 const listingTableColumns = [
176 {
177 title: _("Service"),
178 props: {
179 width: 40,
180 }
181 },
182 {
183 title: _("TCP"),
184 props: {
185 width: 30
186 }
187 },
188 {
189 title: _("UDP"),
190 props: {
191 width: 30
192 }
193 },
194 {
195 title: "",
196 props: {
197 width: 10,
198 screenReaderText: _("Actions")
199 }
200 }
201 ];
202
203 return <Card isPlain className="zone-section" data-id={props.zone.id}>
204 <CardHeader actions={{ actions }} className="zone-section-heading">
205 <Flex alignItems={{ default: 'alignSelfBaseline' }} spaceItems={{ default: 'spaceItemsXl' }}>
206 <CardTitle component="h2">
207 { cockpit.format(_("$0 zone"), upperCaseFirstLetter(props.zone.name || props.zone.id)) }
208 </CardTitle>
209 <Flex>
210 { props.zone.interfaces.length > 0 &&
211 <span>
212 <strong>{cockpit.ngettext("Interface", "Interfaces", props.zone.interfaces.length)}</strong> {props.zone.interfaces.join(", ")}
213 </span>
214 }
215 <span>
216 <strong>{_("Allowed addresses")}</strong> {props.zone.source.length ? props.zone.source.join(", ") : _("Entire subnet")}
217 </span>
218 </Flex>
219 </Flex>
220 </CardHeader>
221 {(props.zone.services.length > 0 || props.zone.ports.length > 0) &&
222 <CardBody className="contains-list">
223 <ListingTable columns={listingTableColumns}
224 id={props.zone.id}
225 aria-label={props.zone.id}
226 variant="compact"
227 emptyCaption={_("There are no active services in this zone")}
228 rows={
229 props.zone.services.map(s => {
230 if (s in firewall.services) {
231 return serviceRow({
232 key: firewall.services[s].id,
233 service: firewall.services[s],
234 onRemoveService: service => props.onRemoveService(props.zone.id, service),
235 onEditService: service => props.onEditService(props.zone, firewall.services[service]),
236 readonly: firewall.readonly,
237 });
238 } else {
239 return null;
240 }
241 }).concat(
242 props.zone.ports.length > 0
243 ? props.zone.ports.map(p => {
244 return portRow({
245 key: `${props.zone.id}-${p.port}-${p.protocol}`,
246 zone: props.zone,
247 port: p,
248 onRemovePort: port => props.onRemovePort(props.zone.id, port.port, port.protocol),
249 readonly: firewall.readonly
250 });
251 })
252 : [])
253 .filter(Boolean)}
254
255 />
256 </CardBody>}
257 </Card>;
258 }
259
260 class SearchInput extends React.Component {
261 constructor(props) {
262 super(props);
263 this.onValueChanged = this.onValueChanged.bind(this);
264 this.state = { value: props.value || "" };
265 }
266
267 onValueChanged(value) {
268 this.setState({ value });
269
270 if (this.timer)
271 window.clearTimeout(this.timer);
272
273 this.timer = window.setTimeout(() => {
274 this.props.onChange(value);
275 this.timer = null;
276 }, 300);
277 }
278
279 render() {
280 return (
281 <Toolbar className="filter-services-toolbar">
282 <ToolbarContent>
283 <ToolbarItem variant="label">
284 {_("Filter services")}
285 </ToolbarItem>
286 <ToolbarItem>
287 <TextInput type="search"
288 id={this.props.id}
289 onChange={(_event, value) => this.onValueChanged(value)}
290 value={this.state.value}
291 />
292 </ToolbarItem>
293 </ToolbarContent>
294 </Toolbar>
295 );
296 }
297 }
298
299 const renderPorts = service => {
300 const tcpPorts = [];
301 const udpPorts = [];
302 function addPorts(ports) {
303 for (const port of ports) {
304 if (port.protocol === "tcp")
305 tcpPorts.push(port.port);
306 else
307 udpPorts.push(port.port);
308 }
309 }
310 addPorts(service.ports);
311 for (const s of service.includes)
312 addPorts(firewall.services[s].ports);
313
314 return (
315 <div className="service-list-item-text">
316 { tcpPorts.length > 0 && <span className="service-ports tcp"><strong>TCP: </strong>{ tcpPorts.join(', ') }</span> }
317 { udpPorts.length > 0 && <span className="service-ports udp"><strong>UDP: </strong>{ udpPorts.join(', ') }</span> }
318 </div>
319 );
320 };
321
322 class AddEditServicesModal extends React.Component {
323 static contextType = DialogsContext;
324
325 constructor(props) {
326 super(props);
327
328 this.state = {
329 services: null,
330 selected: new Set(),
331 filter: "",
332 custom: !!props.custom_id,
333 generate_custom_id: !props.custom_id,
334 tcp_error: "",
335 udp_error: "",
336 avail_services: null,
337 custom_id: props.custom_id || "",
338 custom_description: props.custom_description || "",
339 custom_tcp_ports: props.custom_tcp_ports || [],
340 custom_udp_ports: props.custom_udp_ports || [],
341 custom_tcp_value: props.custom_tcp_value || "",
342 custom_udp_value: props.custom_udp_value || "",
343 dialogError: null,
344 dialogErrorDetail: null,
345 };
346 this.save = this.save.bind(this);
347 this.edit = this.edit.bind(this);
348 this.checkNullValues = this.checkNullValues.bind(this);
349 this.onFilterChanged = this.onFilterChanged.bind(this);
350 this.onToggleService = this.onToggleService.bind(this);
351 this.setId = this.setId.bind(this);
352 this.setDescription = this.setDescription.bind(this);
353 this.getName = this.getName.bind(this);
354 this.validate = this.validate.bind(this);
355 this.createPorts = this.createPorts.bind(this);
356 this.parseServices = this.parseServices.bind(this);
357 this.onToggleType = this.onToggleType.bind(this);
358 this.getCustomId = this.getCustomId.bind(this);
359 }
360
361 createPorts() {
362 const ret = [];
363 this.state.custom_tcp_ports.forEach(port => ret.push([port, 'tcp']));
364 this.state.custom_udp_ports.forEach(port => ret.push([port, 'udp']));
365 return ret;
366 }
367
368 getCustomId() {
369 return "custom--" + (
370 this.state.custom_tcp_ports.map(port => this.getName(port, "tcp"))
371 .concat(this.state.custom_udp_ports.map(port => this.getName(port, "udp")))
372 .join('-')
373 );
374 }
375
376 checkNullValues() {
377 return (!this.state.custom_tcp_value && !this.state.custom_udp_value);
378 }
379
380 edit(event) {
381 const Dialogs = this.context;
382 firewall.editService(this.props.custom_id, this.createPorts(), this.state.custom_description)
383 .then(() => Dialogs.close())
384 .catch(error => {
385 this.setState({
386 dialogError: _("Failed to edit service"),
387 dialogErrorDetail: error.name + ": " + error.message,
388 });
389 });
390
391 if (event)
392 event.preventDefault();
393 return false;
394 }
395
396 save(event) {
397 const Dialogs = this.context;
398 let p;
399 if (this.state.custom) {
400 const custom_id = this.state.custom_id === "" ? this.getCustomId() : this.state.custom_id;
401 p = firewall.createService(custom_id, this.createPorts(), this.props.zoneId, this.state.custom_description);
402 } else {
403 p = firewall.addServices(this.props.zoneId, [...this.state.selected]);
404 }
405 p.then(() => Dialogs.close())
406 .catch(error => {
407 this.setState(prevState => ({
408 dialogError: prevState.custom ? _("Failed to add port") : _("Failed to add service"),
409 dialogErrorDetail: error.name + ": " + error.message,
410 }));
411 });
412
413 if (event)
414 event.preventDefault();
415 return false;
416 }
417
418 onToggleService(event, serviceId) {
419 const service = serviceId;
420 const enabled = event.target.checked;
421
422 this.setState(oldState => {
423 const selected = new Set(oldState.selected);
424
425 if (enabled)
426 selected.add(service);
427 else
428 selected.delete(service);
429
430 return {
431 selected
432 };
433 });
434 }
435
436 /* Create list of services from /etc/services type file
437 *
438 * Return dictionary of services:
439 * - key => port number or port alias (80/http)
440 * - item => dictionary with 3 compulsory items:
441 * - name => port alias (http)
442 * - port => port number (80)
443 * - type => list of types (tcp/udp...)
444 * - description => _may be not present_ (Web Server)
445 */
446 parseServices(content) {
447 if (!content) {
448 console.warn("Couldn't read /etc/services");
449 return [];
450 }
451
452 const ret = {};
453 content.split('\n').forEach(line => {
454 if (!line || line.startsWith("#"))
455 return;
456 const m = line.match(/^(\S+)\s+(\d+)\/(\S+).*?(#(.*))?$/);
457 const new_port = { name: m[1], port: m[2], type: [m[3]] };
458 if (m.length > 5 && m[5])
459 new_port.description = m[5].trim();
460 if (ret[m[1]])
461 ret[m[1]].type.push(new_port.type[0]);
462 else
463 ret[m[1]] = new_port;
464 if (ret[m[2]])
465 ret[m[2]].type.push(new_port.type[0]);
466 else
467 ret[m[2]] = new_port;
468 });
469 return ret;
470 }
471
472 setId(value) {
473 this.setState({
474 custom_id: value,
475 generate_custom_id: value.length === 0,
476 });
477 }
478
479 setDescription(value) {
480 this.setState({
481 custom_description: value
482 });
483 }
484
485 getName(port, type) {
486 const known = this.state.avail_services[port];
487 if (known && known.type.includes(type))
488 return known.name;
489 else
490 return port;
491 }
492
493 getPortNumber(port, type, avail) {
494 if (!avail) {
495 const num_p = Number(port);
496 if (isNaN(num_p))
497 return [0, _("Unknown service name")];
498 else if (num_p <= 0 || num_p > 65535)
499 return [0, _("Invalid port number")];
500 else
501 return [port, ""];
502 } else {
503 return [avail.port, ""];
504 }
505 }
506
507 validate(event, value) {
508 let error = "";
509 let targets = ['tcp', 'custom_tcp_ports', 'tcp_error', 'custom_tcp_value'];
510 if (event.target.id === "udp-ports")
511 targets = ['udp', 'custom_udp_ports', 'udp_error', 'custom_udp_value'];
512 const new_ports = [];
513 const event_id = event.target.id;
514
515 this.setState(oldState => {
516 const ports = value.split(',');
517 ports.forEach((port) => {
518 port = port.trim();
519 if (!port)
520 return;
521 let ports;
522 if (port.indexOf("-") > -1) {
523 ports = port.split("-");
524 if (ports.length != 2) {
525 error = _("Invalid range");
526 return;
527 }
528 [ports[0], error] = this.getPortNumber(ports[0], targets[0], oldState.avail_services[ports[0]]);
529 if (!error) {
530 [ports[1], error] = this.getPortNumber(ports[1], targets[0], oldState.avail_services[ports[1]]);
531 if (!error) {
532 if (Number(ports[0]) >= Number(ports[1]))
533 error = _("Range must be strictly ordered");
534 else
535 new_ports.push(ports[0] + "-" + ports[1]);
536 }
537 }
538 } else {
539 [ports, error] = this.getPortNumber(port, targets[0], oldState.avail_services[port]);
540 if (!error)
541 new_ports.push(ports);
542 }
543 });
544 const newState = {
545 [targets[1]]: new_ports,
546 [targets[2]]: error,
547 [targets[3]]: value
548 };
549
550 let all_ports;
551 if (event_id === "udp-ports") {
552 const old_ports = oldState.custom_tcp_ports.map(port => this.getName(port, "tcp"));
553 all_ports = old_ports.concat(new_ports.map(port => this.getName(port, "udp")));
554 } else {
555 const old_ports = oldState.custom_udp_ports.map(port => this.getName(port, "udp"));
556 all_ports = new_ports.map(port => this.getName(port, "tcp")).concat(old_ports);
557 }
558
559 if (oldState.generate_custom_id) {
560 if (all_ports.length > 0)
561 newState.custom_id = "custom--" + all_ports.join('-');
562 else
563 newState.custom_id = "";
564 }
565
566 return newState;
567 });
568 }
569
570 onToggleType(event) {
571 this.setState({
572 custom: event.target.value === "ports"
573 });
574 }
575
576 componentDidMount() {
577 firewall.getAvailableServices()
578 .then(services => this.setState({ services }));
579 cockpit.file('/etc/services').read()
580 .then(content => this.setState({
581 avail_services: this.parseServices(content)
582 }));
583 }
584
585 onFilterChanged(value) {
586 this.setState({ filter: value.toLowerCase() });
587 }
588
589 render() {
590 const Dialogs = this.context;
591 let services;
592 if (this.state.filter && this.state.services && !isNaN(this.state.filter))
593 services = this.state.services.filter(s => {
594 for (const port of s.ports)
595 if (port.port === this.state.filter)
596 return true;
597 return false;
598 });
599 else if (this.state.filter && this.state.services)
600 services = this.state.services.filter(s => s.id.indexOf(this.state.filter) > -1);
601 else
602 services = this.state.services;
603
604 // hide services which have been enabled in the zone
605 if (services)
606 services = services.filter(s => firewall.zones[this.props.zoneId].services.indexOf(s.id) === -1);
607
608 let addText = "";
609 let titleText = "";
610 if (this.props.custom_id) {
611 addText = _("Edit service");
612 titleText = cockpit.format(_("Edit custom service in $0 zone"), this.props.zoneName);
613 } else {
614 addText = this.state.custom ? _("Add ports") : _("Add services");
615 titleText = this.state.custom ? cockpit.format(_("Add ports to $0 zone"), this.props.zoneName) : cockpit.format(_("Add services to $0 zone"), this.props.zoneName);
616 }
617
618 return (
619 <Modal id="add-services-dialog" isOpen
620 position="top" variant="medium"
621 onClose={Dialogs.close}
622 >
623 <ModalHeader title={titleText} />
624 <ModalBody>
625 <Form isHorizontal onSubmit={this.props.custom_id ? this.edit : this.save}>
626 {
627 this.state.dialogError && <ModalError dialogError={this.state.dialogError} dialogErrorDetail={this.state.dialogErrorDetail} />
628 }
629 { !!this.props.custom_id ||
630 <FormGroup className="add-services-dialog-type" isInline>
631 <Radio name="type"
632 id="add-services-dialog--services"
633 value="services"
634 isChecked={!this.state.custom}
635 onChange={this.onToggleType}
636 label={_("Services")} />
637 <Radio name="type"
638 id="add-services-dialog--ports"
639 value="ports"
640 isChecked={this.state.custom}
641 onChange={this.onToggleType}
642 isDisabled={this.state.avail_services == null}
643 label={_("Custom ports")} />
644 </FormGroup>
645 }
646 { this.state.custom ||
647 <div>
648 { services
649 ? (
650 <>
651 <SearchInput id="filter-services-input"
652 value={this.state.filter}
653 onChange={this.onFilterChanged} />
654 <DataList className="service-list" isCompact>
655 {services.map(s => (
656 <DataListItem key={s.id} aria-labelledby={s.id}>
657 <DataListItemRow>
658 <DataListCheck aria-labelledby={s.id}
659 isChecked={this.state.selected.has(s.id)}
660 onChange={(event, value) => this.onToggleService(event, s.id)}
661 id={"firewall-service-" + s.id}
662 name={s.id + "-checkbox"} />
663 <DataListItemCells
664 dataListCells={[
665 <DataListCell key="service-list-item">
666 <label htmlFor={"firewall-service-" + s.id}
667 className="service-list-iteam-heading">
668 {s.id}
669 </label>
670 {renderPorts(s)}
671 </DataListCell>,
672 ]} />
673 </DataListItemRow>
674 </DataListItem>
675 ))}
676 </DataList>
677 </>
678 )
679 : (
680 <EmptyStatePanel loading />
681 )}
682 </div>
683 }
684 { !this.state.custom ||
685 <>
686 <FormGroup label="TCP">
687 <TextInput id="tcp-ports" type="text" onChange={this.validate}
688 validated={this.state.tcp_error ? "error" : "default"}
689 isDisabled={this.state.avail_services == null}
690 value={this.state.custom_tcp_value}
691 placeholder={_("Example: 22,ssh,8080,5900-5910")} />
692 <FormHelper helperTextInvalid={this.state.tcp_error} helperText={_("Comma-separated ports, ranges, and services are accepted")} />
693 </FormGroup>
694
695 <FormGroup label="UDP">
696 <TextInput id="udp-ports" type="text" onChange={this.validate}
697 validated={this.state.udp_error ? "error" : "default"}
698 isDisabled={this.state.avail_services == null}
699 value={this.state.custom_udp_value}
700 placeholder={_("Example: 88,2019,nfs,rsync")} />
701 <FormHelper helperTextInvalid={this.state.udp_error} helperText={_("Comma-separated ports, ranges, and services are accepted")} />
702 </FormGroup>
703
704 <FormGroup label={_("ID")}>
705 <TextInput id="service-name" onChange={(_event, value) => this.setId(value)} isDisabled={!!this.props.custom_id || this.state.avail_services == null}
706 value={this.state.custom_id} />
707 <FormHelper helperText={_("If left empty, ID will be generated based on associated port services and port numbers")} />
708 </FormGroup>
709
710 <FormGroup label={_("Description")}>
711 <TextInput id="service-description" onChange={(_event, value) => this.setDescription(value)} isDisabled={this.state.avail_services == null}
712 value={this.state.custom_description} />
713 </FormGroup>
714 </>
715 }
716 </Form>
717 </ModalBody>
718 <ModalFooter>
719 { !this.state.custom ||
720 <Alert variant="warning"
721 isInline
722 title={_("Adding custom ports will reload firewalld. A reload will result in the loss of any runtime-only configuration!")} />
723 }
724 <Button variant='primary' isDisabled={(this.state.custom && this.checkNullValues()) || (!this.state.custom && !this.state.selected.size)} onClick={this.props.custom_id ? this.edit : this.save} aria-label={titleText}>
725 {addText}
726 </Button>
727 <Button variant='link' className='btn-cancel' onClick={Dialogs.close}>
728 {_("Cancel")}
729 </Button>
730 </ModalFooter>
731 </Modal>
732 );
733 }
734 }
735
736 class ActivateZoneModal extends React.Component {
737 static contextType = DialogsContext;
738
739 constructor() {
740 super();
741
742 this.state = {
743 ipRange: "ip-entire-subnet",
744 ipRangeValue: null,
745 zone: null,
746 interfaces: new Set(),
747 dialogError: null,
748 dialogErrorDetail: null,
749 };
750 this.onFirewallChanged = this.onFirewallChanged.bind(this);
751 this.onInterfaceChange = this.onInterfaceChange.bind(this);
752 this.onChange = this.onChange.bind(this);
753 this.save = this.save.bind(this);
754 }
755
756 componentDidMount() {
757 firewall.addEventListener("changed", this.onFirewallChanged);
758 }
759
760 componentWillUnmount() {
761 firewall.removeEventListener("changed", this.onFirewallChanged);
762 }
763
764 onFirewallChanged() {
765 this.setState({});
766 }
767
768 onInterfaceChange(event) {
769 const int = event.target.value;
770 const enabled = event.target.checked;
771 this.setState(state => {
772 const interfaces = new Set(state.interfaces);
773 if (enabled)
774 interfaces.add(int);
775 else
776 interfaces.delete(int);
777 return { interfaces };
778 });
779 }
780
781 onChange(key, value) {
782 this.setState({ [key]: value });
783 }
784
785 save(event) {
786 const Dialogs = this.context;
787 let p;
788 if (firewall.zones[this.state.zone].services.indexOf("cockpit") === -1)
789 p = firewall.addService(this.state.zone, "cockpit");
790 else
791 p = Promise.resolve();
792
793 const sources = this.state.ipRange === "ip-range" ? this.state.ipRangeValue.split(",").map(ip => ip.trim()) : [];
794 p.then(() =>
795 firewall.activateZone(this.state.zone, [...this.state.interfaces], sources)
796 .then(Dialogs.close)
797 .catch(error => {
798 this.setState({
799 dialogError: _("Failed to add zone"),
800 dialogErrorDetail: error.name + ": " + error.message,
801 });
802 }));
803
804 if (event)
805 event.preventDefault();
806 return false;
807 }
808
809 render() {
810 const Dialogs = this.context;
811 const zones = Object.keys(firewall.zones).filter(z => firewall.zones[z].target === "default" && !firewall.activeZones.has(z));
812 const customZones = zones.filter(z => firewall.predefinedZones.indexOf(z) === -1);
813 const interfaces = firewall.availableInterfaces.filter(i => {
814 let inZone = false;
815 firewall.activeZones.forEach(z => {
816 inZone ||= firewall.zones[z].interfaces.indexOf(i.device) !== -1;
817 });
818 return !inZone;
819 });
820 // https://networkmanager.dev/docs/api/latest/nm-dbus-types.html#NMDeviceCapabilities
821 const NM_DEVICE_CAP_IS_SOFTWARE = 4;
822 const virtualDevices = interfaces.filter(i => (i.capabilities & NM_DEVICE_CAP_IS_SOFTWARE) !== 0 && i.device !== "lo").sort((a, b) => a.device.localeCompare(b.device));
823 const physicalDevices = interfaces.filter(i => ((i.capabilities & NM_DEVICE_CAP_IS_SOFTWARE) === 0) && i.device !== "lo").sort((a, b) => a.device.localeCompare(b.device));
824 return (
825 <Modal id="add-zone-dialog" isOpen
826 position="top" variant="medium"
827 onClose={Dialogs.close}
828 >
829 <ModalHeader title={_("Add zone")} />
830 <ModalBody>
831 <Form isHorizontal onSubmit={this.save}>
832 {
833 this.state.dialogError && <ModalError dialogError={this.state.dialogError} dialogErrorDetail={this.state.dialogErrorDetail} />
834 }
835 <FormGroup label={ _("Trust level") } className="add-zone-zones">
836 <Flex>
837 <FlexItem className="add-zone-zones-firewalld">
838 <legend>{ _("Sorted from least to most trusted") }</legend>
839 { zones.filter(z => firewall.predefinedZones.indexOf(z) !== -1).sort((a, b) => firewall.predefinedZones.indexOf(a) - firewall.predefinedZones.indexOf(b))
840 .map(z =>
841 <Radio key={z} id={z} name="zone" value={z}
842 isChecked={this.state.zone == z}
843 onChange={e => this.onChange("zone", e.target.value)}
844 label={ firewall.zones[z].id } />
845 )}
846 </FlexItem>
847 <FlexItem className="add-zone-zones-custom">
848 { customZones.length > 0 && <legend>{ _("Custom zones") }</legend> }
849 { customZones.map(z =>
850 <Radio key={z} id={z} name="zone" value={z}
851 isChecked={this.state.zone == z}
852 onChange={e => this.onChange("zone", e.target.value)}
853 label={ firewall.zones[z].id } />
854 )}
855 </FlexItem>
856 </Flex>
857 </FormGroup>
858
859 <FormGroup label={ _("Description") }>
860 <p id="add-zone-description-readonly">
861 { (this.state.zone && firewall.zones[this.state.zone].description) || _("No description available") }
862 </p>
863 </FormGroup>
864
865 <FormGroup label={ _("Included services") } hasNoPaddingTop>
866 <div id="add-zone-services-readonly">
867 { (this.state.zone && firewall.zones[this.state.zone].services.join(", ")) || _("None") }
868 </div>
869 <FormHelper helperText={_("The cockpit service is automatically included")} />
870 </FormGroup>
871
872 <FormGroup label={ _("Interfaces") } hasNoPaddingTop isInline>
873 { physicalDevices.map(i =>
874 <Checkbox key={i.device}
875 id={i.device}
876 value={i.device}
877 onChange={(event, value) => this.onInterfaceChange(event)}
878 isChecked={this.state.interfaces.has(i.device)}
879 label={i.device} />) }
880 { virtualDevices.map(i =>
881 <Checkbox key={i.device}
882 id={i.device}
883 value={i.device}
884 onChange={(event, value) => this.onInterfaceChange(event)}
885 isChecked={this.state.interfaces.has(i.device)}
886 label={i.device} />) }
887 </FormGroup>
888
889 <FormGroup label={ _("Allowed addresses") } hasNoPaddingTop isInline>
890 <Radio name="add-zone-ip"
891 isChecked={this.state.ipRange == "ip-entire-subnet"}
892 value="ip-entire-subnet"
893 id="ip-entire-subnet"
894 onChange={e => this.onChange("ipRange", e.target.value)}
895 label={ _("Entire subnet") } />
896 <Radio name="add-zone-ip"
897 isChecked={this.state.ipRange == "ip-range"}
898 value="ip-range"
899 id="ip-range"
900 onChange={e => this.onChange("ipRange", e.target.value)}
901 label={ _("Range") } />
902 {this.state.ipRange === "ip-range" && (
903 <>
904 <TextInput id="add-zone-ip" onChange={(_event, value) => this.onChange("ipRangeValue", value)} />
905 <FormHelperText>{_("IP address with routing prefix. Separate multiple values with a comma. Example: 192.0.2.0/24, 2001:db8::/32")}</FormHelperText>
906 </>
907 )}
908 </FormGroup>
909 </Form>
910 </ModalBody>
911 <ModalFooter>
912 <Button variant="primary" onClick={this.save} isDisabled={this.state.zone === null ||
913 (this.state.interfaces.size === 0 && this.state.ipRange === "ip-entire-subnet") ||
914 (this.state.ipRange === "ip-range" && !this.state.ipRangeValue)}>
915 { _("Add zone") }
916 </Button>
917 <Button variant="link" className="btn-cancel" onClick={Dialogs.close}>
918 { _("Cancel") }
919 </Button>
920 </ModalFooter>
921 </Modal>
922 );
923 }
924 }
925
926 function DeleteConfirmationModal(props) {
927 return (
928 <Modal id="delete-confirmation-dialog" isOpen
929 position="top" variant="medium"
930 onClose={props.onCancel}
931 >
932 <ModalHeader title={props.title} />
933 {props.body &&
934 <ModalBody>
935 <Alert variant="warning" isInline title={props.body} />
936 </ModalBody>}
937 <ModalFooter>
938 <Button variant="danger" onClick={props.onDelete} aria-label={cockpit.format(_("Confirm removal of $0"), props.target)}>
939 { _("Delete") }
940 </Button>
941 <Button variant="link" className="btn-cancel" onClick={props.onCancel}>
942 { _("Cancel") }
943 </Button>
944 </ModalFooter>
945 </Modal>
946 );
947 }
948
949 export class Firewall extends React.Component {
950 static contextType = DialogsContext;
951
952 constructor() {
953 super();
954
955 this.state = {
956 firewall,
957 pendingTarget: null /* `null` for not pending */
958 };
959
960 this.onFirewallChanged = this.onFirewallChanged.bind(this);
961 this.openServicesDialog = this.openServicesDialog.bind(this);
962 this.openAddZoneDialog = this.openAddZoneDialog.bind(this);
963 this.onRemoveZone = this.onRemoveZone.bind(this);
964 this.onRemoveService = this.onRemoveService.bind(this);
965 this.onEditService = this.onEditService.bind(this);
966 }
967
968 onFirewallChanged() {
969 this.setState((prevState) => {
970 if (prevState.pendingTarget === firewall.enabled)
971 return { firewall, pendingTarget: null };
972
973 return { firewall };
974 });
975 }
976
977 onRemoveZone(zone) {
978 const Dialogs = this.context;
979 let body;
980 if (firewall.zones[zone].services.indexOf("cockpit") !== -1)
981 body = _("This zone contains the cockpit service. Make sure that this zone does not apply to your current web console connection.");
982 else
983 body = _("Removing the zone will remove all services within it.");
984 Dialogs.show(<DeleteConfirmationModal title={ cockpit.format(_("Remove zone $0"), zone) }
985 body={body}
986 target={zone}
987 onCancel={Dialogs.close}
988 onDelete={ () => {
989 firewall.deactiveateZone(zone);
990 Dialogs.close();
991 }} />
992 );
993 }
994
995 onRemoveService(zone, service) {
996 const Dialogs = this.context;
997 if (service === 'cockpit') {
998 const body = _("Removing the cockpit service might result in the web console becoming unreachable. Make sure that this zone does not apply to your current web console connection.");
999 Dialogs.show(<DeleteConfirmationModal title={ cockpit.format(_("Remove $0 service from $1 zone"), service, zone) }
1000 body={body}
1001 target={service}
1002 onCancel={Dialogs.close}
1003 onDelete={ () => {
1004 firewall.removeService(zone, service);
1005 Dialogs.close();
1006 }} />
1007 );
1008 } else {
1009 firewall.removeService(zone, service);
1010 }
1011 }
1012
1013 onRemovePort(zone, port, protocol) {
1014 firewall.removePort(zone, port, protocol);
1015 }
1016
1017 onEditService(zone, service) {
1018 const tcp_ports = [];
1019 const udp_ports = [];
1020 service.ports.forEach(port => {
1021 if (port.protocol === "tcp")
1022 tcp_ports.push(port.port);
1023 else
1024 udp_ports.push(port.port);
1025 });
1026
1027 const zone_name = zone.name ? zone.name : upperCaseFirstLetter(zone.id);
1028
1029 const Dialogs = this.context;
1030 Dialogs.show(<AddEditServicesModal zoneId={zone.id} zoneName={zone_name} custom_id={service.id}
1031 custom_tcp_ports={tcp_ports} custom_udp_ports={udp_ports} custom_description={service.description}
1032 custom_tcp_value={tcp_ports.join(", ")} custom_udp_value={udp_ports.join(", ")} />);
1033 }
1034
1035 componentDidMount() {
1036 firewall.addEventListener("changed", this.onFirewallChanged);
1037 }
1038
1039 componentWillUnmount() {
1040 firewall.removeEventListener("changed", this.onFirewallChanged);
1041 }
1042
1043 openServicesDialog(zoneId, zoneName) {
1044 const Dialogs = this.context;
1045 Dialogs.show(<AddEditServicesModal zoneId={zoneId} zoneName={zoneName} />);
1046 }
1047
1048 openAddZoneDialog() {
1049 const Dialogs = this.context;
1050 Dialogs.show(<ActivateZoneModal />);
1051 }
1052
1053 render() {
1054 function go_up(event) {
1055 cockpit.jump("/network", cockpit.transport.host);
1056 }
1057
1058 if (!this.state.firewall.installed) {
1059 return <EmptyStatePanel title={ _("Firewall is not available") }
1060 paragraph={ cockpit.format(_("Please install the $0 package"), "firewalld") }
1061 icon={ ExclamationCircleIcon }
1062 />;
1063 }
1064
1065 if (!this.state.firewall.ready)
1066 return <EmptyStatePanel loading />;
1067
1068 const addZoneAction = (
1069 <Button variant="primary" onClick={this.openAddZoneDialog} id="add-zone-button" aria-label={_("Add a new zone")}>
1070 {_("Add new zone")}
1071 </Button>
1072 );
1073
1074 const zones = [...this.state.firewall.activeZones].sort((z1, z2) =>
1075 z1 === firewall.defaultZone ? -1 : z2 === firewall.defaultZone ? 1 : 0
1076 ).map(id => this.state.firewall.zones[id]);
1077
1078 const enabled = this.state.firewall.enabled;
1079
1080 return (
1081 <Page className="pf-m-no-sidebar">
1082 <PageBreadcrumb hasBodyWrapper={false} stickyOnBreakpoint={{ default: "top" }}>
1083 <Breadcrumb>
1084 <BreadcrumbItem onClick={go_up} className="pf-v6-c-breadcrumb__link">{_("Networking")}</BreadcrumbItem>
1085 <BreadcrumbItem isActive>{_("Firewall")}</BreadcrumbItem>
1086 </Breadcrumb>
1087 </PageBreadcrumb>
1088 <PageSection hasBodyWrapper={false} id="firewall-heading" className="firewall-heading">
1089 <Flex alignItems={{ default: 'alignItemsCenter' }} justifyContent={{ default: 'justifyContentSpaceBetween' }}>
1090 <Flex alignItems={{ default: 'alignItemsCenter' }} id="firewall-heading-title-group">
1091 <Title headingLevel="h2" size="3xl">
1092 {_("Firewall")}
1093 </Title>
1094 <FirewallSwitch firewall={firewall} />
1095 <p>{_("Incoming requests are blocked by default. Outgoing requests are not blocked.")}</p>
1096 </Flex>
1097 { enabled && !firewall.readonly && <span className="btn-group">{addZoneAction}</span> }
1098 </Flex>
1099 </PageSection>
1100 <PageSection hasBodyWrapper={false} id="zones-listing">
1101 { enabled && <Stack hasGutter>
1102 {
1103 zones.map(z => <ZoneSection key={z.id}
1104 zone={z}
1105 openServicesDialog={this.openServicesDialog}
1106 readonly={this.state.firewall.readonly}
1107 onRemoveZone={this.onRemoveZone}
1108 onEditService={this.onEditService}
1109 onRemoveService={this.onRemoveService}
1110 onRemovePort={this.onRemovePort} />
1111 )
1112 }
1113 </Stack> }
1114 </PageSection>
1115 </Page>
1116 );
1117 }
1118 }
1119
1120 document.addEventListener("DOMContentLoaded", () => {
1121 document.title = cockpit.gettext(document.title);
1122 const root = createRoot(document.getElementById("firewall"));
1123 root.render(<WithDialogs><Firewall /></WithDialogs>);
1124 });