Debian Codegraph @

pkg/shell/hosts_dialog.jsx

raw
1 /*
2 * Copyright (C) 2021 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7
8 import {
9 get_init_superuser_for_options, split_connection_string, generate_connection_string
10 } from "./machines/machines";
11 import * as credentials from "credentials";
12 import ssh_show_default_key_sh from "../lib/ssh-show-default-key.sh";
13 import ssh_add_key_sh from "../lib/ssh-add-key.sh";
14
15 import React from 'react';
16 import PropTypes from 'prop-types';
17
18 import { Alert } from "@patternfly/react-core/dist/esm/components/Alert/index.js";
19 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
20 import { Checkbox } from "@patternfly/react-core/dist/esm/components/Checkbox/index.js";
21 import { ClipboardCopy } from "@patternfly/react-core/dist/esm/components/ClipboardCopy/index.js";
22 import { ExpandableSection } from "@patternfly/react-core/dist/esm/components/ExpandableSection/index.js";
23 import { Form, FormGroup } from "@patternfly/react-core/dist/esm/components/Form/index.js";
24 import {
25 Modal, ModalBody, ModalFooter, ModalHeader
26 } from '@patternfly/react-core/dist/esm/components/Modal/index.js';
27 import { Popover } from "@patternfly/react-core/dist/esm/components/Popover/index.js";
28 import { Radio } from "@patternfly/react-core/dist/esm/components/Radio/index.js";
29 import { Stack } from "@patternfly/react-core/dist/esm/layouts/Stack/index.js";
30 import { TextInput } from "@patternfly/react-core/dist/esm/components/TextInput/index.js";
31 import { OutlinedQuestionCircleIcon, ExternalLinkAltIcon } from "@patternfly/react-icons";
32 import { HelperText, HelperTextItem } from "@patternfly/react-core/dist/esm/components/HelperText/index.js";
33 import { Content, ContentVariants } from "@patternfly/react-core/dist/esm/components/Content";
34
35 import { FormHelper } from "cockpit-components-form-helper";
36 import { ModalError } from "cockpit-components-inline-notification.jsx";
37 import { fmt_to_fragments } from "utils.js";
38
39 const _ = cockpit.gettext;
40
41 export const HostModalState = () => {
42 function set_props(props, callback) {
43 self.modal_properties = props;
44 self.modal_callback = callback;
45 self.dispatchEvent("changed");
46 }
47
48 function close_modal() {
49 set_props(null, null);
50 }
51
52 function show_modal(properties) {
53 return new Promise((resolve, reject) => {
54 set_props(properties, result => { resolve(result); return Promise.resolve() });
55 });
56 }
57
58 const self = {
59 state: null,
60
61 show_modal,
62 close_modal,
63 };
64
65 return cockpit.event_target(self);
66 };
67
68 /* Activate and jump to a newly added machine, identified by its
69 connection string.
70 */
71 function jump_to_new_connection_string(shell_state, connection_string) {
72 // Get the address of the machine from its connection string
73 const addr = split_connection_string(connection_string).address;
74 // Tell the Loader that now is the time to start monitoring the
75 // manifests.
76 shell_state.loader.connect(addr);
77 // Navigate to it.
78 shell_state.jump({ host: addr });
79 }
80
81 export async function add_host(state, shell_state) {
82 const connection_string = await state.show_modal({ });
83 if (connection_string)
84 jump_to_new_connection_string(shell_state, connection_string);
85 }
86
87 export async function edit_host(state, shell_state, machine) {
88 const { current_machine } = shell_state;
89 const connection_string = await state.show_modal({ address: machine.address });
90 if (connection_string) {
91 const addr = split_connection_string(connection_string).address;
92 if (machine == current_machine && addr != machine.address)
93 jump_to_new_connection_string(shell_state, connection_string);
94 }
95 }
96
97 export async function connect_host(state, shell_state, machine) {
98 // We need to trigger the loader for machines that already
99 // have state "connected". The state of a machine object
100 // survives a full shell reload, but the loader of course has
101 // no channel open for it yet. The bridge likely has the SSH
102 // connection still open, so the loader can do its job right
103 // away, like triggering the packages reload.
104 //
105 // "localhost" is a special case: we can always connect the
106 // loader without any extra credentials and we never want to
107 // show any dialogs for it.
108 //
109 if (machine.connection_string == "localhost" ||
110 machine.state == "connected" ||
111 machine.state == "connecting") {
112 shell_state.loader.connect(machine.address);
113 return machine.connection_string;
114 }
115
116 let connection_string = null;
117
118 if (machine.problem && codes[machine.problem]) {
119 // trouble shooting
120 connection_string = await state.show_modal({
121 address: machine.address,
122 template: codes[machine.problem],
123 });
124 } else if (!window.sessionStorage.getItem("connection-warning-shown")) {
125 // connect by launching into the "Connection warning" dialog.
126 connection_string = await state.show_modal({
127 address: machine.address,
128 template: "connect"
129 });
130 } else {
131 // Try to connect without any dialog
132 try {
133 await try2Connect(shell_state.machines, machine.connection_string);
134 connection_string = machine.connection_string;
135 } catch (err) {
136 // continue with troubleshooting in the dialog
137 connection_string = await state.show_modal({
138 address: machine.address,
139 template: codes[err.problem] || "change-port",
140 error_options: err,
141 });
142 }
143 }
144
145 if (connection_string) {
146 // make the rest of the shell aware that the machine is now connected
147 const parts = split_connection_string(connection_string);
148 shell_state.loader.connect(parts.address);
149 shell_state.update();
150 }
151
152 return connection_string;
153 }
154
155 export const codes = {
156 danger: "connect",
157 "no-cockpit": "not-supported",
158 "not-supported": "not-supported",
159 "protocol-error": "not-supported",
160 "authentication-not-supported": "change-auth",
161 "authentication-failed": "change-auth",
162 "no-forwarding": "change-auth",
163 "unknown-hostkey": "unknown-hostkey",
164 "invalid-hostkey": "invalid-hostkey",
165 "not-found": "add-machine",
166 "unknown-host": "unknown-host"
167 };
168
169 function full_address(machines_ins, address) {
170 const machine = machines_ins.lookup(address);
171 if (machine && machine.address !== "localhost")
172 return machine.connection_string;
173
174 return address;
175 }
176
177 function is_method_supported(methods, method) {
178 const result = methods[method];
179 return result ? result !== "no-server-support" : false;
180 }
181
182 function prevent_default(callback) {
183 return event => {
184 callback();
185 event.preventDefault();
186 return false;
187 };
188 }
189
190 class NotSupported extends React.Component {
191 render() {
192 return (
193 <Modal id="hosts_setup_server_dialog" isOpen
194 position="top" variant="medium"
195 onClose={this.props.onClose}
196 >
197 <ModalHeader title={_("Cockpit is not installed")} />
198 <ModalBody>
199 <Stack hasGutter>
200 { this.props.dialogError && <ModalError dialogError={this.props.dialogError} />}
201 <p>{cockpit.format(_("A compatible version of Cockpit is not installed on $0."), this.props.full_address)}</p>
202 </Stack>
203 </ModalBody>
204 <ModalFooter>
205 <Button variant="secondary" className="btn-cancel" onClick={this.props.onClose}>
206 { _("Close") }
207 </Button>
208 </ModalFooter>
209 </Modal>
210 );
211 }
212 }
213
214 class Connect extends React.Component {
215 constructor(props) {
216 super(props);
217
218 this.state = {
219 inProgress: false,
220 };
221 }
222
223 onConnect() {
224 window.sessionStorage.setItem("connection-warning-shown", true);
225 this.setState({ inProgress: true });
226 this.props.run(try2Connect(this.props.machines_ins, this.props.full_address), ex => {
227 let keep_message = false;
228 if (ex.problem === "no-host") {
229 let host_id_port = this.props.full_address;
230 let port = "22";
231 const port_index = host_id_port.lastIndexOf(":");
232 if (port_index === -1) {
233 host_id_port = this.props.full_address + ":22";
234 } else {
235 port = host_id_port.substring(port_index + 1);
236 }
237
238 ex.message = cockpit.format(_("Unable to contact the given host $0. Make sure it has ssh running on port $1, or specify another port in the address."), host_id_port, port);
239 ex.problem = "not-found";
240 keep_message = true;
241 }
242 this.setState({ inProgress: false });
243 this.props.setError(ex, keep_message);
244 });
245 }
246
247 render() {
248 return (
249 <Modal id="hosts_connect_server_dialog" isOpen
250 position="top" variant="small"
251 onClose={this.props.onClose}
252 >
253 <ModalHeader title={fmt_to_fragments(_("Connect to $0?"), <b className="ct-heading-font-weight">{this.props.host}</b>)}
254 titleIconVariant="warning"
255 />
256 <ModalBody>
257 <Content component={ContentVariants.p}>
258 {_("Connected hosts can fully control each other. This includes running programs that could harm your system or steal data. Only connect to trusted machines.")}
259 </Content>
260 <Content component={ContentVariants.p}>
261 <a href="https://docs.cockpit-project.org/cockpit-guide/latest/guide/multi-host.html" target="blank" rel="noopener noreferrer">
262 <ExternalLinkAltIcon /> {_("Read more")}
263 </a>
264 </Content>
265 </ModalBody>
266 <ModalFooter>
267 <HelperText>
268 <HelperTextItem>{_("You will be reminded once per session.")}</HelperTextItem>
269 </HelperText>
270 <Button variant="warning" isLoading={this.state.inProgress}
271 onClick={() => this.onConnect()}>
272 {_("Connect")}
273 </Button>
274 <Button variant="link" className="btn-cancel" onClick={this.props.onClose}>
275 { _("Cancel") }
276 </Button>
277 </ModalFooter>
278 </Modal>
279 );
280 }
281 }
282
283 class AddMachine extends React.Component {
284 constructor(props) {
285 super(props);
286
287 let address_parts = null;
288 if (this.props.full_address)
289 address_parts = split_connection_string(this.props.full_address);
290
291 let host_address = "";
292 let host_user = "";
293 if (address_parts) {
294 host_address = address_parts.address;
295 if (address_parts.port)
296 host_address += ":" + address_parts.port;
297 host_user = address_parts.user;
298 }
299
300 let color = props.machines_ins.unused_color();
301 let old_machine = null;
302 if (props.old_address)
303 old_machine = props.machines_ins.lookup(props.old_address);
304 if (old_machine)
305 color = this.rgb2Hex(old_machine.color);
306 if (old_machine && !old_machine.visible)
307 old_machine = null;
308
309 this.state = {
310 user: host_user || "",
311 address: host_address || "",
312 color,
313 addressError: "",
314 inProgress: false,
315 old_machine,
316 userChanged: false,
317 };
318
319 this.onAddressChange = this.onAddressChange.bind(this);
320 this.onAddHost = this.onAddHost.bind(this);
321 }
322
323 rgb2Hex(c) {
324 function toHex(d) {
325 return ("0" + (parseInt(d, 10).toString(16)))
326 .slice(-2);
327 }
328
329 if (c[0] === "#")
330 return c;
331
332 const colors = /rgb\((\d*), (\d*), (\d*)\)/.exec(c);
333 return "#" + toHex(colors[1]) + toHex(colors[2]) + toHex(colors[3]);
334 }
335
336 onAddressChange() {
337 let error = "";
338 if (this.state.address.search(/\s+/) !== -1)
339 error = _("The IP address or hostname cannot contain whitespace.");
340 else {
341 const machine = this.props.machines_ins.lookup(this.state.address);
342 const machine_address = machine ? full_address(this.props.machines_ins, machine.address) : undefined;
343 if (machine && machine.on_disk && machine_address != this.props.old_address) {
344 if (machine.visible)
345 error = _("This machine has already been added.");
346 else if (!this.state.userChanged)
347 this.setState({ user: machine.user, color: this.rgb2Hex(machine.color) });
348 } else if (this.state.old_machine && !machine && !this.state.userChanged) { // When editing host by changing its address generate new color
349 this.setState((_, prevProps) => ({ color: prevProps.machines_ins.unused_color(), userChanged: true }));
350 }
351 }
352
353 this.setState({ addressError: error });
354
355 return error;
356 }
357
358 onAddHost() {
359 const parts = split_connection_string(this.state.address);
360 // user in "User name:" field wins over user in connection string
361 const address = generate_connection_string(this.state.user || parts.user, parts.port, parts.address);
362
363 if (this.onAddressChange())
364 return;
365
366 this.props.setAddress(address);
367
368 if (this.state.old_machine && address === this.state.old_machine.connection_string) {
369 this.props.setError(null);
370 this.setState({ inProgress: true });
371 this.props.run(this.props.machines_ins.change(this.state.old_machine.key, { color: this.state.color }))
372 .catch(ex => {
373 this.setState({ inProgress: false });
374 throw ex;
375 });
376 return;
377 }
378
379 this.props.setError(null);
380 this.setState({ inProgress: true });
381
382 this.props.setGoal(() => {
383 const parts = split_connection_string(this.state.address);
384 // user in "User name:" field wins over user in connection string
385 const address = generate_connection_string(this.state.user || parts.user, parts.port, parts.address);
386
387 return new Promise((resolve, reject) => {
388 this.props.machines_ins.add(address, this.state.color)
389 .then(() => {
390 // When changing address of machine, hide the old one
391 if (this.state.old_machine && this.state.old_machine != this.props.machines_ins.lookup(address)) {
392 this.props.machines_ins.change(this.state.old_machine.key, { visible: false })
393 .then(resolve);
394 } else {
395 resolve();
396 }
397 })
398 .catch(ex => {
399 ex.message = cockpit.format(_("Failed to add machine: $0"), cockpit.message(ex));
400 this.setState({ dialogError: cockpit.message(ex), inProgress: false });
401 reject(ex);
402 });
403 });
404 });
405
406 if (!window.sessionStorage.getItem("connection-warning-shown")) {
407 this.props.setError({ problem: "danger", command: "close" });
408 } else {
409 this.props.run(try2Connect(this.props.machines_ins, address), ex => {
410 if (ex.problem === "no-host") {
411 let host_id_port = address;
412 let port = "22";
413 const port_index = host_id_port.lastIndexOf(":");
414 if (port_index === -1) {
415 host_id_port = address + ":22";
416 } else {
417 port = host_id_port.substring(port_index + 1);
418 }
419
420 ex.message = cockpit.format(_("Unable to contact the given host $0. Make sure it has ssh running on port $1, or specify another port in the address."), host_id_port, port);
421 ex.problem = "not-found";
422 }
423 this.setState({ inProgress: false });
424 this.props.setError(ex);
425 });
426 }
427 }
428
429 render() {
430 const invisible = this.props.machines_ins.addresses.filter(addr => {
431 const m = this.props.machines_ins.lookup(addr);
432 return !m || !m.visible;
433 });
434
435 const callback = this.onAddHost;
436 const title = this.state.old_machine ? _("Edit host") : _("Add new host");
437 const submitText = this.state.old_machine ? _("Set") : _("Add");
438
439 const body = <Form isHorizontal onSubmit={prevent_default(callback)}>
440 <FormGroup label={_("Host")}>
441 <TextInput id="add-machine-address" onChange={(_event, address) => this.setState({ address })}
442 validated={this.state.addressError ? "error" : "default"} onBlur={this.onAddressChange}
443 isDisabled={this.props.old_address === "localhost"} list="options" value={this.state.address} />
444 <datalist id="options">
445 {invisible.map(a => <option key={a} value={a} />)}
446 </datalist>
447 <FormHelper helperTextInvalid={this.state.addressError} helperText={_("Can be a hostname, IP address, alias name, or ssh:// URI")} />
448 </FormGroup>
449 <FormGroup label={_("User name")}>
450 <TextInput id="add-machine-user" onChange={(_event, value) => this.setState({ user: value, userChanged: true })}
451 isDisabled={this.props.old_address === "localhost"} value={this.state.user} />
452 <FormHelper helperText={_("When empty, connect with the current user")} />
453 </FormGroup>
454 <FormGroup label={_("Color")}>
455 <input type="color" value={this.state.color} onChange={(e) => this.setState({ color: e.target.value }) } />
456 </FormGroup>
457 </Form>;
458
459 return (
460 <Modal id="hosts_setup_server_dialog" isOpen
461 position="top" variant="medium"
462 onClose={this.props.onClose}
463 >
464 <ModalHeader title={title} />
465 <ModalBody>
466 <Stack hasGutter>
467 { this.props.dialogError && <ModalError dialogError={this.props.dialogError} />}
468 {body}
469 </Stack>
470 </ModalBody>
471 <ModalFooter>
472 <Button variant="primary" onClick={callback} isLoading={this.state.inProgress}
473 isDisabled={this.state.address === "" || this.state.addressError !== "" || this.state.inProgress}>
474 { submitText }
475 </Button>
476 <Button variant="link" className="btn-cancel" onClick={this.props.onClose}>
477 { _("Cancel") }
478 </Button>
479 </ModalFooter>
480 </Modal>
481 );
482 }
483 }
484
485 class MachinePort extends React.Component {
486 constructor(props) {
487 super(props);
488
489 const machine = props.machines_ins.lookup(props.full_address);
490 if (!machine) {
491 props.onClose();
492 return;
493 }
494
495 this.state = {
496 port: machine.port,
497 };
498
499 this.onChangePort = this.onChangePort.bind(this);
500 }
501
502 onChangePort() {
503 const promise = new Promise((resolve, reject) => {
504 const parts = split_connection_string(this.props.full_address);
505 parts.port = this.state.port;
506 const address = generate_connection_string(parts.user, parts.port, parts.address);
507 const self = this;
508
509 function update_host(ex) {
510 self.props.setAddress(address);
511 self.props.machines_ins.change(parts.address, { port: parts.port })
512 .then(() => {
513 // We failed before so try to connect again now that the machine is saved
514 if (ex) {
515 try2Connect(self.props.machines_ins, address)
516 .then(self.props.complete)
517 .catch(reject);
518 } else {
519 resolve();
520 }
521 })
522 .catch(ex => reject(cockpit.format(_("Failed to edit machine: $0"), cockpit.message(ex))));
523 }
524
525 try2Connect(this.props.machines_ins, address)
526 .then(update_host)
527 .catch(ex => {
528 // any other error means progress, so save
529 if (ex.problem !== 'no-host')
530 update_host(ex);
531 else
532 reject(ex);
533 });
534 });
535
536 this.props.run(promise);
537 }
538
539 render() {
540 const callback = this.onChangePort;
541 const title = cockpit.format(_("Could not contact $0"), this.props.full_address);
542 const submitText = _("Update");
543
544 const body = <>
545 <p>
546 <span>{cockpit.format(_("Unable to contact $0."), this.props.full_address)}</span>
547 <span>{_("Is sshd running on a different port?")}</span>
548 </p>
549 <Form isHorizontal onSubmit={prevent_default(callback)}>
550 <FormGroup label={_("Port")}>
551 <TextInput id="edit-machine-port" onChange={(_event, value) => this.setState({ port: value })} />
552 </FormGroup>
553 </Form>
554 </>;
555
556 return (
557 <Modal id="hosts_setup_server_dialog" isOpen
558 position="top" variant="medium"
559 onClose={this.props.onClose}
560 >
561 <ModalHeader title={title} />
562 <ModalBody>
563 <Stack hasGutter>
564 { this.props.dialogError && <ModalError dialogError={this.props.dialogError} />}
565 {body}
566 </Stack>
567 </ModalBody>
568 <ModalFooter>
569 <Button variant="primary" onClick={callback} isLoading={this.state.inProgress}
570 isDisabled={this.state.inProgress}>
571 { submitText }
572 </Button>
573 <Button variant="link" className="btn-cancel" onClick={this.props.onClose}>
574 { _("Cancel") }
575 </Button>
576 </ModalFooter>
577 </Modal>
578 );
579 }
580 }
581
582 class HostKey extends React.Component {
583 constructor(props) {
584 super(props);
585
586 this.state = {
587 inProgress: false,
588 verifyExpanded: false,
589 error_options: props.error_options,
590 };
591
592 this.onAddKey = this.onAddKey.bind(this);
593 }
594
595 componentDidMount() {
596 if (!this.props.error_options || !this.props.error_options["host-key"]) {
597 const options = {};
598 let match_problem = this.props.template;
599 if (this.props.template == "unknown-host") {
600 options.session = "private";
601 match_problem = "unknown-hostkey";
602 }
603
604 try2Connect(this.props.machines_ins, this.props.full_address, options)
605 .then(this.props.complete)
606 .catch(ex => {
607 if (ex.problem !== match_problem) {
608 this.props.setError(ex);
609 } else {
610 this.setState({ error_options: ex });
611 }
612 });
613 }
614 }
615
616 onAddKey() {
617 this.setState({ inProgress: true });
618
619 const key = this.state.error_options["host-key"];
620 const machine = this.props.machines_ins.lookup(this.props.full_address);
621 let q;
622 if (!machine || machine.on_disk) {
623 q = this.props.machines_ins.add_key(key);
624 } else {
625 // When machine isn't saved to disk don't save the key either
626 q = this.props.machines_ins.change(this.props.full_address, { host_key: key });
627 }
628
629 this.props.run(q.then(() => {
630 return try2Connect(this.props.machines_ins, this.props.full_address, {})
631 .catch(ex => {
632 if ((ex.problem == "invalid-hostkey" || ex.problem == "unknown-hostkey") && machine && !machine.on_disk)
633 this.props.machines_ins.change(this.props.full_address, { host_key: null });
634 else {
635 this.setState({ inProgress: false });
636 throw ex;
637 }
638 });
639 }));
640 }
641
642 render() {
643 let key_type = "";
644 let fp = "";
645 if (this.state.error_options && this.state.error_options["host-key"]) {
646 key_type = this.state.error_options["host-key"].split(" ")[1];
647 fp = this.state.error_options["host-fingerprint"];
648 }
649
650 const scan_cmd = `ssh-keyscan -t ${key_type} localhost | ssh-keygen -lf -`;
651
652 const callback = this.onAddKey;
653 const title = cockpit.format(this.props.template === "invalid-hostkey" ? _("$0 key changed") : _("New host: $0"),
654 this.props.host);
655 const submitText = _("Trust and add host");
656 let unknown = false;
657 let body = null;
658 if (!key_type) {
659 unknown = true;
660 } else if (this.props.template === "invalid-hostkey") {
661 body = <>
662 <Alert variant='danger' isInline title={_("Changed keys are often the result of an operating system reinstallation. However, an unexpected change may indicate a third-party attempt to intercept your connection.")} />
663 <p>{_("To ensure that your connection is not intercepted by a malicious third-party, please verify the host key fingerprint:")}</p>
664 <ClipboardCopy isReadOnly hoverTip={_("Copy")} clickTip={_("Copied")} className="hostkey-fingerprint pf-v6-u-font-family-monospace">{fp}</ClipboardCopy>
665 <p className="hostkey-type">({key_type})</p>
666 <p>{cockpit.format(_("To verify a fingerprint, run the following on $0 while physically sitting at the machine or through a trusted network:"), this.props.host)}</p>
667 <ClipboardCopy isReadOnly hoverTip={_("Copy")} clickTip={_("Copied")} className="hostkey-verify-help-cmds pf-v6-u-font-family-monospace">{scan_cmd}</ClipboardCopy>
668 <p>{_("The resulting fingerprint is fine to share via public methods, including email.")}</p>
669 <p>{_("If the fingerprint matches, click 'Trust and add host'. Otherwise, do not connect and contact your administrator.")}</p>
670 </>;
671 } else {
672 const fingerprint_help = <Popover bodyContent={
673 _("The resulting fingerprint is fine to share via public methods, including email. If you are asking someone else to do the verification for you, they can send the results using any method.")}>
674 <OutlinedQuestionCircleIcon />
675 </Popover>;
676 body = <>
677 <p>{cockpit.format(_("You are connecting to $0 for the first time."), this.props.host)}</p>
678 <ExpandableSection toggleText={ _("Verify fingerprint") }
679 isExpanded={this.state.verifyExpanded}
680 onToggle={(_ev, verifyExpanded) => this.setState({ verifyExpanded }) }>
681 <div>{_("Run this command over a trusted network or physically on the remote machine:")}</div>
682 <ClipboardCopy isReadOnly hoverTip={_("Copy")} clickTip={_("Copied")} className="hostkey-verify-help hostkey-verify-help-cmds pf-v6-u-font-family-monospace">{scan_cmd}</ClipboardCopy>
683 <div>{_("The fingerprint should match:")} {fingerprint_help}</div>
684 <ClipboardCopy isReadOnly hoverTip={_("Copy")} clickTip={_("Copied")} className="hostkey-verify-help hostkey-fingerprint pf-v6-u-font-family-monospace">{fp}</ClipboardCopy>
685 </ExpandableSection>
686 <Alert variant='warning' isInline isPlain title={_("Malicious pages on a remote machine may affect other connected hosts")} />
687 </>;
688 }
689
690 return (
691 <Modal id="hosts_setup_server_dialog" isOpen
692 position="top" variant="medium"
693 onClose={this.props.onClose}
694 >
695 <ModalHeader title={title} />
696 <ModalBody>
697 <Stack hasGutter>
698 { this.props.dialogError && <ModalError dialogError={this.props.dialogError} />}
699 {body}
700 </Stack>
701 </ModalBody>
702 <ModalFooter>
703 { unknown ||
704 <Button variant="primary" onClick={callback} isLoading={this.state.inProgress}
705 isDisabled={this.state.inProgress}>
706 { submitText }
707 </Button>
708 }
709 <Button variant="link" className="btn-cancel" onClick={this.props.onClose}>
710 { _("Cancel") }
711 </Button>
712 </ModalFooter>
713 </Modal>
714 );
715 }
716 }
717
718 class ChangeAuth extends React.Component {
719 constructor(props) {
720 super(props);
721
722 this.state = {
723 auth: "password",
724 auto_login: false,
725 custom_password: "",
726 custom_password_error: "",
727 locked_identity_password: "",
728 locked_identity_password_error: "",
729 login_setup_new_key_password: "",
730 login_setup_new_key_password_error: "",
731 login_setup_new_key_password2: "",
732 login_setup_new_key_password2_error: "",
733 user: "",
734 default_ssh_key: null,
735 identity_path: null,
736 inProgress: true, // componentDidMount changes to false once loaded
737 };
738
739 this.keys = null;
740 if (credentials)
741 this.keys = credentials.keys_instance();
742
743 this.getSupports = this.getSupports.bind(this);
744 this.updateIdentity = this.updateIdentity.bind(this);
745 this.login = this.login.bind(this);
746 this.maybe_create_key = this.maybe_create_key.bind(this);
747 this.authorize_key = this.authorize_key.bind(this);
748 this.maybe_unlock_key = this.maybe_unlock_key.bind(this);
749 }
750
751 updateIdentity() {
752 let identity_path = null;
753 if (this.props.error_options && this.props.error_options.error && this.props.error_options.error.startsWith("locked identity"))
754 identity_path = this.props.error_options.error.split(": ")[1];
755
756 const default_ssh_key = this.state.default_ssh_key;
757 if (default_ssh_key && default_ssh_key.encrypted)
758 default_ssh_key.unaligned_passphrase = identity_path && identity_path === default_ssh_key.name;
759
760 this.setState({ identity_path, default_ssh_key });
761 }
762
763 componentDidMount() {
764 cockpit.user()
765 .then(user =>
766 cockpit.script(ssh_show_default_key_sh, [], { })
767 .then(data => {
768 let default_ssh_key = null;
769 const info = data.split("\n");
770 if (info[0])
771 default_ssh_key = { name: info[0], exists: true, encrypted: info[1] === "encrypted" };
772 else
773 default_ssh_key = { name: user.home + "/.ssh/id_rsa", type: "rsa", exists: false };
774
775 return this.setState({ inProgress: false, default_ssh_key, user }, this.updateIdentity);
776 })
777 )
778 .catch(ex => { this.setState({ inProgress: false }); this.props.setError(ex) });
779
780 if (!this.props.error_options || this.props.error_options["auth-method-results"] === null) {
781 try2Connect(this.props.machines_ins, this.props.full_address)
782 .then(this.props.complete)
783 .catch(ex => {
784 this.setState({ inProgress: false });
785 this.props.setError(ex);
786 });
787 }
788 }
789
790 componentWillUnmount() {
791 if (this.keys)
792 this.keys.close();
793 this.keys = null;
794 }
795
796 componentDidUpdate(prevProps) {
797 if (prevProps.error_options !== this.props.error_options)
798 this.updateIdentity();
799 }
800
801 getSupports() {
802 let methods = null;
803 let available = null;
804
805 let offer_login_password = false;
806 let offer_key_password = false;
807
808 if (this.props.error_options) {
809 available = {};
810
811 methods = this.props.error_options["auth-method-results"];
812 if (methods) {
813 for (const method in methods) {
814 if (is_method_supported(methods, method)) {
815 available[method] = true;
816 }
817 }
818 }
819
820 offer_login_password = !!available.password;
821 offer_key_password = this.state.identity_path !== null;
822 } else {
823 offer_login_password = true;
824 offer_key_password = false;
825 }
826
827 return {
828 offer_login_password,
829 offer_key_password,
830 };
831 }
832
833 maybe_create_key(passphrase) {
834 if (!this.state.default_ssh_key.exists)
835 return this.keys.create(this.state.default_ssh_key.name, this.state.default_ssh_key.type, passphrase);
836 else
837 return Promise.resolve();
838 }
839
840 authorize_key(host) {
841 return this.keys.get_pubkey(this.state.default_ssh_key.name)
842 .then(data => cockpit.script(ssh_add_key_sh, [data.trim()], { host, err: "message" }));
843 }
844
845 maybe_unlock_key() {
846 const { offer_login_password, offer_key_password } = this.getSupports();
847 const both = offer_login_password && offer_key_password;
848
849 if ((both && this.state.auth === "key") || (!both && offer_key_password))
850 return this.keys.load(this.state.identity_path, this.state.locked_identity_password);
851 else
852 return Promise.resolve();
853 }
854
855 login() {
856 const options = {};
857 const user = split_connection_string(this.props.full_address).user || "";
858 const do_key_password_change = this.state.auto_login && this.state.default_ssh_key.unaligned_passphrase;
859
860 let custom_password_error = "";
861 let locked_identity_password_error = "";
862 let login_setup_new_key_password_error = "";
863 let login_setup_new_key_password2_error = "";
864
865 const { offer_login_password, offer_key_password } = this.getSupports();
866 const both = offer_login_password && offer_key_password;
867
868 if ((both && this.state.auth === "password") || (!both && offer_login_password)) {
869 if (!this.state.custom_password)
870 custom_password_error = _("The password can not be empty");
871
872 options.password = this.state.custom_password;
873 options.session = 'shared';
874 if (!user) {
875 /* we don't want to save the default user for everyone
876 * so we pass current user as an option, but make sure the
877 * session isn't private
878 */
879 if (this.state.user && this.state.user.name)
880 options.user = this.state.user.name;
881 options["temp-session"] = false; /* Compatibility option */
882 }
883 }
884
885 if ((offer_key_password && !(both && this.state.auth === "password")) && !this.state.locked_identity_password)
886 locked_identity_password_error = _("The key password can not be empty");
887
888 if (this.state.auto_login && !do_key_password_change && this.state.login_setup_new_key_password !== this.state.login_setup_new_key_password2)
889 login_setup_new_key_password2_error = _("The key passwords do not match");
890
891 if (do_key_password_change && !this.state.login_setup_new_key_password)
892 login_setup_new_key_password_error = _("The new key password can not be empty");
893
894 if (do_key_password_change && this.state.login_setup_new_key_password !== this.state.login_setup_new_key_password2)
895 login_setup_new_key_password2_error = _("The key passwords do not match");
896
897 if (custom_password_error || locked_identity_password_error || login_setup_new_key_password_error || login_setup_new_key_password2_error) {
898 this.setState({
899 custom_password_error,
900 locked_identity_password_error,
901 login_setup_new_key_password_error,
902 login_setup_new_key_password2_error,
903 });
904 return;
905 }
906
907 this.setState({ inProgress: true });
908 const machine = this.props.machines_ins.lookup(this.props.full_address);
909
910 this.props.run(this.maybe_unlock_key()
911 .then(() => {
912 return try2Connect(this.props.machines_ins, this.props.full_address, options)
913 .then(() => {
914 if (machine)
915 return this.props.machines_ins.change(machine.address, { user });
916 else
917 return Promise.resolve();
918 })
919 .then(() => {
920 if (do_key_password_change)
921 return this.keys.change(this.state.default_ssh_key.name, this.state.locked_identity_password, this.state.login_setup_new_key_password);
922 else if (this.state.auto_login)
923 return this.maybe_create_key(this.state.login_setup_new_key_password)
924 .then(() => this.authorize_key(this.props.full_address));
925 else
926 return Promise.resolve();
927 });
928 })
929 .catch(ex => {
930 this.setState({ inProgress: false });
931 throw ex;
932 }));
933 }
934
935 render() {
936 const { offer_login_password, offer_key_password } = this.getSupports();
937 const both = offer_login_password && offer_key_password;
938
939 let offer_key_setup = true;
940 let show_password_advice = true;
941 if (!this.state.default_ssh_key)
942 offer_key_setup = false;
943 else if (this.state.default_ssh_key.unaligned_passphrase)
944 offer_key_setup = (both && this.state.auth === "key") || (!both && offer_key_password);
945 else if (this.state.identity_path) {
946 // This is a locked, non-default identity that will never
947 // be loaded into the agent, so there is no point in
948 // offering to change the passphrase.
949 show_password_advice = false;
950 offer_key_setup = false;
951 }
952
953 const callback = this.login;
954 const title = cockpit.format(_("Log in to $0"), this.props.full_address);
955 const submitText = _("Log in");
956 let statement = "";
957
958 if (!offer_login_password && !offer_key_password)
959 statement = <p>{cockpit.format(_("Unable to log in to $0. The host does not accept password login or any of your SSH keys."), this.props.full_address)}</p>;
960 else if (offer_login_password && !offer_key_password)
961 statement = <p>{cockpit.format(_("Unable to log in to $0 using SSH key authentication. Please provide the password. You may want to set up your SSH keys for automatic login."), this.props.full_address)}</p>;
962 else if (offer_key_password && !offer_login_password)
963 statement = <>
964 <p>{cockpit.format(_("The SSH key for logging in to $0 is protected by a password, and the host does not allow logging in with a password. Please provide the password of the key at $1."), this.props.full_address, this.state.identity_path)}</p>
965 {show_password_advice && <span className="password-change-advice">{_("You may want to change the password of the key for automatic login.")}</span>}
966 </>;
967 else if (both)
968 statement = <>
969 <p>{cockpit.format(_("The SSH key for logging in to $0 is protected. You can log in with either your login password or by providing the password of the key at $1."), this.props.full_address, this.state.identity_path)}</p>
970 {show_password_advice && <span className="password-change-advice">{_("You may want to change the password of the key for automatic login.")}</span>}
971 </>;
972
973 let auto_text = null;
974 let auto_details = null;
975 if (this.state.default_ssh_key) {
976 const lmach = this.props.machines_ins.lookup(null);
977 const key = this.state.default_ssh_key.name;
978 const luser = this.state.user.name;
979 const lhost = lmach ? lmach.label || lmach.address : "localhost";
980 const afile = "~/.ssh/authorized_keys";
981 const ruser = split_connection_string(this.props.full_address).user || this.state.user.name;
982 const rhost = split_connection_string(this.props.full_address).address;
983 if (!this.state.default_ssh_key.exists) {
984 auto_text = _("Create a new SSH key and authorize it");
985 auto_details = <>
986 <p>{cockpit.format(_("A new SSH key at $0 will be created for $1 on $2 and it will be added to the $3 file of $4 on $5."), key, luser, lhost, afile, ruser, rhost)}</p>
987 <FormGroup label={_("Key password")}>
988 <TextInput id="login-setup-new-key-password" onChange={(_event, value) => this.setState({ login_setup_new_key_password: value })}
989 type="password" value={this.state.login_setup_new_key_password} validated={this.state.login_setup_new_key_password_error ? "error" : "default"} />
990 <FormHelper helperTextInvalid={this.state.login_setup_new_key_password_error} />
991 </FormGroup>
992 <FormGroup label={_("Confirm key password")}>
993 <TextInput id="login-setup-new-key-password2" onChange={(_event, value) => this.setState({ login_setup_new_key_password2: value })}
994 type="password" value={this.state.login_setup_new_key_password2} validated={this.state.login_setup_new_key_password2_error ? "error" : "default"} />
995 <FormHelper helperTextInvalid={this.state.login_setup_new_key_password2_error} />
996 </FormGroup>
997 <p>{cockpit.format(_("In order to allow log in to $0 as $1 without password in the future, use the login password of $2 on $3 as the key password, or leave the key password blank."), rhost, ruser, luser, lhost)}</p>
998 </>;
999 } else if (this.state.default_ssh_key.unaligned_passphrase) {
1000 auto_text = cockpit.format(_("Change the password of $0"), key);
1001 auto_details = <>
1002 <p>{cockpit.format(_("By changing the password of the SSH key $0 to the login password of $1 on $2, the key will be automatically made available and you can log in to $3 without password in the future."), key, luser, lhost, afile, rhost)}</p>
1003 <FormGroup label={_("New key password")}>
1004 <TextInput id="login-setup-new-key-password" onChange={(_event, value) => this.setState({ login_setup_new_key_password: value })}
1005 type="password" value={this.state.login_setup_new_key_password} validated={this.state.login_setup_new_key_password_error ? "error" : "default"} />
1006 <FormHelper helperTextInvalid={this.state.login_setup_new_key_password_error} />
1007 </FormGroup>
1008 <FormGroup label={_("Confirm new key password")} validated={this.state.login_setup_new_key_password2_error ? "error" : "default"}>
1009 <TextInput id="login-setup-new-key-password2" onChange={(_event, value) => this.setState({ login_setup_new_key_password2: value })}
1010 type="password" value={this.state.login_setup_new_key_password2} validated={this.state.login_setup_new_key_password2_error ? "error" : "default"} />
1011
1012 <FormHelper helperTextInvalid={this.state.login_setup_new_key_password2_error} />
1013 </FormGroup>
1014 <p>{cockpit.format(_("In order to allow log in to $0 as $1 without password in the future, use the login password of $2 on $3 as the key password, or leave the key password blank."), rhost, ruser, luser, lhost)}</p>
1015 </>;
1016 } else {
1017 auto_text = _("Authorize SSH key");
1018 auto_details = <>
1019 <p>{cockpit.format(_("The SSH key $0 of $1 on $2 will be added to the $3 file of $4 on $5."), key, luser, lhost, afile, ruser, rhost)}</p>
1020 <p>{_("This will allow you to log in without password in the future.")}</p>
1021 </>;
1022 }
1023 }
1024
1025 const body = <>
1026 {statement}
1027 <br />
1028 {(offer_login_password || offer_key_password) &&
1029 <Form isHorizontal onSubmit={prevent_default(callback)}>
1030 {both &&
1031 <FormGroup label={_("Authentication")} isInline hasNoPaddingTop>
1032 <Radio isChecked={this.state.auth === "password"}
1033 onChange={() => this.setState({ auth: "password" })}
1034 id="auth-password"
1035 value="password"
1036 label={_("Password")} />
1037 <Radio isChecked={this.state.auth === "key"}
1038 onChange={() => this.setState({ auth: "key" })}
1039 id="auth-key"
1040 value="key"
1041 label={_("SSH key")} />
1042 </FormGroup>
1043 }
1044 {((both && this.state.auth === "password") || (!both && offer_login_password)) &&
1045 <FormGroup label={_("Password")}>
1046 <TextInput id="login-custom-password" onChange={(_event, value) => this.setState({ custom_password: value })}
1047 type="password" value={this.state.custom_password} validated={this.state.custom_password_error ? "error" : "default"} />
1048 <FormHelper helperTextInvalid={this.state.custom_password_error} />
1049 </FormGroup>
1050 }
1051 {((both && this.state.auth === "key") || (!both && offer_key_password)) &&
1052 <FormGroup label={_("Key password")}>
1053 <TextInput id="locked-identity-password" onChange={(_event, value) => this.setState({ locked_identity_password: value })}
1054 type="password" autoComplete="new-password" value={this.state.locked_identity_password} validated={this.state.locked_identity_password_error ? "error" : "default"} />
1055 <FormHelper
1056 helperText={cockpit.format(_("The SSH key $0 will be made available for the remainder of the session and will be available for login to other hosts as well."), this.state.identity_path)}
1057 helperTextInvalid={this.state.locked_identity_password_error} />
1058 </FormGroup>
1059 }
1060 {offer_key_setup &&
1061 <FormGroup label={ _("Automatic login") } hasNoPaddingTop isInline>
1062 <Checkbox onChange={(_event, checked) => this.setState({ auto_login: checked })}
1063 isChecked={this.state.auto_login} id="login-setup-keys"
1064 label={auto_text} body={this.state.auto_login ? auto_details : null} />
1065 </FormGroup>
1066 }
1067 </Form>
1068 }
1069 </>;
1070
1071 return (
1072 <Modal id="hosts_setup_server_dialog" isOpen
1073 position="top" variant="medium"
1074 onClose={this.props.onClose}
1075 >
1076 <ModalHeader title={title} />
1077 <ModalBody>
1078 <Stack hasGutter>
1079 { this.props.dialogError && <ModalError dialogError={this.props.dialogError} />}
1080 {body}
1081 </Stack>
1082 </ModalBody>
1083 <ModalFooter>
1084 <Button variant="primary" onClick={callback} isLoading={this.state.inProgress}
1085 isDisabled={this.state.inProgress || (!offer_login_password && !offer_key_password) || !this.state.default_ssh_key || !this.props.error_options}>
1086 { submitText }
1087 </Button>
1088 <Button variant="link" className="btn-cancel" onClick={this.props.onClose}>
1089 { _("Cancel") }
1090 </Button>
1091 </ModalFooter>
1092 </Modal>
1093 );
1094 }
1095 }
1096
1097 function try2Connect(machines_ins, address, options) {
1098 return new Promise((resolve, reject) => {
1099 const conn_options = { ...options, payload: "echo", host: address };
1100
1101 conn_options["init-superuser"] = get_init_superuser_for_options(conn_options);
1102
1103 const machine = machines_ins.lookup(address);
1104 if (machine && machine.host_key && !machine.on_disk) {
1105 conn_options['temp-session'] = false; // Compatibility option
1106 conn_options.session = 'shared';
1107 conn_options['host-key'] = machine.host_key;
1108 }
1109
1110 const client = cockpit.channel(conn_options);
1111 client.send("x");
1112 client.addEventListener("message", () => {
1113 resolve();
1114 client.close();
1115 });
1116 client.addEventListener("close", (event, options) => {
1117 reject(options);
1118 });
1119 });
1120 }
1121
1122 class HostModalInner extends React.Component {
1123 constructor(props) {
1124 super(props);
1125
1126 this.state = {
1127 current_template: this.props.template || "add-machine",
1128 address: full_address(props.machines_ins, props.address),
1129 old_address: full_address(props.machines_ins, props.address),
1130 error_options: this.props.error_options,
1131 dialogError: "", // Error to be shown in the modal
1132 };
1133
1134 this.promise_callback = null;
1135
1136 this.addressOrLabel = this.addressOrLabel.bind(this);
1137 this.changeContent = this.changeContent.bind(this);
1138 this.setGoal = this.setGoal.bind(this);
1139 this.setError = this.setError.bind(this);
1140 this.setAddress = this.setAddress.bind(this);
1141 this.run = this.run.bind(this);
1142 this.complete = this.complete.bind(this);
1143 }
1144
1145 addressOrLabel() {
1146 const machine = this.props.machines_ins.lookup(this.state.address);
1147 let host = split_connection_string(this.state.address).address;
1148 if (machine && machine.label)
1149 host = machine.label;
1150 return host;
1151 }
1152
1153 changeContent(template, error_options, with_error_message) {
1154 if (this.state.current_template !== template)
1155 this.setState({
1156 current_template: template,
1157 error_options,
1158 dialogError: with_error_message ? cockpit.message(error_options) : null,
1159 });
1160 }
1161
1162 complete() {
1163 if (this.promise_callback)
1164 this.promise_callback().then(this.props.onClose);
1165 else
1166 this.props.onClose();
1167 }
1168
1169 setGoal(callback) {
1170 this.promise_callback = callback;
1171 }
1172
1173 setError(error, keep_message_on_change) {
1174 if (error === null)
1175 return this.setState({ dialogError: null });
1176
1177 let template = null;
1178 if (error.problem && error.command === "close")
1179 template = codes[error.problem];
1180
1181 if (template && this.state.current_template !== template)
1182 this.changeContent(template, error, keep_message_on_change);
1183 else
1184 this.setState({ error_options: error, dialogError: cockpit.message(error) });
1185 }
1186
1187 setAddress(address) {
1188 this.setState({ address });
1189 }
1190
1191 run(promise, failure_callback) {
1192 return new Promise((resolve, reject) => {
1193 const promise_funcs = [];
1194 const self = this;
1195
1196 function next(i) {
1197 promise_funcs[i]()
1198 .then(val => {
1199 i = i + 1;
1200 if (i < promise_funcs.length) {
1201 next(i);
1202 } else {
1203 resolve();
1204 self.props.onClose();
1205 }
1206 })
1207 .catch(ex => {
1208 if (failure_callback)
1209 failure_callback(ex);
1210 else
1211 self.setError(ex);
1212 });
1213 }
1214
1215 promise_funcs.push(() => { return promise });
1216
1217 if (this.promise_callback)
1218 promise_funcs.push(this.promise_callback);
1219
1220 if (this.props.caller_callback)
1221 promise_funcs.push(() => this.props.caller_callback(this.state.address));
1222
1223 next(0);
1224 });
1225 }
1226
1227 render() {
1228 const template = this.state.current_template;
1229
1230 const props = {
1231 template,
1232 host: this.addressOrLabel(),
1233 full_address: this.state.address,
1234 old_address: this.state.old_address,
1235 address_data: split_connection_string(this.state.address),
1236 error_options: this.state.error_options,
1237 dialogError: this.state.dialogError,
1238 machines_ins: this.props.machines_ins,
1239 onClose: () => {
1240 if (this.props.caller_cancelled)
1241 this.props.caller_cancelled();
1242 this.props.onClose();
1243 },
1244 run: this.run,
1245 setGoal: this.setGoal,
1246 setError: this.setError,
1247 setAddress: this.setAddress,
1248 try2Connect: this.try2Connect,
1249 complete: this.complete,
1250 };
1251
1252 if (template === "connect")
1253 return <Connect {...props} />;
1254 else if (template === "add-machine")
1255 return <AddMachine {...props} />;
1256 else if (template === "unknown-hostkey" || template === "unknown-host" || template === "invalid-hostkey")
1257 return <HostKey {...props} />;
1258 else if (template === "change-auth")
1259 return <ChangeAuth {...props} />;
1260 else if (template === "change-port")
1261 return <MachinePort {...props} />;
1262 else if (template === "not-supported")
1263 return <NotSupported {...props} />;
1264
1265 console.error("Unknown template:", template);
1266 return null;
1267 }
1268 }
1269
1270 HostModalInner.propTypes = {
1271 machines_ins: PropTypes.object.isRequired,
1272 onClose: PropTypes.func.isRequired,
1273 caller_callback: PropTypes.func,
1274 address: PropTypes.string,
1275 template: PropTypes.string,
1276 };
1277
1278 export const HostModal = ({ state, machines }) => {
1279 if (!state.modal_properties)
1280 return null;
1281
1282 return <HostModalInner machines_ins={machines}
1283 onClose={() => state.close_modal()}
1284 {...state.modal_properties}
1285 caller_callback={state.modal_callback}
1286 caller_cancelled={() => state.modal_callback(null)} />;
1287 };