Debian Codegraph @

pkg/networkmanager/wireguard.jsx

raw
1 /*
2 * Copyright (C) 2023 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import React, { useContext, useEffect, useState } from 'react';
7 import cockpit from 'cockpit';
8 import { Button } from '@patternfly/react-core/dist/esm/components/Button/index.js';
9 import { ClipboardCopy } from '@patternfly/react-core/dist/esm/components/ClipboardCopy/index.js';
10 import { EmptyState, EmptyStateBody } from '@patternfly/react-core/dist/esm/components/EmptyState/index.js';
11 import { FormGroup, FormFieldGroup, FormFieldGroupHeader, FormHelperText } from '@patternfly/react-core/dist/esm/components/Form/index.js';
12 import { Flex, FlexItem } from "@patternfly/react-core/dist/esm/layouts/Flex/index.js";
13 import { Grid } from '@patternfly/react-core/dist/esm/layouts/Grid/index.js';
14 import { HelperText, HelperTextItem } from '@patternfly/react-core/dist/esm/components/HelperText/index';
15 import { InputGroup } from '@patternfly/react-core/dist/esm/components/InputGroup/index.js';
16 import { Popover } from '@patternfly/react-core/dist/esm/components/Popover/index.js';
17 import { Radio } from '@patternfly/react-core/dist/esm/components/Radio/index.js';
18 import { Content } from "@patternfly/react-core/dist/esm/components/Content/index.js";
19 import { TextInput } from '@patternfly/react-core/dist/esm/components/TextInput/index.js';
20 import { HelpIcon, TrashIcon } from '@patternfly/react-icons';
21
22 import { Name, NetworkModal, dialogSave } from "./dialogs-common";
23 import { ModelContext } from './model-context';
24 import { useDialogs } from 'dialogs.jsx';
25 import { validate_ip, validate_ipv4, validate_ipv6 } from './utils';
26
27 import './wireguard.scss';
28 import { useInit } from 'hooks';
29
30 const _ = cockpit.gettext;
31
32 function addressesToString(settings) {
33 const addresses = settings.ipv4.address_data.concat(settings.ipv6.address_data);
34 return addresses.map(addr => addr.address + "/" + addr.prefix).join(", ");
35 }
36
37 function stringToAddresses(str) {
38 const ipv4 = [];
39 const ipv6 = [];
40
41 str.split(/[\s,]+/).forEach(strAddress => {
42 const parts = strAddress.split("/");
43 if (parts.length > 2) {
44 throw new Error(_("Addresses are not formatted correctly"));
45 }
46
47 const [address, prefix] = parts;
48
49 if (validate_ipv6(address)) {
50 const defaultPrefix = "128";
51 ipv6.push({ address, prefix: prefix ?? defaultPrefix });
52 } else if (validate_ipv4(address)) {
53 const defaultPrefix = "32";
54 ipv4.push({ address, prefix: prefix ?? defaultPrefix });
55 } else {
56 throw cockpit.format(_("Invalid IP address '$0'"), address);
57 }
58 });
59
60 return [ipv4, ipv6];
61 }
62
63 export function WireGuardDialog({ settings, connection, dev }) {
64 const Dialogs = useDialogs();
65 const idPrefix = "network-wireguard-settings";
66 const model = useContext(ModelContext);
67
68 const [iface, setIface] = useState(settings.connection.interface_name);
69 const [isPrivKeyGenerated, setIsPrivKeyGenerated] = useState(true);
70 const [generatedPrivateKey, setGeneratedPrivateKey] = useState("");
71 const [pastedPrivateKey, setPastedPrivatedKey] = useState("");
72 const [publicKey, setPublicKey] = useState("");
73 const [listenPort, setListenPort] = useState(settings.wireguard.listen_port);
74 const [addresses, setAddresses] = useState(addressesToString(settings));
75 const [dialogError, setDialogError] = useState("");
76 const [peers, setPeers] = useState(settings.wireguard.peers.map(peer => ({ ...peer, allowedIps: peer.allowedIps?.join(",") ?? '' })));
77
78 // Additional check for `wg` after install_dialog for non-packagekit and el8 environments
79 useInit(async () => {
80 try {
81 await cockpit.script("command -v wg");
82 } catch (e) {
83 setDialogError(_("wireguard-tools package is not installed"));
84 return;
85 }
86
87 if (connection?.[" priv"].path) {
88 const objpath = connection[" priv"].path;
89 const [result] = await model.client.call(objpath, "org.freedesktop.NetworkManager.Settings.Connection", "GetSecrets", ["wireguard"]);
90 setGeneratedPrivateKey(result.wireguard["private-key"].v);
91 } else {
92 generatePrivateKey();
93 }
94 });
95
96 useEffect(() => {
97 const privateKey = isPrivKeyGenerated ? generatedPrivateKey : pastedPrivateKey;
98 if (privateKey === "") {
99 setPublicKey("");
100 return;
101 }
102
103 async function getPublicKey() {
104 try {
105 const key = await cockpit.spawn(["wg", "pubkey"], { err: 'message' }).input(privateKey.trim());
106 setPublicKey(key.trim());
107 } catch (e) {
108 console.error("Failed to call wg pubkey:", e.message);
109 setPublicKey('');
110 }
111 }
112
113 getPublicKey();
114 }, [isPrivKeyGenerated, generatedPrivateKey, pastedPrivateKey]);
115
116 async function generatePrivateKey() {
117 try {
118 const key = await cockpit.spawn(["wg", "genkey"]);
119 setGeneratedPrivateKey(key.trim());
120 } catch (e) {
121 setDialogError(e.message);
122 }
123 }
124
125 function validatePeer(peer, index) {
126 const endpoint = peer.endpoint?.trim();
127 if (endpoint) {
128 const split = endpoint.split(":");
129 // port should be after last ':'
130 const port = Number(split.at(-1));
131 const address = split.slice(0, -1).join(":").replace(/^\[|]$/g, '');
132
133 if (!validate_ip(address)) {
134 throw cockpit.format(_("Peer #$0 has invalid endpoint. It must be specified as host:port, e.g. 1.2.3.4:51820, [2001:db8::1]:51820 or example.com:51820"), index + 1);
135 }
136
137 if (!Number.isInteger(port) || port < 0 || port > 65535) {
138 throw cockpit.format(_("Peer #$0 has invalid endpoint port. Port must be a number."), index + 1);
139 }
140 }
141
142 return ({ ...peer, allowedIps: peer.allowedIps.trim().split(',') });
143 }
144
145 function onSubmit() {
146 const private_key = isPrivKeyGenerated ? generatedPrivateKey : pastedPrivateKey;
147
148 // Validate Addresses before submit
149 // Also validate listenPort as PF TextInput[type=number] accepts normal text as well on firefox
150 // See - https://github.com/patternfly/patternfly-react/issues/9391
151 let ipv4_addr;
152 let ipv6_addr;
153 let peersArr;
154 const listen_port = Number(listenPort);
155 try {
156 [ipv4_addr, ipv6_addr] = stringToAddresses(addresses);
157
158 if (isNaN(listen_port)) {
159 throw new Error(_("Listen port must be a number"));
160 }
161
162 peersArr = peers.map((peer, index) => {
163 return validatePeer(peer, index);
164 });
165 } catch (e) {
166 setDialogError(typeof e === 'string' ? e : e.message);
167 return;
168 }
169
170 function createAddressesObj(ipv4, ipv6) {
171 const addresses = {};
172
173 if (ipv4.length > 0) {
174 addresses.ipv4 = {
175 address_data: ipv4,
176 method: "manual",
177 dns: [],
178 dns_search: [],
179 };
180 } else {
181 addresses.ipv4 = { method: "disabled" };
182 }
183
184 if (ipv6.length > 0) {
185 addresses.ipv6 = {
186 address_data: ipv6,
187 // "stable-privacy" use hashing method for IPv6 autoconfiguration
188 addr_gen_mode: 1,
189 method: "manual",
190 dns: [],
191 dns_search: [],
192 };
193 } else {
194 addresses.ipv6 = { method: "disabled" };
195 }
196
197 return addresses;
198 }
199
200 function createSettingsObj() {
201 return {
202 ...settings,
203 connection: {
204 ...settings.connection,
205 id: `con-${iface}`,
206 interface_name: iface,
207 type: 'wireguard'
208 },
209 wireguard: {
210 private_key,
211 listen_port,
212 peers: peersArr,
213 },
214 ...createAddressesObj(ipv4_addr, ipv6_addr),
215 };
216 }
217
218 dialogSave({
219 connection,
220 dev,
221 model,
222 settings: createSettingsObj(),
223 onClose: Dialogs.close,
224 setDialogError
225 });
226 }
227
228 return (
229 <NetworkModal
230 title={!connection ? _("Add WireGuard VPN") : _("Edit WireGuard VPN")}
231 onSubmit={onSubmit}
232 dialogError={dialogError}
233 idPrefix={idPrefix}
234 submitDisabled={!iface || !addresses || !generatedPrivateKey}
235 isCreateDialog={!connection}
236 >
237 <Name idPrefix={idPrefix} iface={iface} setIface={setIface} />
238 <FormGroup label={_("Private key")} fieldId={idPrefix + '-private-key-input'} isInline hasNoPaddingTop>
239 <Radio label={_("Generated")} name="private-key" id={idPrefix + '-generated-key'} defaultChecked onChange={() => { setIsPrivKeyGenerated(true) }} />
240 <Radio label={_("Paste existing key")} name="private-key" id={idPrefix + '-paste-key'} onChange={() => { setIsPrivKeyGenerated(false) }} />
241
242 {isPrivKeyGenerated
243 ? <InputGroup className='pf-v6-u-pt-sm'>
244 <Flex className='pf-v6-u-w-100' spaceItems={{ default: 'spaceItemsSm' }}>
245 <FlexItem grow={{ default: 'grow' }}>
246 <ClipboardCopy isReadOnly id={idPrefix + '-private-key-input'} className='pf-v6-u-font-family-monospace pf-v6-u-w-100'>{generatedPrivateKey}</ClipboardCopy>
247 </FlexItem>
248 {connection && <FlexItem>
249 <Button variant='secondary' onClick={generatePrivateKey}>{_("Regenerate")}</Button>
250 </FlexItem>}
251 </Flex>
252 </InputGroup>
253 : <InputGroup className='pf-v6-u-pt-sm'>
254 <TextInput id={idPrefix + '-private-key-input'}
255 className='pf-v6-u-font-family-monospace'
256 value={pastedPrivateKey}
257 onChange={(_, val) => setPastedPrivatedKey(val)}
258 isDisabled={isPrivKeyGenerated}
259 />
260 </InputGroup>}
261 </FormGroup>
262 <FormGroup label={_("Public key")}>
263 {(isPrivKeyGenerated || publicKey)
264 ? <ClipboardCopy isReadOnly className='pf-v6-u-font-family-monospace' id={idPrefix + '-public-key'}>{publicKey}</ClipboardCopy>
265 : <Flex className='placeholder-text' alignItems={{ default: 'alignItemsCenter' }}><Content component="p">{_("Public key will be generated when a valid private key is entered")}</Content></Flex>}
266 </FormGroup>
267 <FormGroup label={_("Listen port")} fieldId={idPrefix + '-listen-port-input'}>
268 <Flex>
269 <TextInput id={idPrefix + '-listen-port-input'} className='wg-listen-port' value={listenPort} onChange={(_, val) => { setListenPort(val) }} />
270 {!parseInt(listenPort) && <FormHelperText>
271 <HelperText>
272 <HelperTextItem>{_("Will be set to \"Automatic\"")}</HelperTextItem>
273 </HelperText>
274 </FormHelperText>}
275 </Flex>
276 </FormGroup>
277 <FormGroup label={_("IP addresses")} fieldId={idPrefix + '-addresses-input'}>
278 <TextInput id={idPrefix + '-addresses-input'} value={addresses} onChange={(_, val) => { setAddresses(val) }} placeholder="Example, 10.0.0.1/24, 2001:db8:cafe::1/64" />
279 <FormHelperText>
280 <HelperText>
281 <HelperTextItem>{_("Multiple addresses can be specified using commas or spaces as delimiters.")}</HelperTextItem>
282 </HelperText>
283 </FormHelperText>
284 </FormGroup>
285 <FormFieldGroup
286 header={
287 <FormFieldGroupHeader
288 className='pf-v6-u-align-items-center'
289 titleText={{
290 text: (
291 <Flex className='pf-m-space-items-none'>
292 <FlexItem>
293 <Content component="p">{_("Peers")}</Content>
294 </FlexItem>
295 <FlexItem>
296 <Popover
297 bodyContent={
298 <p>{_("Peers are other machines that connect with this one. Public keys from other machines will be shared with each other.")}</p>
299 }
300 footerContent={
301 <p>{_("Endpoint acting as a \"server\" need to be specified as host:port, otherwise it can be left empty.")}</p>
302 }
303 >
304 <Button icon={<HelpIcon />} variant='plain' />
305 </Popover>
306 </FlexItem>
307 </Flex>
308 )
309 }}
310 actions={
311 <Button
312 variant='secondary'
313 onClick={() => setPeers(peers => [...peers, { publicKey: '', endpoint: '', allowedIps: '' }])}
314 >
315 {_("Add peer")}
316 </Button>
317 }
318 />
319 }
320 className='dynamic-form-group'
321 >
322 {(peers.length !== 0)
323 ? peers.map((peer, i) => (
324 <Grid key={i} hasGutter id={idPrefix + '-peer-' + i}>
325 <FormGroup className='pf-m-6-col-on-md' label={_("Public key")} fieldId={idPrefix + '-publickey-peer-' + i}>
326 <TextInput
327 value={peer.publicKey}
328 onChange={(_, val) => {
329 setPeers(peers => peers.map((peer, index) => i === index ? { ...peer, publicKey: val } : peer));
330 }}
331 id={idPrefix + '-publickey-peer-' + i}
332 />
333 </FormGroup>
334 <FormGroup className='pf-m-3-col-on-md' label={_("Endpoint")} fieldId={idPrefix + '-endpoint-peer-' + i}>
335 <TextInput
336 value={peer.endpoint}
337 onChange={(_, val) => {
338 setPeers(peers => peers.map((peer, index) => i === index ? { ...peer, endpoint: val } : peer));
339 }}
340 id={idPrefix + '-endpoint-peer-' + i}
341 />
342 </FormGroup>
343 <FormGroup className='pf-m-3-col-on-md' label={_("Allowed IPs")} fieldId={idPrefix + '-allowedips-peer-' + i}>
344 <TextInput
345 value={peer.allowedIps}
346 onChange={(_, val) => {
347 setPeers(peers => peers.map((peer, index) => i === index ? { ...peer, allowedIps: val } : peer));
348 }}
349 id={idPrefix + '-allowedips-peer-' + i}
350 />
351 </FormGroup>
352 <FormGroup className='pf-m-1-col-on-md remove-button-group'>
353 <Button icon={<TrashIcon />}
354 variant='plain'
355 id={idPrefix + '-btn-close-peer-' + i}
356 size='sm'
357 onClick={() => {
358 setPeers(peers => peers.filter((_, index) => i !== index));
359 }}
360 />
361 </FormGroup>
362 </Grid>
363 ))
364 : <EmptyState>
365 <EmptyStateBody>{_("No peers added.")}</EmptyStateBody>
366 </EmptyState>
367 }
368 </FormFieldGroup>
369 </NetworkModal>
370 );
371 }
372
373 export function getWireGuardGhostSettings({ newIfaceName }) {
374 return {
375 connection: {
376 id: `con-${newIfaceName}`,
377 interface_name: newIfaceName
378 },
379 wireguard: {
380 listen_port: 0,
381 private_key: "",
382 peers: []
383 },
384 ipv4: {
385 address_data: []
386 },
387 ipv6: {
388 address_data: []
389 },
390 };
391 }