Merge tag 'pull-target-arm-20240531' of https://git.linaro.org/people/pmaydell/qemu...
[qemu/kevin.git] / block / ssh.c
bloba88171d4b53edb9025f91796a8a7664386ea75fc
1 /*
2 * Secure Shell (ssh) backend for QEMU.
4 * Copyright (C) 2013 Red Hat Inc., Richard W.M. Jones <rjones@redhat.com>
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
27 #include <libssh/libssh.h>
28 #include <libssh/sftp.h>
30 #include "block/block-io.h"
31 #include "block/block_int.h"
32 #include "block/qdict.h"
33 #include "qapi/error.h"
34 #include "qemu/error-report.h"
35 #include "qemu/module.h"
36 #include "qemu/option.h"
37 #include "qemu/ctype.h"
38 #include "qemu/cutils.h"
39 #include "qemu/sockets.h"
40 #include "qapi/qapi-visit-sockets.h"
41 #include "qapi/qapi-visit-block-core.h"
42 #include "qapi/qmp/qdict.h"
43 #include "qapi/qmp/qstring.h"
44 #include "qapi/qobject-input-visitor.h"
45 #include "qapi/qobject-output-visitor.h"
46 #include "trace.h"
49 * TRACE_LIBSSH=<level> enables tracing in libssh itself.
50 * The meaning of <level> is described here:
51 * http://api.libssh.org/master/group__libssh__log.html
53 #define TRACE_LIBSSH 0 /* see: SSH_LOG_* */
55 typedef struct BDRVSSHState {
56 /* Coroutine. */
57 CoMutex lock;
59 /* SSH connection. */
60 int sock; /* socket */
61 ssh_session session; /* ssh session */
62 sftp_session sftp; /* sftp session */
63 sftp_file sftp_handle; /* sftp remote file handle */
66 * File attributes at open. We try to keep the .size field
67 * updated if it changes (eg by writing at the end of the file).
69 sftp_attributes attrs;
71 InetSocketAddress *inet;
73 /* Used to warn if 'flush' is not supported. */
74 bool unsafe_flush_warning;
77 * Store the user name for ssh_refresh_filename() because the
78 * default depends on the system you are on -- therefore, when we
79 * generate a filename, it should always contain the user name we
80 * are actually using.
82 char *user;
83 } BDRVSSHState;
85 static void ssh_state_init(BDRVSSHState *s)
87 memset(s, 0, sizeof *s);
88 s->sock = -1;
89 qemu_co_mutex_init(&s->lock);
92 static void ssh_state_free(BDRVSSHState *s)
94 g_free(s->user);
96 if (s->attrs) {
97 sftp_attributes_free(s->attrs);
99 if (s->sftp_handle) {
100 sftp_close(s->sftp_handle);
102 if (s->sftp) {
103 sftp_free(s->sftp);
105 if (s->session) {
106 ssh_disconnect(s->session);
107 ssh_free(s->session); /* This frees s->sock */
111 static void G_GNUC_PRINTF(3, 4)
112 session_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
114 va_list args;
115 char *msg;
117 va_start(args, fs);
118 msg = g_strdup_vprintf(fs, args);
119 va_end(args);
121 if (s->session) {
122 const char *ssh_err;
123 int ssh_err_code;
125 /* This is not an errno. See <libssh/libssh.h>. */
126 ssh_err = ssh_get_error(s->session);
127 ssh_err_code = ssh_get_error_code(s->session);
128 error_setg(errp, "%s: %s (libssh error code: %d)",
129 msg, ssh_err, ssh_err_code);
130 } else {
131 error_setg(errp, "%s", msg);
133 g_free(msg);
136 static void G_GNUC_PRINTF(3, 4)
137 sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
139 va_list args;
140 char *msg;
142 va_start(args, fs);
143 msg = g_strdup_vprintf(fs, args);
144 va_end(args);
146 if (s->sftp) {
147 const char *ssh_err;
148 int ssh_err_code;
149 int sftp_err_code;
151 /* This is not an errno. See <libssh/libssh.h>. */
152 ssh_err = ssh_get_error(s->session);
153 ssh_err_code = ssh_get_error_code(s->session);
154 /* See <libssh/sftp.h>. */
155 sftp_err_code = sftp_get_error(s->sftp);
157 error_setg(errp,
158 "%s: %s (libssh error code: %d, sftp error code: %d)",
159 msg, ssh_err, ssh_err_code, sftp_err_code);
160 } else {
161 error_setg(errp, "%s", msg);
163 g_free(msg);
166 static void sftp_error_trace(BDRVSSHState *s, const char *op)
168 const char *ssh_err;
169 int ssh_err_code;
170 int sftp_err_code;
172 /* This is not an errno. See <libssh/libssh.h>. */
173 ssh_err = ssh_get_error(s->session);
174 ssh_err_code = ssh_get_error_code(s->session);
175 /* See <libssh/sftp.h>. */
176 sftp_err_code = sftp_get_error(s->sftp);
178 trace_sftp_error(op, ssh_err, ssh_err_code, sftp_err_code);
181 static int parse_uri(const char *filename, QDict *options, Error **errp)
183 g_autoptr(GUri) uri = g_uri_parse(filename, G_URI_FLAGS_NONE, NULL);
184 const char *uri_host, *uri_path, *uri_user, *uri_query;
185 char *port_str;
186 int port;
187 g_autoptr(GError) gerror = NULL;
188 char *qp_name, *qp_value;
189 GUriParamsIter qp;
191 if (!uri) {
192 return -EINVAL;
195 if (g_strcmp0(g_uri_get_scheme(uri), "ssh") != 0) {
196 error_setg(errp, "URI scheme must be 'ssh'");
197 return -EINVAL;
200 uri_host = g_uri_get_host(uri);
201 if (!uri_host || g_str_equal(uri_host, "")) {
202 error_setg(errp, "missing hostname in URI");
203 return -EINVAL;
206 uri_path = g_uri_get_path(uri);
207 if (!uri_path || g_str_equal(uri_path, "")) {
208 error_setg(errp, "missing remote path in URI");
209 return -EINVAL;
212 uri_user = g_uri_get_user(uri);
213 if (uri_user && !g_str_equal(uri_user, "")) {
214 qdict_put_str(options, "user", uri_user);
217 qdict_put_str(options, "server.host", uri_host);
219 port = g_uri_get_port(uri);
220 port_str = g_strdup_printf("%d", port > 0 ? port : 22);
221 qdict_put_str(options, "server.port", port_str);
222 g_free(port_str);
224 qdict_put_str(options, "path", uri_path);
226 uri_query = g_uri_get_query(uri);
227 if (uri_query) {
228 g_uri_params_iter_init(&qp, uri_query, -1, "&", G_URI_PARAMS_NONE);
229 while (g_uri_params_iter_next(&qp, &qp_name, &qp_value, &gerror)) {
230 if (!qp_name || !qp_value || gerror) {
231 warn_report("Failed to parse SSH URI parameters '%s'",
232 uri_query);
233 break;
236 * Pick out the query parameters that we understand, and ignore
237 * (or rather warn about) the rest.
239 if (g_str_equal(qp_name, "host_key_check")) {
240 qdict_put_str(options, "host_key_check", qp_value);
241 } else {
242 warn_report("Unsupported parameter '%s' in URI", qp_name);
247 return 0;
250 static bool ssh_has_filename_options_conflict(QDict *options, Error **errp)
252 const QDictEntry *qe;
254 for (qe = qdict_first(options); qe; qe = qdict_next(options, qe)) {
255 if (!strcmp(qe->key, "host") ||
256 !strcmp(qe->key, "port") ||
257 !strcmp(qe->key, "path") ||
258 !strcmp(qe->key, "user") ||
259 !strcmp(qe->key, "host_key_check") ||
260 strstart(qe->key, "server.", NULL))
262 error_setg(errp, "Option '%s' cannot be used with a file name",
263 qe->key);
264 return true;
268 return false;
271 static void ssh_parse_filename(const char *filename, QDict *options,
272 Error **errp)
274 if (ssh_has_filename_options_conflict(options, errp)) {
275 return;
278 parse_uri(filename, options, errp);
281 static int check_host_key_knownhosts(BDRVSSHState *s, Error **errp)
283 int ret;
284 enum ssh_known_hosts_e state;
285 int r;
286 ssh_key pubkey;
287 enum ssh_keytypes_e pubkey_type;
288 unsigned char *server_hash = NULL;
289 size_t server_hash_len;
290 char *fingerprint = NULL;
292 state = ssh_session_is_known_server(s->session);
293 trace_ssh_server_status(state);
295 switch (state) {
296 case SSH_KNOWN_HOSTS_OK:
297 /* OK */
298 trace_ssh_check_host_key_knownhosts();
299 break;
300 case SSH_KNOWN_HOSTS_CHANGED:
301 ret = -EINVAL;
302 r = ssh_get_server_publickey(s->session, &pubkey);
303 if (r == 0) {
304 r = ssh_get_publickey_hash(pubkey, SSH_PUBLICKEY_HASH_SHA256,
305 &server_hash, &server_hash_len);
306 pubkey_type = ssh_key_type(pubkey);
307 ssh_key_free(pubkey);
309 if (r == 0) {
310 fingerprint = ssh_get_fingerprint_hash(SSH_PUBLICKEY_HASH_SHA256,
311 server_hash,
312 server_hash_len);
313 ssh_clean_pubkey_hash(&server_hash);
315 if (fingerprint) {
316 error_setg(errp,
317 "host key (%s key with fingerprint %s) does not match "
318 "the one in known_hosts; this may be a possible attack",
319 ssh_key_type_to_char(pubkey_type), fingerprint);
320 ssh_string_free_char(fingerprint);
321 } else {
322 error_setg(errp,
323 "host key does not match the one in known_hosts; this "
324 "may be a possible attack");
326 goto out;
327 case SSH_KNOWN_HOSTS_OTHER:
328 ret = -EINVAL;
329 error_setg(errp,
330 "host key for this server not found, another type exists");
331 goto out;
332 case SSH_KNOWN_HOSTS_UNKNOWN:
333 ret = -EINVAL;
334 error_setg(errp, "no host key was found in known_hosts");
335 goto out;
336 case SSH_KNOWN_HOSTS_NOT_FOUND:
337 ret = -ENOENT;
338 error_setg(errp, "known_hosts file not found");
339 goto out;
340 case SSH_KNOWN_HOSTS_ERROR:
341 ret = -EINVAL;
342 error_setg(errp, "error while checking the host");
343 goto out;
344 default:
345 ret = -EINVAL;
346 error_setg(errp, "error while checking for known server (%d)", state);
347 goto out;
350 /* known_hosts checking successful. */
351 ret = 0;
353 out:
354 return ret;
357 static unsigned hex2decimal(char ch)
359 if (ch >= '0' && ch <= '9') {
360 return (ch - '0');
361 } else if (ch >= 'a' && ch <= 'f') {
362 return 10 + (ch - 'a');
363 } else if (ch >= 'A' && ch <= 'F') {
364 return 10 + (ch - 'A');
367 return -1;
370 /* Compare the binary fingerprint (hash of host key) with the
371 * host_key_check parameter.
373 static int compare_fingerprint(const unsigned char *fingerprint, size_t len,
374 const char *host_key_check)
376 unsigned c;
378 while (len > 0) {
379 while (*host_key_check == ':')
380 host_key_check++;
381 if (!qemu_isxdigit(host_key_check[0]) ||
382 !qemu_isxdigit(host_key_check[1]))
383 return 1;
384 c = hex2decimal(host_key_check[0]) * 16 +
385 hex2decimal(host_key_check[1]);
386 if (c - *fingerprint != 0)
387 return c - *fingerprint;
388 fingerprint++;
389 len--;
390 host_key_check += 2;
392 return *host_key_check - '\0';
395 static char *format_fingerprint(const unsigned char *fingerprint, size_t len)
397 static const char *hex = "0123456789abcdef";
398 char *ret = g_new0(char, (len * 2) + 1);
399 for (size_t i = 0; i < len; i++) {
400 ret[i * 2] = hex[((fingerprint[i] >> 4) & 0xf)];
401 ret[(i * 2) + 1] = hex[(fingerprint[i] & 0xf)];
403 ret[len * 2] = '\0';
404 return ret;
407 static int
408 check_host_key_hash(BDRVSSHState *s, const char *hash,
409 enum ssh_publickey_hash_type type, const char *typestr,
410 Error **errp)
412 int r;
413 ssh_key pubkey;
414 unsigned char *server_hash;
415 size_t server_hash_len;
416 const char *keytype;
418 r = ssh_get_server_publickey(s->session, &pubkey);
419 if (r != SSH_OK) {
420 session_error_setg(errp, s, "failed to read remote host key");
421 return -EINVAL;
424 keytype = ssh_key_type_to_char(ssh_key_type(pubkey));
426 r = ssh_get_publickey_hash(pubkey, type, &server_hash, &server_hash_len);
427 ssh_key_free(pubkey);
428 if (r != 0) {
429 session_error_setg(errp, s,
430 "failed reading the hash of the server SSH key");
431 return -EINVAL;
434 r = compare_fingerprint(server_hash, server_hash_len, hash);
435 if (r != 0) {
436 g_autofree char *server_fp = format_fingerprint(server_hash,
437 server_hash_len);
438 error_setg(errp, "remote host %s key fingerprint '%s:%s' "
439 "does not match host_key_check '%s:%s'",
440 keytype, typestr, server_fp, typestr, hash);
441 ssh_clean_pubkey_hash(&server_hash);
442 return -EPERM;
444 ssh_clean_pubkey_hash(&server_hash);
446 return 0;
449 static int check_host_key(BDRVSSHState *s, SshHostKeyCheck *hkc, Error **errp)
451 SshHostKeyCheckMode mode;
453 if (hkc) {
454 mode = hkc->mode;
455 } else {
456 mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
459 switch (mode) {
460 case SSH_HOST_KEY_CHECK_MODE_NONE:
461 return 0;
462 case SSH_HOST_KEY_CHECK_MODE_HASH:
463 if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_MD5) {
464 return check_host_key_hash(s, hkc->u.hash.hash,
465 SSH_PUBLICKEY_HASH_MD5, "md5",
466 errp);
467 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1) {
468 return check_host_key_hash(s, hkc->u.hash.hash,
469 SSH_PUBLICKEY_HASH_SHA1, "sha1",
470 errp);
471 } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA256) {
472 return check_host_key_hash(s, hkc->u.hash.hash,
473 SSH_PUBLICKEY_HASH_SHA256, "sha256",
474 errp);
476 g_assert_not_reached();
477 break;
478 case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
479 return check_host_key_knownhosts(s, errp);
480 default:
481 g_assert_not_reached();
484 return -EINVAL;
487 static int authenticate(BDRVSSHState *s, Error **errp)
489 int r, ret;
490 int method;
492 /* Try to authenticate with the "none" method. */
493 r = ssh_userauth_none(s->session, NULL);
494 if (r == SSH_AUTH_ERROR) {
495 ret = -EPERM;
496 session_error_setg(errp, s, "failed to authenticate using none "
497 "authentication");
498 goto out;
499 } else if (r == SSH_AUTH_SUCCESS) {
500 /* Authenticated! */
501 ret = 0;
502 goto out;
505 method = ssh_userauth_list(s->session, NULL);
506 trace_ssh_auth_methods(method);
509 * Try to authenticate with publickey, using the ssh-agent
510 * if available.
512 if (method & SSH_AUTH_METHOD_PUBLICKEY) {
513 r = ssh_userauth_publickey_auto(s->session, NULL, NULL);
514 if (r == SSH_AUTH_ERROR) {
515 ret = -EINVAL;
516 session_error_setg(errp, s, "failed to authenticate using "
517 "publickey authentication");
518 goto out;
519 } else if (r == SSH_AUTH_SUCCESS) {
520 /* Authenticated! */
521 ret = 0;
522 goto out;
526 ret = -EPERM;
527 error_setg(errp, "failed to authenticate using publickey authentication "
528 "and the identities held by your ssh-agent");
530 out:
531 return ret;
534 static QemuOptsList ssh_runtime_opts = {
535 .name = "ssh",
536 .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
537 .desc = {
539 .name = "host",
540 .type = QEMU_OPT_STRING,
541 .help = "Host to connect to",
544 .name = "port",
545 .type = QEMU_OPT_NUMBER,
546 .help = "Port to connect to",
549 .name = "host_key_check",
550 .type = QEMU_OPT_STRING,
551 .help = "Defines how and what to check the host key against",
553 { /* end of list */ }
557 static bool ssh_process_legacy_options(QDict *output_opts,
558 QemuOpts *legacy_opts,
559 Error **errp)
561 const char *host = qemu_opt_get(legacy_opts, "host");
562 const char *port = qemu_opt_get(legacy_opts, "port");
563 const char *host_key_check = qemu_opt_get(legacy_opts, "host_key_check");
565 if (!host && port) {
566 error_setg(errp, "port may not be used without host");
567 return false;
570 if (host) {
571 qdict_put_str(output_opts, "server.host", host);
572 qdict_put_str(output_opts, "server.port", port ?: stringify(22));
575 if (host_key_check) {
576 if (strcmp(host_key_check, "no") == 0) {
577 qdict_put_str(output_opts, "host-key-check.mode", "none");
578 } else if (strncmp(host_key_check, "md5:", 4) == 0) {
579 qdict_put_str(output_opts, "host-key-check.mode", "hash");
580 qdict_put_str(output_opts, "host-key-check.type", "md5");
581 qdict_put_str(output_opts, "host-key-check.hash",
582 &host_key_check[4]);
583 } else if (strncmp(host_key_check, "sha1:", 5) == 0) {
584 qdict_put_str(output_opts, "host-key-check.mode", "hash");
585 qdict_put_str(output_opts, "host-key-check.type", "sha1");
586 qdict_put_str(output_opts, "host-key-check.hash",
587 &host_key_check[5]);
588 } else if (strncmp(host_key_check, "sha256:", 7) == 0) {
589 qdict_put_str(output_opts, "host-key-check.mode", "hash");
590 qdict_put_str(output_opts, "host-key-check.type", "sha256");
591 qdict_put_str(output_opts, "host-key-check.hash",
592 &host_key_check[7]);
593 } else if (strcmp(host_key_check, "yes") == 0) {
594 qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
595 } else {
596 error_setg(errp, "unknown host_key_check setting (%s)",
597 host_key_check);
598 return false;
602 return true;
605 static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
607 BlockdevOptionsSsh *result = NULL;
608 QemuOpts *opts = NULL;
609 const QDictEntry *e;
610 Visitor *v;
612 /* Translate legacy options */
613 opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
614 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
615 goto fail;
618 if (!ssh_process_legacy_options(options, opts, errp)) {
619 goto fail;
622 /* Create the QAPI object */
623 v = qobject_input_visitor_new_flat_confused(options, errp);
624 if (!v) {
625 goto fail;
628 visit_type_BlockdevOptionsSsh(v, NULL, &result, errp);
629 visit_free(v);
630 if (!result) {
631 goto fail;
634 /* Remove the processed options from the QDict (the visitor processes
635 * _all_ options in the QDict) */
636 while ((e = qdict_first(options))) {
637 qdict_del(options, e->key);
640 fail:
641 qemu_opts_del(opts);
642 return result;
645 static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
646 int ssh_flags, int creat_mode, Error **errp)
648 int r, ret;
649 unsigned int port = 0;
650 int new_sock = -1;
652 if (opts->user) {
653 s->user = g_strdup(opts->user);
654 } else {
655 s->user = g_strdup(g_get_user_name());
656 if (!s->user) {
657 error_setg_errno(errp, errno, "Can't get user name");
658 ret = -errno;
659 goto err;
663 /* Pop the config into our state object, Exit if invalid */
664 s->inet = opts->server;
665 opts->server = NULL;
667 if (qemu_strtoui(s->inet->port, NULL, 10, &port) < 0) {
668 error_setg(errp, "Use only numeric port value");
669 ret = -EINVAL;
670 goto err;
673 /* Open the socket and connect. */
674 new_sock = inet_connect_saddr(s->inet, errp);
675 if (new_sock < 0) {
676 ret = -EIO;
677 goto err;
681 * Try to disable the Nagle algorithm on TCP sockets to reduce latency,
682 * but do not fail if it cannot be disabled.
684 r = socket_set_nodelay(new_sock);
685 if (r < 0) {
686 warn_report("can't set TCP_NODELAY for the ssh server %s: %s",
687 s->inet->host, strerror(errno));
690 /* Create SSH session. */
691 s->session = ssh_new();
692 if (!s->session) {
693 ret = -EINVAL;
694 session_error_setg(errp, s, "failed to initialize libssh session");
695 goto err;
699 * Make sure we are in blocking mode during the connection and
700 * authentication phases.
702 ssh_set_blocking(s->session, 1);
704 r = ssh_options_set(s->session, SSH_OPTIONS_USER, s->user);
705 if (r < 0) {
706 ret = -EINVAL;
707 session_error_setg(errp, s,
708 "failed to set the user in the libssh session");
709 goto err;
712 r = ssh_options_set(s->session, SSH_OPTIONS_HOST, s->inet->host);
713 if (r < 0) {
714 ret = -EINVAL;
715 session_error_setg(errp, s,
716 "failed to set the host in the libssh session");
717 goto err;
720 if (port > 0) {
721 r = ssh_options_set(s->session, SSH_OPTIONS_PORT, &port);
722 if (r < 0) {
723 ret = -EINVAL;
724 session_error_setg(errp, s,
725 "failed to set the port in the libssh session");
726 goto err;
730 r = ssh_options_set(s->session, SSH_OPTIONS_COMPRESSION, "none");
731 if (r < 0) {
732 ret = -EINVAL;
733 session_error_setg(errp, s,
734 "failed to disable the compression in the libssh "
735 "session");
736 goto err;
739 /* Read ~/.ssh/config. */
740 r = ssh_options_parse_config(s->session, NULL);
741 if (r < 0) {
742 ret = -EINVAL;
743 session_error_setg(errp, s, "failed to parse ~/.ssh/config");
744 goto err;
747 r = ssh_options_set(s->session, SSH_OPTIONS_FD, &new_sock);
748 if (r < 0) {
749 ret = -EINVAL;
750 session_error_setg(errp, s,
751 "failed to set the socket in the libssh session");
752 goto err;
754 /* libssh took ownership of the socket. */
755 s->sock = new_sock;
756 new_sock = -1;
758 /* Connect. */
759 r = ssh_connect(s->session);
760 if (r != SSH_OK) {
761 ret = -EINVAL;
762 session_error_setg(errp, s, "failed to establish SSH session");
763 goto err;
766 /* Check the remote host's key against known_hosts. */
767 ret = check_host_key(s, opts->host_key_check, errp);
768 if (ret < 0) {
769 goto err;
772 /* Authenticate. */
773 ret = authenticate(s, errp);
774 if (ret < 0) {
775 goto err;
778 /* Start SFTP. */
779 s->sftp = sftp_new(s->session);
780 if (!s->sftp) {
781 session_error_setg(errp, s, "failed to create sftp handle");
782 ret = -EINVAL;
783 goto err;
786 r = sftp_init(s->sftp);
787 if (r < 0) {
788 sftp_error_setg(errp, s, "failed to initialize sftp handle");
789 ret = -EINVAL;
790 goto err;
793 /* Open the remote file. */
794 trace_ssh_connect_to_ssh(opts->path, ssh_flags, creat_mode);
795 s->sftp_handle = sftp_open(s->sftp, opts->path, ssh_flags, creat_mode);
796 if (!s->sftp_handle) {
797 sftp_error_setg(errp, s, "failed to open remote file '%s'",
798 opts->path);
799 ret = -EINVAL;
800 goto err;
803 /* Make sure the SFTP file is handled in blocking mode. */
804 sftp_file_set_blocking(s->sftp_handle);
806 s->attrs = sftp_fstat(s->sftp_handle);
807 if (!s->attrs) {
808 sftp_error_setg(errp, s, "failed to read file attributes");
809 return -EINVAL;
812 return 0;
814 err:
815 if (s->attrs) {
816 sftp_attributes_free(s->attrs);
818 s->attrs = NULL;
819 if (s->sftp_handle) {
820 sftp_close(s->sftp_handle);
822 s->sftp_handle = NULL;
823 if (s->sftp) {
824 sftp_free(s->sftp);
826 s->sftp = NULL;
827 if (s->session) {
828 ssh_disconnect(s->session);
829 ssh_free(s->session);
831 s->session = NULL;
832 s->sock = -1;
833 if (new_sock >= 0) {
834 close(new_sock);
837 return ret;
840 static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
841 Error **errp)
843 BDRVSSHState *s = bs->opaque;
844 BlockdevOptionsSsh *opts;
845 int ret;
846 int ssh_flags;
848 ssh_state_init(s);
850 ssh_flags = 0;
851 if (bdrv_flags & BDRV_O_RDWR) {
852 ssh_flags |= O_RDWR;
853 } else {
854 ssh_flags |= O_RDONLY;
857 opts = ssh_parse_options(options, errp);
858 if (opts == NULL) {
859 return -EINVAL;
862 /* Start up SSH. */
863 ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
864 if (ret < 0) {
865 goto err;
868 /* Go non-blocking. */
869 ssh_set_blocking(s->session, 0);
871 if (s->attrs->type == SSH_FILEXFER_TYPE_REGULAR) {
872 bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
875 qapi_free_BlockdevOptionsSsh(opts);
877 return 0;
879 err:
880 qapi_free_BlockdevOptionsSsh(opts);
882 return ret;
885 /* Note: This is a blocking operation */
886 static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
888 ssize_t ret;
889 char c[1] = { '\0' };
890 int was_blocking = ssh_is_blocking(s->session);
892 /* offset must be strictly greater than the current size so we do
893 * not overwrite anything */
894 assert(offset > 0 && offset > s->attrs->size);
896 ssh_set_blocking(s->session, 1);
898 sftp_seek64(s->sftp_handle, offset - 1);
899 ret = sftp_write(s->sftp_handle, c, 1);
901 ssh_set_blocking(s->session, was_blocking);
903 if (ret < 0) {
904 sftp_error_setg(errp, s, "Failed to grow file");
905 return -EIO;
908 s->attrs->size = offset;
909 return 0;
912 static QemuOptsList ssh_create_opts = {
913 .name = "ssh-create-opts",
914 .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
915 .desc = {
917 .name = BLOCK_OPT_SIZE,
918 .type = QEMU_OPT_SIZE,
919 .help = "Virtual disk size"
921 { /* end of list */ }
925 static int ssh_co_create(BlockdevCreateOptions *options, Error **errp)
927 BlockdevCreateOptionsSsh *opts = &options->u.ssh;
928 BDRVSSHState s;
929 int ret;
931 assert(options->driver == BLOCKDEV_DRIVER_SSH);
933 ssh_state_init(&s);
935 ret = connect_to_ssh(&s, opts->location,
936 O_RDWR | O_CREAT | O_TRUNC,
937 0644, errp);
938 if (ret < 0) {
939 goto fail;
942 if (opts->size > 0) {
943 ret = ssh_grow_file(&s, opts->size, errp);
944 if (ret < 0) {
945 goto fail;
949 ret = 0;
950 fail:
951 ssh_state_free(&s);
952 return ret;
955 static int coroutine_fn ssh_co_create_opts(BlockDriver *drv,
956 const char *filename,
957 QemuOpts *opts,
958 Error **errp)
960 BlockdevCreateOptions *create_options;
961 BlockdevCreateOptionsSsh *ssh_opts;
962 int ret;
963 QDict *uri_options = NULL;
965 create_options = g_new0(BlockdevCreateOptions, 1);
966 create_options->driver = BLOCKDEV_DRIVER_SSH;
967 ssh_opts = &create_options->u.ssh;
969 /* Get desired file size. */
970 ssh_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
971 BDRV_SECTOR_SIZE);
972 trace_ssh_co_create_opts(ssh_opts->size);
974 uri_options = qdict_new();
975 ret = parse_uri(filename, uri_options, errp);
976 if (ret < 0) {
977 goto out;
980 ssh_opts->location = ssh_parse_options(uri_options, errp);
981 if (ssh_opts->location == NULL) {
982 ret = -EINVAL;
983 goto out;
986 ret = ssh_co_create(create_options, errp);
988 out:
989 qobject_unref(uri_options);
990 qapi_free_BlockdevCreateOptions(create_options);
991 return ret;
994 static void ssh_close(BlockDriverState *bs)
996 BDRVSSHState *s = bs->opaque;
998 ssh_state_free(s);
1001 static int ssh_has_zero_init(BlockDriverState *bs)
1003 BDRVSSHState *s = bs->opaque;
1004 /* Assume false, unless we can positively prove it's true. */
1005 int has_zero_init = 0;
1007 if (s->attrs->type == SSH_FILEXFER_TYPE_REGULAR) {
1008 has_zero_init = 1;
1011 return has_zero_init;
1014 typedef struct BDRVSSHRestart {
1015 BlockDriverState *bs;
1016 Coroutine *co;
1017 } BDRVSSHRestart;
1019 static void restart_coroutine(void *opaque)
1021 BDRVSSHRestart *restart = opaque;
1022 BlockDriverState *bs = restart->bs;
1023 BDRVSSHState *s = bs->opaque;
1024 AioContext *ctx = bdrv_get_aio_context(bs);
1026 trace_ssh_restart_coroutine(restart->co);
1027 aio_set_fd_handler(ctx, s->sock, NULL, NULL, NULL, NULL, NULL);
1029 aio_co_wake(restart->co);
1032 /* A non-blocking call returned EAGAIN, so yield, ensuring the
1033 * handlers are set up so that we'll be rescheduled when there is an
1034 * interesting event on the socket.
1036 static coroutine_fn void co_yield(BDRVSSHState *s, BlockDriverState *bs)
1038 int r;
1039 IOHandler *rd_handler = NULL, *wr_handler = NULL;
1040 BDRVSSHRestart restart = {
1041 .bs = bs,
1042 .co = qemu_coroutine_self()
1045 r = ssh_get_poll_flags(s->session);
1047 if (r & SSH_READ_PENDING) {
1048 rd_handler = restart_coroutine;
1050 if (r & SSH_WRITE_PENDING) {
1051 wr_handler = restart_coroutine;
1054 trace_ssh_co_yield(s->sock, rd_handler, wr_handler);
1056 aio_set_fd_handler(bdrv_get_aio_context(bs), s->sock,
1057 rd_handler, wr_handler, NULL, NULL, &restart);
1058 qemu_coroutine_yield();
1059 trace_ssh_co_yield_back(s->sock);
1062 static coroutine_fn int ssh_read(BDRVSSHState *s, BlockDriverState *bs,
1063 int64_t offset, size_t size,
1064 QEMUIOVector *qiov)
1066 ssize_t r;
1067 size_t got;
1068 char *buf, *end_of_vec;
1069 struct iovec *i;
1071 trace_ssh_read(offset, size);
1073 trace_ssh_seek(offset);
1074 sftp_seek64(s->sftp_handle, offset);
1076 /* This keeps track of the current iovec element ('i'), where we
1077 * will write to next ('buf'), and the end of the current iovec
1078 * ('end_of_vec').
1080 i = &qiov->iov[0];
1081 buf = i->iov_base;
1082 end_of_vec = i->iov_base + i->iov_len;
1084 for (got = 0; got < size; ) {
1085 size_t request_read_size;
1086 again:
1088 * The size of SFTP packets is limited to 32K bytes, so limit
1089 * the amount of data requested to 16K, as libssh currently
1090 * does not handle multiple requests on its own.
1092 request_read_size = MIN(end_of_vec - buf, 16384);
1093 trace_ssh_read_buf(buf, end_of_vec - buf, request_read_size);
1094 r = sftp_read(s->sftp_handle, buf, request_read_size);
1095 trace_ssh_read_return(r, sftp_get_error(s->sftp));
1097 if (r == SSH_AGAIN) {
1098 co_yield(s, bs);
1099 goto again;
1101 if (r == SSH_EOF || (r == 0 && sftp_get_error(s->sftp) == SSH_FX_EOF)) {
1102 /* EOF: Short read so pad the buffer with zeroes and return it. */
1103 qemu_iovec_memset(qiov, got, 0, size - got);
1104 return 0;
1106 if (r <= 0) {
1107 sftp_error_trace(s, "read");
1108 return -EIO;
1111 got += r;
1112 buf += r;
1113 if (buf >= end_of_vec && got < size) {
1114 i++;
1115 buf = i->iov_base;
1116 end_of_vec = i->iov_base + i->iov_len;
1120 return 0;
1123 static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1124 int64_t sector_num,
1125 int nb_sectors, QEMUIOVector *qiov)
1127 BDRVSSHState *s = bs->opaque;
1128 int ret;
1130 qemu_co_mutex_lock(&s->lock);
1131 ret = ssh_read(s, bs, sector_num * BDRV_SECTOR_SIZE,
1132 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1133 qemu_co_mutex_unlock(&s->lock);
1135 return ret;
1138 static coroutine_fn int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1139 int64_t offset, size_t size,
1140 QEMUIOVector *qiov)
1142 ssize_t r;
1143 size_t written;
1144 char *buf, *end_of_vec;
1145 struct iovec *i;
1147 trace_ssh_write(offset, size);
1149 trace_ssh_seek(offset);
1150 sftp_seek64(s->sftp_handle, offset);
1152 /* This keeps track of the current iovec element ('i'), where we
1153 * will read from next ('buf'), and the end of the current iovec
1154 * ('end_of_vec').
1156 i = &qiov->iov[0];
1157 buf = i->iov_base;
1158 end_of_vec = i->iov_base + i->iov_len;
1160 for (written = 0; written < size; ) {
1161 size_t request_write_size;
1162 again:
1164 * Avoid too large data packets, as libssh currently does not
1165 * handle multiple requests on its own.
1167 request_write_size = MIN(end_of_vec - buf, 131072);
1168 trace_ssh_write_buf(buf, end_of_vec - buf, request_write_size);
1169 r = sftp_write(s->sftp_handle, buf, request_write_size);
1170 trace_ssh_write_return(r, sftp_get_error(s->sftp));
1172 if (r == SSH_AGAIN) {
1173 co_yield(s, bs);
1174 goto again;
1176 if (r < 0) {
1177 sftp_error_trace(s, "write");
1178 return -EIO;
1181 written += r;
1182 buf += r;
1183 if (buf >= end_of_vec && written < size) {
1184 i++;
1185 buf = i->iov_base;
1186 end_of_vec = i->iov_base + i->iov_len;
1189 if (offset + written > s->attrs->size) {
1190 s->attrs->size = offset + written;
1194 return 0;
1197 static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1198 int64_t sector_num,
1199 int nb_sectors, QEMUIOVector *qiov,
1200 int flags)
1202 BDRVSSHState *s = bs->opaque;
1203 int ret;
1205 qemu_co_mutex_lock(&s->lock);
1206 ret = ssh_write(s, bs, sector_num * BDRV_SECTOR_SIZE,
1207 nb_sectors * BDRV_SECTOR_SIZE, qiov);
1208 qemu_co_mutex_unlock(&s->lock);
1210 return ret;
1213 static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1215 if (!s->unsafe_flush_warning) {
1216 warn_report("ssh server %s does not support fsync",
1217 s->inet->host);
1218 if (what) {
1219 error_report("to support fsync, you need %s", what);
1221 s->unsafe_flush_warning = true;
1225 static coroutine_fn int ssh_flush(BDRVSSHState *s, BlockDriverState *bs)
1227 int r;
1229 trace_ssh_flush();
1231 if (!sftp_extension_supported(s->sftp, "fsync@openssh.com", "1")) {
1232 unsafe_flush_warning(s, "OpenSSH >= 6.3");
1233 return 0;
1235 again:
1236 r = sftp_fsync(s->sftp_handle);
1237 if (r == SSH_AGAIN) {
1238 co_yield(s, bs);
1239 goto again;
1241 if (r < 0) {
1242 sftp_error_trace(s, "fsync");
1243 return -EIO;
1246 return 0;
1249 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1251 BDRVSSHState *s = bs->opaque;
1252 int ret;
1254 qemu_co_mutex_lock(&s->lock);
1255 ret = ssh_flush(s, bs);
1256 qemu_co_mutex_unlock(&s->lock);
1258 return ret;
1261 static int64_t coroutine_fn ssh_co_getlength(BlockDriverState *bs)
1263 BDRVSSHState *s = bs->opaque;
1264 int64_t length;
1266 /* Note we cannot make a libssh call here. */
1267 length = (int64_t) s->attrs->size;
1268 trace_ssh_getlength(length);
1270 return length;
1273 static int coroutine_fn ssh_co_truncate(BlockDriverState *bs, int64_t offset,
1274 bool exact, PreallocMode prealloc,
1275 BdrvRequestFlags flags, Error **errp)
1277 BDRVSSHState *s = bs->opaque;
1279 if (prealloc != PREALLOC_MODE_OFF) {
1280 error_setg(errp, "Unsupported preallocation mode '%s'",
1281 PreallocMode_str(prealloc));
1282 return -ENOTSUP;
1285 if (offset < s->attrs->size) {
1286 error_setg(errp, "ssh driver does not support shrinking files");
1287 return -ENOTSUP;
1290 if (offset == s->attrs->size) {
1291 return 0;
1294 return ssh_grow_file(s, offset, errp);
1297 static void ssh_refresh_filename(BlockDriverState *bs)
1299 BDRVSSHState *s = bs->opaque;
1300 const char *path, *host_key_check;
1301 int ret;
1304 * None of these options can be represented in a plain "host:port"
1305 * format, so if any was given, we have to abort.
1307 if (s->inet->has_ipv4 || s->inet->has_ipv6 || s->inet->has_to ||
1308 s->inet->has_numeric)
1310 return;
1313 path = qdict_get_try_str(bs->full_open_options, "path");
1314 assert(path); /* mandatory option */
1316 host_key_check = qdict_get_try_str(bs->full_open_options, "host_key_check");
1318 ret = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1319 "ssh://%s@%s:%s%s%s%s",
1320 s->user, s->inet->host, s->inet->port, path,
1321 host_key_check ? "?host_key_check=" : "",
1322 host_key_check ?: "");
1323 if (ret >= sizeof(bs->exact_filename)) {
1324 /* An overflow makes the filename unusable, so do not report any */
1325 bs->exact_filename[0] = '\0';
1329 static char *ssh_bdrv_dirname(BlockDriverState *bs, Error **errp)
1331 if (qdict_haskey(bs->full_open_options, "host_key_check")) {
1333 * We cannot generate a simple prefix if we would have to
1334 * append a query string.
1336 error_setg(errp,
1337 "Cannot generate a base directory with host_key_check set");
1338 return NULL;
1341 if (bs->exact_filename[0] == '\0') {
1342 error_setg(errp, "Cannot generate a base directory for this ssh node");
1343 return NULL;
1346 return path_combine(bs->exact_filename, "");
1349 static const char *const ssh_strong_runtime_opts[] = {
1350 "host",
1351 "port",
1352 "path",
1353 "user",
1354 "host_key_check",
1355 "server.",
1357 NULL
1360 static BlockDriver bdrv_ssh = {
1361 .format_name = "ssh",
1362 .protocol_name = "ssh",
1363 .instance_size = sizeof(BDRVSSHState),
1364 .bdrv_parse_filename = ssh_parse_filename,
1365 .bdrv_file_open = ssh_file_open,
1366 .bdrv_co_create = ssh_co_create,
1367 .bdrv_co_create_opts = ssh_co_create_opts,
1368 .bdrv_close = ssh_close,
1369 .bdrv_has_zero_init = ssh_has_zero_init,
1370 .bdrv_co_readv = ssh_co_readv,
1371 .bdrv_co_writev = ssh_co_writev,
1372 .bdrv_co_getlength = ssh_co_getlength,
1373 .bdrv_co_truncate = ssh_co_truncate,
1374 .bdrv_co_flush_to_disk = ssh_co_flush,
1375 .bdrv_refresh_filename = ssh_refresh_filename,
1376 .bdrv_dirname = ssh_bdrv_dirname,
1377 .create_opts = &ssh_create_opts,
1378 .strong_runtime_opts = ssh_strong_runtime_opts,
1381 static void bdrv_ssh_init(void)
1383 int r;
1385 r = ssh_init();
1386 if (r != 0) {
1387 fprintf(stderr, "libssh initialization failed, %d\n", r);
1388 exit(EXIT_FAILURE);
1391 #if TRACE_LIBSSH != 0
1392 ssh_set_log_level(TRACE_LIBSSH);
1393 #endif
1395 bdrv_register(&bdrv_ssh);
1398 block_init(bdrv_ssh_init);