xref: /openbmc/qemu/block/ssh.c (revision 4f752191)
1 /*
2  * Secure Shell (ssh) backend for QEMU.
3  *
4  * Copyright (C) 2013 Red Hat Inc., Richard W.M. Jones <rjones@redhat.com>
5  *
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:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
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.
23  */
24 
25 #include "qemu/osdep.h"
26 
27 #include <libssh/libssh.h>
28 #include <libssh/sftp.h>
29 
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"
47 
48 /*
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
52  */
53 #define TRACE_LIBSSH  0 /* see: SSH_LOG_* */
54 
55 typedef struct BDRVSSHState {
56     /* Coroutine. */
57     CoMutex lock;
58 
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 */
64 
65     /*
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).
68      */
69     sftp_attributes attrs;
70 
71     InetSocketAddress *inet;
72 
73     /* Used to warn if 'flush' is not supported. */
74     bool unsafe_flush_warning;
75 
76     /*
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.
81      */
82     char *user;
83 } BDRVSSHState;
84 
85 static void ssh_state_init(BDRVSSHState *s)
86 {
87     memset(s, 0, sizeof *s);
88     s->sock = -1;
89     qemu_co_mutex_init(&s->lock);
90 }
91 
92 static void ssh_state_free(BDRVSSHState *s)
93 {
94     g_free(s->user);
95 
96     if (s->attrs) {
97         sftp_attributes_free(s->attrs);
98     }
99     if (s->sftp_handle) {
100         sftp_close(s->sftp_handle);
101     }
102     if (s->sftp) {
103         sftp_free(s->sftp);
104     }
105     if (s->session) {
106         ssh_disconnect(s->session);
107         ssh_free(s->session); /* This frees s->sock */
108     }
109 }
110 
111 static void G_GNUC_PRINTF(3, 4)
112 session_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
113 {
114     va_list args;
115     char *msg;
116 
117     va_start(args, fs);
118     msg = g_strdup_vprintf(fs, args);
119     va_end(args);
120 
121     if (s->session) {
122         const char *ssh_err;
123         int ssh_err_code;
124 
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);
132     }
133     g_free(msg);
134 }
135 
136 static void G_GNUC_PRINTF(3, 4)
137 sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
138 {
139     va_list args;
140     char *msg;
141 
142     va_start(args, fs);
143     msg = g_strdup_vprintf(fs, args);
144     va_end(args);
145 
146     if (s->sftp) {
147         const char *ssh_err;
148         int ssh_err_code;
149         int sftp_err_code;
150 
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);
156 
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);
162     }
163     g_free(msg);
164 }
165 
166 static void sftp_error_trace(BDRVSSHState *s, const char *op)
167 {
168     const char *ssh_err;
169     int ssh_err_code;
170     int sftp_err_code;
171 
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);
177 
178     trace_sftp_error(op, ssh_err, ssh_err_code, sftp_err_code);
179 }
180 
181 static int parse_uri(const char *filename, QDict *options, Error **errp)
182 {
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;
190 
191     if (!uri) {
192         return -EINVAL;
193     }
194 
195     if (g_strcmp0(g_uri_get_scheme(uri), "ssh") != 0) {
196         error_setg(errp, "URI scheme must be 'ssh'");
197         return -EINVAL;
198     }
199 
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;
204     }
205 
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;
210     }
211 
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);
215     }
216 
217     qdict_put_str(options, "server.host", uri_host);
218 
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);
223 
224     qdict_put_str(options, "path", uri_path);
225 
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;
234             }
235             /*
236              * Pick out the query parameters that we understand, and ignore
237              * (or rather warn about) the rest.
238              */
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);
243             }
244         }
245     }
246 
247     return 0;
248 }
249 
250 static bool ssh_has_filename_options_conflict(QDict *options, Error **errp)
251 {
252     const QDictEntry *qe;
253 
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))
261         {
262             error_setg(errp, "Option '%s' cannot be used with a file name",
263                        qe->key);
264             return true;
265         }
266     }
267 
268     return false;
269 }
270 
271 static void ssh_parse_filename(const char *filename, QDict *options,
272                                Error **errp)
273 {
274     if (ssh_has_filename_options_conflict(options, errp)) {
275         return;
276     }
277 
278     parse_uri(filename, options, errp);
279 }
280 
281 static int check_host_key_knownhosts(BDRVSSHState *s, Error **errp)
282 {
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;
291 
292     state = ssh_session_is_known_server(s->session);
293     trace_ssh_server_status(state);
294 
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);
308         }
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);
314         }
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");
325         }
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;
348     }
349 
350     /* known_hosts checking successful. */
351     ret = 0;
352 
353  out:
354     return ret;
355 }
356 
357 static unsigned hex2decimal(char ch)
358 {
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');
365     }
366 
367     return UINT_MAX;
368 }
369 
370 /* Compare the binary fingerprint (hash of host key) with the
371  * host_key_check parameter.
372  */
373 static int compare_fingerprint(const unsigned char *fingerprint, size_t len,
374                                const char *host_key_check)
375 {
376     unsigned c;
377 
378     while (len > 0) {
379         unsigned c0, c1;
380         while (*host_key_check == ':')
381             host_key_check++;
382         c0 = hex2decimal(host_key_check[0]);
383         c1 = hex2decimal(host_key_check[1]);
384         if (c0 > 0xf || c1 > 0xf) {
385             return 1;
386         }
387         c = c0 * 16 + c1;
388         if (c - *fingerprint != 0)
389             return c - *fingerprint;
390         fingerprint++;
391         len--;
392         host_key_check += 2;
393     }
394     return *host_key_check - '\0';
395 }
396 
397 static char *format_fingerprint(const unsigned char *fingerprint, size_t len)
398 {
399     static const char *hex = "0123456789abcdef";
400     char *ret = g_new0(char, (len * 2) + 1);
401     for (size_t i = 0; i < len; i++) {
402         ret[i * 2] = hex[((fingerprint[i] >> 4) & 0xf)];
403         ret[(i * 2) + 1] = hex[(fingerprint[i] & 0xf)];
404     }
405     ret[len * 2] = '\0';
406     return ret;
407 }
408 
409 static int
410 check_host_key_hash(BDRVSSHState *s, const char *hash,
411                     enum ssh_publickey_hash_type type, const char *typestr,
412                     Error **errp)
413 {
414     int r;
415     ssh_key pubkey;
416     unsigned char *server_hash;
417     size_t server_hash_len;
418     const char *keytype;
419 
420     r = ssh_get_server_publickey(s->session, &pubkey);
421     if (r != SSH_OK) {
422         session_error_setg(errp, s, "failed to read remote host key");
423         return -EINVAL;
424     }
425 
426     keytype = ssh_key_type_to_char(ssh_key_type(pubkey));
427 
428     r = ssh_get_publickey_hash(pubkey, type, &server_hash, &server_hash_len);
429     ssh_key_free(pubkey);
430     if (r != 0) {
431         session_error_setg(errp, s,
432                            "failed reading the hash of the server SSH key");
433         return -EINVAL;
434     }
435 
436     r = compare_fingerprint(server_hash, server_hash_len, hash);
437     if (r != 0) {
438         g_autofree char *server_fp = format_fingerprint(server_hash,
439                                                         server_hash_len);
440         error_setg(errp, "remote host %s key fingerprint '%s:%s' "
441                    "does not match host_key_check '%s:%s'",
442                    keytype, typestr, server_fp, typestr, hash);
443         ssh_clean_pubkey_hash(&server_hash);
444         return -EPERM;
445     }
446     ssh_clean_pubkey_hash(&server_hash);
447 
448     return 0;
449 }
450 
451 static int check_host_key(BDRVSSHState *s, SshHostKeyCheck *hkc, Error **errp)
452 {
453     SshHostKeyCheckMode mode;
454 
455     if (hkc) {
456         mode = hkc->mode;
457     } else {
458         mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
459     }
460 
461     switch (mode) {
462     case SSH_HOST_KEY_CHECK_MODE_NONE:
463         return 0;
464     case SSH_HOST_KEY_CHECK_MODE_HASH:
465         if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_MD5) {
466             return check_host_key_hash(s, hkc->u.hash.hash,
467                                        SSH_PUBLICKEY_HASH_MD5, "md5",
468                                        errp);
469         } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1) {
470             return check_host_key_hash(s, hkc->u.hash.hash,
471                                        SSH_PUBLICKEY_HASH_SHA1, "sha1",
472                                        errp);
473         } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA256) {
474             return check_host_key_hash(s, hkc->u.hash.hash,
475                                        SSH_PUBLICKEY_HASH_SHA256, "sha256",
476                                        errp);
477         }
478         g_assert_not_reached();
479     case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
480         return check_host_key_knownhosts(s, errp);
481     default:
482         g_assert_not_reached();
483     }
484 
485     return -EINVAL;
486 }
487 
488 static int authenticate(BDRVSSHState *s, Error **errp)
489 {
490     int r, ret;
491     int method;
492 
493     /* Try to authenticate with the "none" method. */
494     r = ssh_userauth_none(s->session, NULL);
495     if (r == SSH_AUTH_ERROR) {
496         ret = -EPERM;
497         session_error_setg(errp, s, "failed to authenticate using none "
498                                     "authentication");
499         goto out;
500     } else if (r == SSH_AUTH_SUCCESS) {
501         /* Authenticated! */
502         ret = 0;
503         goto out;
504     }
505 
506     method = ssh_userauth_list(s->session, NULL);
507     trace_ssh_auth_methods(method);
508 
509     /*
510      * Try to authenticate with publickey, using the ssh-agent
511      * if available.
512      */
513     if (method & SSH_AUTH_METHOD_PUBLICKEY) {
514         r = ssh_userauth_publickey_auto(s->session, NULL, NULL);
515         if (r == SSH_AUTH_ERROR) {
516             ret = -EINVAL;
517             session_error_setg(errp, s, "failed to authenticate using "
518                                         "publickey authentication");
519             goto out;
520         } else if (r == SSH_AUTH_SUCCESS) {
521             /* Authenticated! */
522             ret = 0;
523             goto out;
524         }
525     }
526 
527     ret = -EPERM;
528     error_setg(errp, "failed to authenticate using publickey authentication "
529                "and the identities held by your ssh-agent");
530 
531  out:
532     return ret;
533 }
534 
535 static QemuOptsList ssh_runtime_opts = {
536     .name = "ssh",
537     .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
538     .desc = {
539         {
540             .name = "host",
541             .type = QEMU_OPT_STRING,
542             .help = "Host to connect to",
543         },
544         {
545             .name = "port",
546             .type = QEMU_OPT_NUMBER,
547             .help = "Port to connect to",
548         },
549         {
550             .name = "host_key_check",
551             .type = QEMU_OPT_STRING,
552             .help = "Defines how and what to check the host key against",
553         },
554         { /* end of list */ }
555     },
556 };
557 
558 static bool ssh_process_legacy_options(QDict *output_opts,
559                                        QemuOpts *legacy_opts,
560                                        Error **errp)
561 {
562     const char *host = qemu_opt_get(legacy_opts, "host");
563     const char *port = qemu_opt_get(legacy_opts, "port");
564     const char *host_key_check = qemu_opt_get(legacy_opts, "host_key_check");
565 
566     if (!host && port) {
567         error_setg(errp, "port may not be used without host");
568         return false;
569     }
570 
571     if (host) {
572         qdict_put_str(output_opts, "server.host", host);
573         qdict_put_str(output_opts, "server.port", port ?: stringify(22));
574     }
575 
576     if (host_key_check) {
577         if (strcmp(host_key_check, "no") == 0) {
578             qdict_put_str(output_opts, "host-key-check.mode", "none");
579         } else if (strncmp(host_key_check, "md5:", 4) == 0) {
580             qdict_put_str(output_opts, "host-key-check.mode", "hash");
581             qdict_put_str(output_opts, "host-key-check.type", "md5");
582             qdict_put_str(output_opts, "host-key-check.hash",
583                           &host_key_check[4]);
584         } else if (strncmp(host_key_check, "sha1:", 5) == 0) {
585             qdict_put_str(output_opts, "host-key-check.mode", "hash");
586             qdict_put_str(output_opts, "host-key-check.type", "sha1");
587             qdict_put_str(output_opts, "host-key-check.hash",
588                           &host_key_check[5]);
589         } else if (strncmp(host_key_check, "sha256:", 7) == 0) {
590             qdict_put_str(output_opts, "host-key-check.mode", "hash");
591             qdict_put_str(output_opts, "host-key-check.type", "sha256");
592             qdict_put_str(output_opts, "host-key-check.hash",
593                           &host_key_check[7]);
594         } else if (strcmp(host_key_check, "yes") == 0) {
595             qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
596         } else {
597             error_setg(errp, "unknown host_key_check setting (%s)",
598                        host_key_check);
599             return false;
600         }
601     }
602 
603     return true;
604 }
605 
606 static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
607 {
608     BlockdevOptionsSsh *result = NULL;
609     QemuOpts *opts = NULL;
610     const QDictEntry *e;
611     Visitor *v;
612 
613     /* Translate legacy options */
614     opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
615     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
616         goto fail;
617     }
618 
619     if (!ssh_process_legacy_options(options, opts, errp)) {
620         goto fail;
621     }
622 
623     /* Create the QAPI object */
624     v = qobject_input_visitor_new_flat_confused(options, errp);
625     if (!v) {
626         goto fail;
627     }
628 
629     visit_type_BlockdevOptionsSsh(v, NULL, &result, errp);
630     visit_free(v);
631     if (!result) {
632         goto fail;
633     }
634 
635     /* Remove the processed options from the QDict (the visitor processes
636      * _all_ options in the QDict) */
637     while ((e = qdict_first(options))) {
638         qdict_del(options, e->key);
639     }
640 
641 fail:
642     qemu_opts_del(opts);
643     return result;
644 }
645 
646 static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
647                           int ssh_flags, int creat_mode, Error **errp)
648 {
649     int r, ret;
650     unsigned int port = 0;
651     int new_sock = -1;
652 
653     if (opts->user) {
654         s->user = g_strdup(opts->user);
655     } else {
656         s->user = g_strdup(g_get_user_name());
657         if (!s->user) {
658             error_setg_errno(errp, errno, "Can't get user name");
659             ret = -errno;
660             goto err;
661         }
662     }
663 
664     /* Pop the config into our state object, Exit if invalid */
665     s->inet = opts->server;
666     opts->server = NULL;
667 
668     if (qemu_strtoui(s->inet->port, NULL, 10, &port) < 0) {
669         error_setg(errp, "Use only numeric port value");
670         ret = -EINVAL;
671         goto err;
672     }
673 
674     /* Open the socket and connect. */
675     new_sock = inet_connect_saddr(s->inet, errp);
676     if (new_sock < 0) {
677         ret = -EIO;
678         goto err;
679     }
680 
681     /*
682      * Try to disable the Nagle algorithm on TCP sockets to reduce latency,
683      * but do not fail if it cannot be disabled.
684      */
685     r = socket_set_nodelay(new_sock);
686     if (r < 0) {
687         warn_report("can't set TCP_NODELAY for the ssh server %s: %s",
688                     s->inet->host, strerror(errno));
689     }
690 
691     /* Create SSH session. */
692     s->session = ssh_new();
693     if (!s->session) {
694         ret = -EINVAL;
695         session_error_setg(errp, s, "failed to initialize libssh session");
696         goto err;
697     }
698 
699     /*
700      * Make sure we are in blocking mode during the connection and
701      * authentication phases.
702      */
703     ssh_set_blocking(s->session, 1);
704 
705     r = ssh_options_set(s->session, SSH_OPTIONS_USER, s->user);
706     if (r < 0) {
707         ret = -EINVAL;
708         session_error_setg(errp, s,
709                            "failed to set the user in the libssh session");
710         goto err;
711     }
712 
713     r = ssh_options_set(s->session, SSH_OPTIONS_HOST, s->inet->host);
714     if (r < 0) {
715         ret = -EINVAL;
716         session_error_setg(errp, s,
717                            "failed to set the host in the libssh session");
718         goto err;
719     }
720 
721     if (port > 0) {
722         r = ssh_options_set(s->session, SSH_OPTIONS_PORT, &port);
723         if (r < 0) {
724             ret = -EINVAL;
725             session_error_setg(errp, s,
726                                "failed to set the port in the libssh session");
727             goto err;
728         }
729     }
730 
731     r = ssh_options_set(s->session, SSH_OPTIONS_COMPRESSION, "none");
732     if (r < 0) {
733         ret = -EINVAL;
734         session_error_setg(errp, s,
735                            "failed to disable the compression in the libssh "
736                            "session");
737         goto err;
738     }
739 
740     /* Read ~/.ssh/config. */
741     r = ssh_options_parse_config(s->session, NULL);
742     if (r < 0) {
743         ret = -EINVAL;
744         session_error_setg(errp, s, "failed to parse ~/.ssh/config");
745         goto err;
746     }
747 
748     r = ssh_options_set(s->session, SSH_OPTIONS_FD, &new_sock);
749     if (r < 0) {
750         ret = -EINVAL;
751         session_error_setg(errp, s,
752                            "failed to set the socket in the libssh session");
753         goto err;
754     }
755     /* libssh took ownership of the socket. */
756     s->sock = new_sock;
757     new_sock = -1;
758 
759     /* Connect. */
760     r = ssh_connect(s->session);
761     if (r != SSH_OK) {
762         ret = -EINVAL;
763         session_error_setg(errp, s, "failed to establish SSH session");
764         goto err;
765     }
766 
767     /* Check the remote host's key against known_hosts. */
768     ret = check_host_key(s, opts->host_key_check, errp);
769     if (ret < 0) {
770         goto err;
771     }
772 
773     /* Authenticate. */
774     ret = authenticate(s, errp);
775     if (ret < 0) {
776         goto err;
777     }
778 
779     /* Start SFTP. */
780     s->sftp = sftp_new(s->session);
781     if (!s->sftp) {
782         session_error_setg(errp, s, "failed to create sftp handle");
783         ret = -EINVAL;
784         goto err;
785     }
786 
787     r = sftp_init(s->sftp);
788     if (r < 0) {
789         sftp_error_setg(errp, s, "failed to initialize sftp handle");
790         ret = -EINVAL;
791         goto err;
792     }
793 
794     /* Open the remote file. */
795     trace_ssh_connect_to_ssh(opts->path, ssh_flags, creat_mode);
796     s->sftp_handle = sftp_open(s->sftp, opts->path, ssh_flags, creat_mode);
797     if (!s->sftp_handle) {
798         sftp_error_setg(errp, s, "failed to open remote file '%s'",
799                         opts->path);
800         ret = -EINVAL;
801         goto err;
802     }
803 
804     /* Make sure the SFTP file is handled in blocking mode. */
805     sftp_file_set_blocking(s->sftp_handle);
806 
807     s->attrs = sftp_fstat(s->sftp_handle);
808     if (!s->attrs) {
809         sftp_error_setg(errp, s, "failed to read file attributes");
810         return -EINVAL;
811     }
812 
813     return 0;
814 
815  err:
816     if (s->attrs) {
817         sftp_attributes_free(s->attrs);
818     }
819     s->attrs = NULL;
820     if (s->sftp_handle) {
821         sftp_close(s->sftp_handle);
822     }
823     s->sftp_handle = NULL;
824     if (s->sftp) {
825         sftp_free(s->sftp);
826     }
827     s->sftp = NULL;
828     if (s->session) {
829         ssh_disconnect(s->session);
830         ssh_free(s->session);
831     }
832     s->session = NULL;
833     s->sock = -1;
834     if (new_sock >= 0) {
835         close(new_sock);
836     }
837 
838     return ret;
839 }
840 
841 static int ssh_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
842                     Error **errp)
843 {
844     BDRVSSHState *s = bs->opaque;
845     BlockdevOptionsSsh *opts;
846     int ret;
847     int ssh_flags;
848 
849     ssh_state_init(s);
850 
851     ssh_flags = 0;
852     if (bdrv_flags & BDRV_O_RDWR) {
853         ssh_flags |= O_RDWR;
854     } else {
855         ssh_flags |= O_RDONLY;
856     }
857 
858     opts = ssh_parse_options(options, errp);
859     if (opts == NULL) {
860         return -EINVAL;
861     }
862 
863     /* Start up SSH. */
864     ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
865     if (ret < 0) {
866         goto err;
867     }
868 
869     /* Go non-blocking. */
870     ssh_set_blocking(s->session, 0);
871 
872     if (s->attrs->type == SSH_FILEXFER_TYPE_REGULAR) {
873         bs->supported_truncate_flags = BDRV_REQ_ZERO_WRITE;
874     }
875 
876     qapi_free_BlockdevOptionsSsh(opts);
877 
878     return 0;
879 
880  err:
881     qapi_free_BlockdevOptionsSsh(opts);
882 
883     return ret;
884 }
885 
886 /* Note: This is a blocking operation */
887 static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
888 {
889     ssize_t ret;
890     char c[1] = { '\0' };
891     int was_blocking = ssh_is_blocking(s->session);
892 
893     /* offset must be strictly greater than the current size so we do
894      * not overwrite anything */
895     assert(offset > 0 && offset > s->attrs->size);
896 
897     ssh_set_blocking(s->session, 1);
898 
899     sftp_seek64(s->sftp_handle, offset - 1);
900     ret = sftp_write(s->sftp_handle, c, 1);
901 
902     ssh_set_blocking(s->session, was_blocking);
903 
904     if (ret < 0) {
905         sftp_error_setg(errp, s, "Failed to grow file");
906         return -EIO;
907     }
908 
909     s->attrs->size = offset;
910     return 0;
911 }
912 
913 static QemuOptsList ssh_create_opts = {
914     .name = "ssh-create-opts",
915     .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
916     .desc = {
917         {
918             .name = BLOCK_OPT_SIZE,
919             .type = QEMU_OPT_SIZE,
920             .help = "Virtual disk size"
921         },
922         { /* end of list */ }
923     }
924 };
925 
926 static int ssh_co_create(BlockdevCreateOptions *options, Error **errp)
927 {
928     BlockdevCreateOptionsSsh *opts = &options->u.ssh;
929     BDRVSSHState s;
930     int ret;
931 
932     assert(options->driver == BLOCKDEV_DRIVER_SSH);
933 
934     ssh_state_init(&s);
935 
936     ret = connect_to_ssh(&s, opts->location,
937                          O_RDWR | O_CREAT | O_TRUNC,
938                          0644, errp);
939     if (ret < 0) {
940         goto fail;
941     }
942 
943     if (opts->size > 0) {
944         ret = ssh_grow_file(&s, opts->size, errp);
945         if (ret < 0) {
946             goto fail;
947         }
948     }
949 
950     ret = 0;
951 fail:
952     ssh_state_free(&s);
953     return ret;
954 }
955 
956 static int coroutine_fn ssh_co_create_opts(BlockDriver *drv,
957                                            const char *filename,
958                                            QemuOpts *opts,
959                                            Error **errp)
960 {
961     BlockdevCreateOptions *create_options;
962     BlockdevCreateOptionsSsh *ssh_opts;
963     int ret;
964     QDict *uri_options = NULL;
965 
966     create_options = g_new0(BlockdevCreateOptions, 1);
967     create_options->driver = BLOCKDEV_DRIVER_SSH;
968     ssh_opts = &create_options->u.ssh;
969 
970     /* Get desired file size. */
971     ssh_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
972                               BDRV_SECTOR_SIZE);
973     trace_ssh_co_create_opts(ssh_opts->size);
974 
975     uri_options = qdict_new();
976     ret = parse_uri(filename, uri_options, errp);
977     if (ret < 0) {
978         goto out;
979     }
980 
981     ssh_opts->location = ssh_parse_options(uri_options, errp);
982     if (ssh_opts->location == NULL) {
983         ret = -EINVAL;
984         goto out;
985     }
986 
987     ret = ssh_co_create(create_options, errp);
988 
989  out:
990     qobject_unref(uri_options);
991     qapi_free_BlockdevCreateOptions(create_options);
992     return ret;
993 }
994 
995 static void ssh_close(BlockDriverState *bs)
996 {
997     BDRVSSHState *s = bs->opaque;
998 
999     ssh_state_free(s);
1000 }
1001 
1002 static int ssh_has_zero_init(BlockDriverState *bs)
1003 {
1004     BDRVSSHState *s = bs->opaque;
1005     /* Assume false, unless we can positively prove it's true. */
1006     int has_zero_init = 0;
1007 
1008     if (s->attrs->type == SSH_FILEXFER_TYPE_REGULAR) {
1009         has_zero_init = 1;
1010     }
1011 
1012     return has_zero_init;
1013 }
1014 
1015 typedef struct BDRVSSHRestart {
1016     BlockDriverState *bs;
1017     Coroutine *co;
1018 } BDRVSSHRestart;
1019 
1020 static void restart_coroutine(void *opaque)
1021 {
1022     BDRVSSHRestart *restart = opaque;
1023     BlockDriverState *bs = restart->bs;
1024     BDRVSSHState *s = bs->opaque;
1025     AioContext *ctx = bdrv_get_aio_context(bs);
1026 
1027     trace_ssh_restart_coroutine(restart->co);
1028     aio_set_fd_handler(ctx, s->sock, NULL, NULL, NULL, NULL, NULL);
1029 
1030     aio_co_wake(restart->co);
1031 }
1032 
1033 /* A non-blocking call returned EAGAIN, so yield, ensuring the
1034  * handlers are set up so that we'll be rescheduled when there is an
1035  * interesting event on the socket.
1036  */
1037 static coroutine_fn void co_yield(BDRVSSHState *s, BlockDriverState *bs)
1038 {
1039     int r;
1040     IOHandler *rd_handler = NULL, *wr_handler = NULL;
1041     BDRVSSHRestart restart = {
1042         .bs = bs,
1043         .co = qemu_coroutine_self()
1044     };
1045 
1046     r = ssh_get_poll_flags(s->session);
1047 
1048     if (r & SSH_READ_PENDING) {
1049         rd_handler = restart_coroutine;
1050     }
1051     if (r & SSH_WRITE_PENDING) {
1052         wr_handler = restart_coroutine;
1053     }
1054 
1055     trace_ssh_co_yield(s->sock, rd_handler, wr_handler);
1056 
1057     aio_set_fd_handler(bdrv_get_aio_context(bs), s->sock,
1058                        rd_handler, wr_handler, NULL, NULL, &restart);
1059     qemu_coroutine_yield();
1060     trace_ssh_co_yield_back(s->sock);
1061 }
1062 
1063 static coroutine_fn int ssh_read(BDRVSSHState *s, BlockDriverState *bs,
1064                                  int64_t offset, size_t size,
1065                                  QEMUIOVector *qiov)
1066 {
1067     ssize_t r;
1068     size_t got;
1069     char *buf, *end_of_vec;
1070     struct iovec *i;
1071 
1072     trace_ssh_read(offset, size);
1073 
1074     trace_ssh_seek(offset);
1075     sftp_seek64(s->sftp_handle, offset);
1076 
1077     /* This keeps track of the current iovec element ('i'), where we
1078      * will write to next ('buf'), and the end of the current iovec
1079      * ('end_of_vec').
1080      */
1081     i = &qiov->iov[0];
1082     buf = i->iov_base;
1083     end_of_vec = i->iov_base + i->iov_len;
1084 
1085     for (got = 0; got < size; ) {
1086         size_t request_read_size;
1087     again:
1088         /*
1089          * The size of SFTP packets is limited to 32K bytes, so limit
1090          * the amount of data requested to 16K, as libssh currently
1091          * does not handle multiple requests on its own.
1092          */
1093         request_read_size = MIN(end_of_vec - buf, 16384);
1094         trace_ssh_read_buf(buf, end_of_vec - buf, request_read_size);
1095         r = sftp_read(s->sftp_handle, buf, request_read_size);
1096         trace_ssh_read_return(r, sftp_get_error(s->sftp));
1097 
1098         if (r == SSH_AGAIN) {
1099             co_yield(s, bs);
1100             goto again;
1101         }
1102         if (r == SSH_EOF || (r == 0 && sftp_get_error(s->sftp) == SSH_FX_EOF)) {
1103             /* EOF: Short read so pad the buffer with zeroes and return it. */
1104             qemu_iovec_memset(qiov, got, 0, size - got);
1105             return 0;
1106         }
1107         if (r <= 0) {
1108             sftp_error_trace(s, "read");
1109             return -EIO;
1110         }
1111 
1112         got += r;
1113         buf += r;
1114         if (buf >= end_of_vec && got < size) {
1115             i++;
1116             buf = i->iov_base;
1117             end_of_vec = i->iov_base + i->iov_len;
1118         }
1119     }
1120 
1121     return 0;
1122 }
1123 
1124 static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1125                                      int64_t sector_num,
1126                                      int nb_sectors, QEMUIOVector *qiov)
1127 {
1128     BDRVSSHState *s = bs->opaque;
1129     int ret;
1130 
1131     qemu_co_mutex_lock(&s->lock);
1132     ret = ssh_read(s, bs, sector_num * BDRV_SECTOR_SIZE,
1133                    nb_sectors * BDRV_SECTOR_SIZE, qiov);
1134     qemu_co_mutex_unlock(&s->lock);
1135 
1136     return ret;
1137 }
1138 
1139 static coroutine_fn int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1140                                   int64_t offset, size_t size,
1141                                   QEMUIOVector *qiov)
1142 {
1143     ssize_t r;
1144     size_t written;
1145     char *buf, *end_of_vec;
1146     struct iovec *i;
1147 
1148     trace_ssh_write(offset, size);
1149 
1150     trace_ssh_seek(offset);
1151     sftp_seek64(s->sftp_handle, offset);
1152 
1153     /* This keeps track of the current iovec element ('i'), where we
1154      * will read from next ('buf'), and the end of the current iovec
1155      * ('end_of_vec').
1156      */
1157     i = &qiov->iov[0];
1158     buf = i->iov_base;
1159     end_of_vec = i->iov_base + i->iov_len;
1160 
1161     for (written = 0; written < size; ) {
1162         size_t request_write_size;
1163     again:
1164         /*
1165          * Avoid too large data packets, as libssh currently does not
1166          * handle multiple requests on its own.
1167          */
1168         request_write_size = MIN(end_of_vec - buf, 131072);
1169         trace_ssh_write_buf(buf, end_of_vec - buf, request_write_size);
1170         r = sftp_write(s->sftp_handle, buf, request_write_size);
1171         trace_ssh_write_return(r, sftp_get_error(s->sftp));
1172 
1173         if (r == SSH_AGAIN) {
1174             co_yield(s, bs);
1175             goto again;
1176         }
1177         if (r < 0) {
1178             sftp_error_trace(s, "write");
1179             return -EIO;
1180         }
1181 
1182         written += r;
1183         buf += r;
1184         if (buf >= end_of_vec && written < size) {
1185             i++;
1186             buf = i->iov_base;
1187             end_of_vec = i->iov_base + i->iov_len;
1188         }
1189 
1190         if (offset + written > s->attrs->size) {
1191             s->attrs->size = offset + written;
1192         }
1193     }
1194 
1195     return 0;
1196 }
1197 
1198 static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1199                                       int64_t sector_num,
1200                                       int nb_sectors, QEMUIOVector *qiov,
1201                                       int flags)
1202 {
1203     BDRVSSHState *s = bs->opaque;
1204     int ret;
1205 
1206     qemu_co_mutex_lock(&s->lock);
1207     ret = ssh_write(s, bs, sector_num * BDRV_SECTOR_SIZE,
1208                     nb_sectors * BDRV_SECTOR_SIZE, qiov);
1209     qemu_co_mutex_unlock(&s->lock);
1210 
1211     return ret;
1212 }
1213 
1214 static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1215 {
1216     if (!s->unsafe_flush_warning) {
1217         warn_report("ssh server %s does not support fsync",
1218                     s->inet->host);
1219         if (what) {
1220             error_report("to support fsync, you need %s", what);
1221         }
1222         s->unsafe_flush_warning = true;
1223     }
1224 }
1225 
1226 static coroutine_fn int ssh_flush(BDRVSSHState *s, BlockDriverState *bs)
1227 {
1228     int r;
1229 
1230     trace_ssh_flush();
1231 
1232     if (!sftp_extension_supported(s->sftp, "fsync@openssh.com", "1")) {
1233         unsafe_flush_warning(s, "OpenSSH >= 6.3");
1234         return 0;
1235     }
1236  again:
1237     r = sftp_fsync(s->sftp_handle);
1238     if (r == SSH_AGAIN) {
1239         co_yield(s, bs);
1240         goto again;
1241     }
1242     if (r < 0) {
1243         sftp_error_trace(s, "fsync");
1244         return -EIO;
1245     }
1246 
1247     return 0;
1248 }
1249 
1250 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1251 {
1252     BDRVSSHState *s = bs->opaque;
1253     int ret;
1254 
1255     qemu_co_mutex_lock(&s->lock);
1256     ret = ssh_flush(s, bs);
1257     qemu_co_mutex_unlock(&s->lock);
1258 
1259     return ret;
1260 }
1261 
1262 static int64_t coroutine_fn ssh_co_getlength(BlockDriverState *bs)
1263 {
1264     BDRVSSHState *s = bs->opaque;
1265     int64_t length;
1266 
1267     /* Note we cannot make a libssh call here. */
1268     length = (int64_t) s->attrs->size;
1269     trace_ssh_getlength(length);
1270 
1271     return length;
1272 }
1273 
1274 static int coroutine_fn ssh_co_truncate(BlockDriverState *bs, int64_t offset,
1275                                         bool exact, PreallocMode prealloc,
1276                                         BdrvRequestFlags flags, Error **errp)
1277 {
1278     BDRVSSHState *s = bs->opaque;
1279 
1280     if (prealloc != PREALLOC_MODE_OFF) {
1281         error_setg(errp, "Unsupported preallocation mode '%s'",
1282                    PreallocMode_str(prealloc));
1283         return -ENOTSUP;
1284     }
1285 
1286     if (offset < s->attrs->size) {
1287         error_setg(errp, "ssh driver does not support shrinking files");
1288         return -ENOTSUP;
1289     }
1290 
1291     if (offset == s->attrs->size) {
1292         return 0;
1293     }
1294 
1295     return ssh_grow_file(s, offset, errp);
1296 }
1297 
1298 static void ssh_refresh_filename(BlockDriverState *bs)
1299 {
1300     BDRVSSHState *s = bs->opaque;
1301     const char *path, *host_key_check;
1302     int ret;
1303 
1304     /*
1305      * None of these options can be represented in a plain "host:port"
1306      * format, so if any was given, we have to abort.
1307      */
1308     if (s->inet->has_ipv4 || s->inet->has_ipv6 || s->inet->has_to ||
1309         s->inet->has_numeric)
1310     {
1311         return;
1312     }
1313 
1314     path = qdict_get_try_str(bs->full_open_options, "path");
1315     assert(path); /* mandatory option */
1316 
1317     host_key_check = qdict_get_try_str(bs->full_open_options, "host_key_check");
1318 
1319     ret = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1320                    "ssh://%s@%s:%s%s%s%s",
1321                    s->user, s->inet->host, s->inet->port, path,
1322                    host_key_check ? "?host_key_check=" : "",
1323                    host_key_check ?: "");
1324     if (ret >= sizeof(bs->exact_filename)) {
1325         /* An overflow makes the filename unusable, so do not report any */
1326         bs->exact_filename[0] = '\0';
1327     }
1328 }
1329 
1330 static char *ssh_bdrv_dirname(BlockDriverState *bs, Error **errp)
1331 {
1332     if (qdict_haskey(bs->full_open_options, "host_key_check")) {
1333         /*
1334          * We cannot generate a simple prefix if we would have to
1335          * append a query string.
1336          */
1337         error_setg(errp,
1338                    "Cannot generate a base directory with host_key_check set");
1339         return NULL;
1340     }
1341 
1342     if (bs->exact_filename[0] == '\0') {
1343         error_setg(errp, "Cannot generate a base directory for this ssh node");
1344         return NULL;
1345     }
1346 
1347     return path_combine(bs->exact_filename, "");
1348 }
1349 
1350 static const char *const ssh_strong_runtime_opts[] = {
1351     "host",
1352     "port",
1353     "path",
1354     "user",
1355     "host_key_check",
1356     "server.",
1357 
1358     NULL
1359 };
1360 
1361 static BlockDriver bdrv_ssh = {
1362     .format_name                  = "ssh",
1363     .protocol_name                = "ssh",
1364     .instance_size                = sizeof(BDRVSSHState),
1365     .bdrv_parse_filename          = ssh_parse_filename,
1366     .bdrv_open                    = ssh_open,
1367     .bdrv_co_create               = ssh_co_create,
1368     .bdrv_co_create_opts          = ssh_co_create_opts,
1369     .bdrv_close                   = ssh_close,
1370     .bdrv_has_zero_init           = ssh_has_zero_init,
1371     .bdrv_co_readv                = ssh_co_readv,
1372     .bdrv_co_writev               = ssh_co_writev,
1373     .bdrv_co_getlength            = ssh_co_getlength,
1374     .bdrv_co_truncate             = ssh_co_truncate,
1375     .bdrv_co_flush_to_disk        = ssh_co_flush,
1376     .bdrv_refresh_filename        = ssh_refresh_filename,
1377     .bdrv_dirname                 = ssh_bdrv_dirname,
1378     .create_opts                  = &ssh_create_opts,
1379     .strong_runtime_opts          = ssh_strong_runtime_opts,
1380 };
1381 
1382 static void bdrv_ssh_init(void)
1383 {
1384     int r;
1385 
1386     r = ssh_init();
1387     if (r != 0) {
1388         fprintf(stderr, "libssh initialization failed, %d\n", r);
1389         exit(EXIT_FAILURE);
1390     }
1391 
1392 #if TRACE_LIBSSH != 0
1393     ssh_set_log_level(TRACE_LIBSSH);
1394 #endif
1395 
1396     bdrv_register(&bdrv_ssh);
1397 }
1398 
1399 block_init(bdrv_ssh_init);
1400