xref: /openbmc/qemu/block/ssh.c (revision 500eb6db)
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 <libssh2.h>
28 #include <libssh2_sftp.h>
29 
30 #include "block/block_int.h"
31 #include "block/qdict.h"
32 #include "qapi/error.h"
33 #include "qemu/error-report.h"
34 #include "qemu/module.h"
35 #include "qemu/option.h"
36 #include "qemu/ctype.h"
37 #include "qemu/cutils.h"
38 #include "qemu/sockets.h"
39 #include "qemu/uri.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_LIBSSH2=<bitmask> enables tracing in libssh2 itself.  Note
50  * that this requires that libssh2 was specially compiled with the
51  * `./configure --enable-debug' option, so most likely you will have
52  * to compile it yourself.  The meaning of <bitmask> is described
53  * here: http://www.libssh2.org/libssh2_trace.html
54  */
55 #define TRACE_LIBSSH2 0 /* or try: LIBSSH2_TRACE_SFTP */
56 
57 typedef struct BDRVSSHState {
58     /* Coroutine. */
59     CoMutex lock;
60 
61     /* SSH connection. */
62     int sock;                         /* socket */
63     LIBSSH2_SESSION *session;         /* ssh session */
64     LIBSSH2_SFTP *sftp;               /* sftp session */
65     LIBSSH2_SFTP_HANDLE *sftp_handle; /* sftp remote file handle */
66 
67     /* See ssh_seek() function below. */
68     int64_t offset;
69     bool offset_op_read;
70 
71     /* File attributes at open.  We try to keep the .filesize field
72      * updated if it changes (eg by writing at the end of the file).
73      */
74     LIBSSH2_SFTP_ATTRIBUTES attrs;
75 
76     InetSocketAddress *inet;
77 
78     /* Used to warn if 'flush' is not supported. */
79     bool unsafe_flush_warning;
80 
81     /*
82      * Store the user name for ssh_refresh_filename() because the
83      * default depends on the system you are on -- therefore, when we
84      * generate a filename, it should always contain the user name we
85      * are actually using.
86      */
87     char *user;
88 } BDRVSSHState;
89 
90 static void ssh_state_init(BDRVSSHState *s)
91 {
92     memset(s, 0, sizeof *s);
93     s->sock = -1;
94     s->offset = -1;
95     qemu_co_mutex_init(&s->lock);
96 }
97 
98 static void ssh_state_free(BDRVSSHState *s)
99 {
100     g_free(s->user);
101 
102     if (s->sftp_handle) {
103         libssh2_sftp_close(s->sftp_handle);
104     }
105     if (s->sftp) {
106         libssh2_sftp_shutdown(s->sftp);
107     }
108     if (s->session) {
109         libssh2_session_disconnect(s->session,
110                                    "from qemu ssh client: "
111                                    "user closed the connection");
112         libssh2_session_free(s->session);
113     }
114     if (s->sock >= 0) {
115         close(s->sock);
116     }
117 }
118 
119 static void GCC_FMT_ATTR(3, 4)
120 session_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
121 {
122     va_list args;
123     char *msg;
124 
125     va_start(args, fs);
126     msg = g_strdup_vprintf(fs, args);
127     va_end(args);
128 
129     if (s->session) {
130         char *ssh_err;
131         int ssh_err_code;
132 
133         /* This is not an errno.  See <libssh2.h>. */
134         ssh_err_code = libssh2_session_last_error(s->session,
135                                                   &ssh_err, NULL, 0);
136         error_setg(errp, "%s: %s (libssh2 error code: %d)",
137                    msg, ssh_err, ssh_err_code);
138     } else {
139         error_setg(errp, "%s", msg);
140     }
141     g_free(msg);
142 }
143 
144 static void GCC_FMT_ATTR(3, 4)
145 sftp_error_setg(Error **errp, BDRVSSHState *s, const char *fs, ...)
146 {
147     va_list args;
148     char *msg;
149 
150     va_start(args, fs);
151     msg = g_strdup_vprintf(fs, args);
152     va_end(args);
153 
154     if (s->sftp) {
155         char *ssh_err;
156         int ssh_err_code;
157         unsigned long sftp_err_code;
158 
159         /* This is not an errno.  See <libssh2.h>. */
160         ssh_err_code = libssh2_session_last_error(s->session,
161                                                   &ssh_err, NULL, 0);
162         /* See <libssh2_sftp.h>. */
163         sftp_err_code = libssh2_sftp_last_error((s)->sftp);
164 
165         error_setg(errp,
166                    "%s: %s (libssh2 error code: %d, sftp error code: %lu)",
167                    msg, ssh_err, ssh_err_code, sftp_err_code);
168     } else {
169         error_setg(errp, "%s", msg);
170     }
171     g_free(msg);
172 }
173 
174 static void sftp_error_trace(BDRVSSHState *s, const char *op)
175 {
176     char *ssh_err;
177     int ssh_err_code;
178     unsigned long sftp_err_code;
179 
180     /* This is not an errno.  See <libssh2.h>. */
181     ssh_err_code = libssh2_session_last_error(s->session,
182                                               &ssh_err, NULL, 0);
183     /* See <libssh2_sftp.h>. */
184     sftp_err_code = libssh2_sftp_last_error((s)->sftp);
185 
186     trace_sftp_error(op, ssh_err, ssh_err_code, sftp_err_code);
187 }
188 
189 static int parse_uri(const char *filename, QDict *options, Error **errp)
190 {
191     URI *uri = NULL;
192     QueryParams *qp;
193     char *port_str;
194     int i;
195 
196     uri = uri_parse(filename);
197     if (!uri) {
198         return -EINVAL;
199     }
200 
201     if (g_strcmp0(uri->scheme, "ssh") != 0) {
202         error_setg(errp, "URI scheme must be 'ssh'");
203         goto err;
204     }
205 
206     if (!uri->server || strcmp(uri->server, "") == 0) {
207         error_setg(errp, "missing hostname in URI");
208         goto err;
209     }
210 
211     if (!uri->path || strcmp(uri->path, "") == 0) {
212         error_setg(errp, "missing remote path in URI");
213         goto err;
214     }
215 
216     qp = query_params_parse(uri->query);
217     if (!qp) {
218         error_setg(errp, "could not parse query parameters");
219         goto err;
220     }
221 
222     if(uri->user && strcmp(uri->user, "") != 0) {
223         qdict_put_str(options, "user", uri->user);
224     }
225 
226     qdict_put_str(options, "server.host", uri->server);
227 
228     port_str = g_strdup_printf("%d", uri->port ?: 22);
229     qdict_put_str(options, "server.port", port_str);
230     g_free(port_str);
231 
232     qdict_put_str(options, "path", uri->path);
233 
234     /* Pick out any query parameters that we understand, and ignore
235      * the rest.
236      */
237     for (i = 0; i < qp->n; ++i) {
238         if (strcmp(qp->p[i].name, "host_key_check") == 0) {
239             qdict_put_str(options, "host_key_check", qp->p[i].value);
240         }
241     }
242 
243     query_params_free(qp);
244     uri_free(uri);
245     return 0;
246 
247  err:
248     if (uri) {
249       uri_free(uri);
250     }
251     return -EINVAL;
252 }
253 
254 static bool ssh_has_filename_options_conflict(QDict *options, Error **errp)
255 {
256     const QDictEntry *qe;
257 
258     for (qe = qdict_first(options); qe; qe = qdict_next(options, qe)) {
259         if (!strcmp(qe->key, "host") ||
260             !strcmp(qe->key, "port") ||
261             !strcmp(qe->key, "path") ||
262             !strcmp(qe->key, "user") ||
263             !strcmp(qe->key, "host_key_check") ||
264             strstart(qe->key, "server.", NULL))
265         {
266             error_setg(errp, "Option '%s' cannot be used with a file name",
267                        qe->key);
268             return true;
269         }
270     }
271 
272     return false;
273 }
274 
275 static void ssh_parse_filename(const char *filename, QDict *options,
276                                Error **errp)
277 {
278     if (ssh_has_filename_options_conflict(options, errp)) {
279         return;
280     }
281 
282     parse_uri(filename, options, errp);
283 }
284 
285 static int check_host_key_knownhosts(BDRVSSHState *s,
286                                      const char *host, int port, Error **errp)
287 {
288     const char *home;
289     char *knh_file = NULL;
290     LIBSSH2_KNOWNHOSTS *knh = NULL;
291     struct libssh2_knownhost *found;
292     int ret, r;
293     const char *hostkey;
294     size_t len;
295     int type;
296 
297     hostkey = libssh2_session_hostkey(s->session, &len, &type);
298     if (!hostkey) {
299         ret = -EINVAL;
300         session_error_setg(errp, s, "failed to read remote host key");
301         goto out;
302     }
303 
304     knh = libssh2_knownhost_init(s->session);
305     if (!knh) {
306         ret = -EINVAL;
307         session_error_setg(errp, s,
308                            "failed to initialize known hosts support");
309         goto out;
310     }
311 
312     home = getenv("HOME");
313     if (home) {
314         knh_file = g_strdup_printf("%s/.ssh/known_hosts", home);
315     } else {
316         knh_file = g_strdup_printf("/root/.ssh/known_hosts");
317     }
318 
319     /* Read all known hosts from OpenSSH-style known_hosts file. */
320     libssh2_knownhost_readfile(knh, knh_file, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
321 
322     r = libssh2_knownhost_checkp(knh, host, port, hostkey, len,
323                                  LIBSSH2_KNOWNHOST_TYPE_PLAIN|
324                                  LIBSSH2_KNOWNHOST_KEYENC_RAW,
325                                  &found);
326     switch (r) {
327     case LIBSSH2_KNOWNHOST_CHECK_MATCH:
328         /* OK */
329         trace_ssh_check_host_key_knownhosts(found->key);
330         break;
331     case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:
332         ret = -EINVAL;
333         session_error_setg(errp, s,
334                       "host key does not match the one in known_hosts"
335                       " (found key %s)", found->key);
336         goto out;
337     case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND:
338         ret = -EINVAL;
339         session_error_setg(errp, s, "no host key was found in known_hosts");
340         goto out;
341     case LIBSSH2_KNOWNHOST_CHECK_FAILURE:
342         ret = -EINVAL;
343         session_error_setg(errp, s,
344                       "failure matching the host key with known_hosts");
345         goto out;
346     default:
347         ret = -EINVAL;
348         session_error_setg(errp, s, "unknown error matching the host key"
349                       " with known_hosts (%d)", r);
350         goto out;
351     }
352 
353     /* known_hosts checking successful. */
354     ret = 0;
355 
356  out:
357     if (knh != NULL) {
358         libssh2_knownhost_free(knh);
359     }
360     g_free(knh_file);
361     return ret;
362 }
363 
364 static unsigned hex2decimal(char ch)
365 {
366     if (ch >= '0' && ch <= '9') {
367         return (ch - '0');
368     } else if (ch >= 'a' && ch <= 'f') {
369         return 10 + (ch - 'a');
370     } else if (ch >= 'A' && ch <= 'F') {
371         return 10 + (ch - 'A');
372     }
373 
374     return -1;
375 }
376 
377 /* Compare the binary fingerprint (hash of host key) with the
378  * host_key_check parameter.
379  */
380 static int compare_fingerprint(const unsigned char *fingerprint, size_t len,
381                                const char *host_key_check)
382 {
383     unsigned c;
384 
385     while (len > 0) {
386         while (*host_key_check == ':')
387             host_key_check++;
388         if (!qemu_isxdigit(host_key_check[0]) ||
389             !qemu_isxdigit(host_key_check[1]))
390             return 1;
391         c = hex2decimal(host_key_check[0]) * 16 +
392             hex2decimal(host_key_check[1]);
393         if (c - *fingerprint != 0)
394             return c - *fingerprint;
395         fingerprint++;
396         len--;
397         host_key_check += 2;
398     }
399     return *host_key_check - '\0';
400 }
401 
402 static int
403 check_host_key_hash(BDRVSSHState *s, const char *hash,
404                     int hash_type, size_t fingerprint_len, Error **errp)
405 {
406     const char *fingerprint;
407 
408     fingerprint = libssh2_hostkey_hash(s->session, hash_type);
409     if (!fingerprint) {
410         session_error_setg(errp, s, "failed to read remote host key");
411         return -EINVAL;
412     }
413 
414     if(compare_fingerprint((unsigned char *) fingerprint, fingerprint_len,
415                            hash) != 0) {
416         error_setg(errp, "remote host key does not match host_key_check '%s'",
417                    hash);
418         return -EPERM;
419     }
420 
421     return 0;
422 }
423 
424 static int check_host_key(BDRVSSHState *s, const char *host, int port,
425                           SshHostKeyCheck *hkc, Error **errp)
426 {
427     SshHostKeyCheckMode mode;
428 
429     if (hkc) {
430         mode = hkc->mode;
431     } else {
432         mode = SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS;
433     }
434 
435     switch (mode) {
436     case SSH_HOST_KEY_CHECK_MODE_NONE:
437         return 0;
438     case SSH_HOST_KEY_CHECK_MODE_HASH:
439         if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_MD5) {
440             return check_host_key_hash(s, hkc->u.hash.hash,
441                                        LIBSSH2_HOSTKEY_HASH_MD5, 16, errp);
442         } else if (hkc->u.hash.type == SSH_HOST_KEY_CHECK_HASH_TYPE_SHA1) {
443             return check_host_key_hash(s, hkc->u.hash.hash,
444                                        LIBSSH2_HOSTKEY_HASH_SHA1, 20, errp);
445         }
446         g_assert_not_reached();
447         break;
448     case SSH_HOST_KEY_CHECK_MODE_KNOWN_HOSTS:
449         return check_host_key_knownhosts(s, host, port, errp);
450     default:
451         g_assert_not_reached();
452     }
453 
454     return -EINVAL;
455 }
456 
457 static int authenticate(BDRVSSHState *s, const char *user, Error **errp)
458 {
459     int r, ret;
460     const char *userauthlist;
461     LIBSSH2_AGENT *agent = NULL;
462     struct libssh2_agent_publickey *identity;
463     struct libssh2_agent_publickey *prev_identity = NULL;
464 
465     userauthlist = libssh2_userauth_list(s->session, user, strlen(user));
466     if (strstr(userauthlist, "publickey") == NULL) {
467         ret = -EPERM;
468         error_setg(errp,
469                 "remote server does not support \"publickey\" authentication");
470         goto out;
471     }
472 
473     /* Connect to ssh-agent and try each identity in turn. */
474     agent = libssh2_agent_init(s->session);
475     if (!agent) {
476         ret = -EINVAL;
477         session_error_setg(errp, s, "failed to initialize ssh-agent support");
478         goto out;
479     }
480     if (libssh2_agent_connect(agent)) {
481         ret = -ECONNREFUSED;
482         session_error_setg(errp, s, "failed to connect to ssh-agent");
483         goto out;
484     }
485     if (libssh2_agent_list_identities(agent)) {
486         ret = -EINVAL;
487         session_error_setg(errp, s,
488                            "failed requesting identities from ssh-agent");
489         goto out;
490     }
491 
492     for(;;) {
493         r = libssh2_agent_get_identity(agent, &identity, prev_identity);
494         if (r == 1) {           /* end of list */
495             break;
496         }
497         if (r < 0) {
498             ret = -EINVAL;
499             session_error_setg(errp, s,
500                                "failed to obtain identity from ssh-agent");
501             goto out;
502         }
503         r = libssh2_agent_userauth(agent, user, identity);
504         if (r == 0) {
505             /* Authenticated! */
506             ret = 0;
507             goto out;
508         }
509         /* Failed to authenticate with this identity, try the next one. */
510         prev_identity = identity;
511     }
512 
513     ret = -EPERM;
514     error_setg(errp, "failed to authenticate using publickey authentication "
515                "and the identities held by your ssh-agent");
516 
517  out:
518     if (agent != NULL) {
519         /* Note: libssh2 implementation implicitly calls
520          * libssh2_agent_disconnect if necessary.
521          */
522         libssh2_agent_free(agent);
523     }
524 
525     return ret;
526 }
527 
528 static QemuOptsList ssh_runtime_opts = {
529     .name = "ssh",
530     .head = QTAILQ_HEAD_INITIALIZER(ssh_runtime_opts.head),
531     .desc = {
532         {
533             .name = "host",
534             .type = QEMU_OPT_STRING,
535             .help = "Host to connect to",
536         },
537         {
538             .name = "port",
539             .type = QEMU_OPT_NUMBER,
540             .help = "Port to connect to",
541         },
542         {
543             .name = "host_key_check",
544             .type = QEMU_OPT_STRING,
545             .help = "Defines how and what to check the host key against",
546         },
547         { /* end of list */ }
548     },
549 };
550 
551 static bool ssh_process_legacy_options(QDict *output_opts,
552                                        QemuOpts *legacy_opts,
553                                        Error **errp)
554 {
555     const char *host = qemu_opt_get(legacy_opts, "host");
556     const char *port = qemu_opt_get(legacy_opts, "port");
557     const char *host_key_check = qemu_opt_get(legacy_opts, "host_key_check");
558 
559     if (!host && port) {
560         error_setg(errp, "port may not be used without host");
561         return false;
562     }
563 
564     if (host) {
565         qdict_put_str(output_opts, "server.host", host);
566         qdict_put_str(output_opts, "server.port", port ?: stringify(22));
567     }
568 
569     if (host_key_check) {
570         if (strcmp(host_key_check, "no") == 0) {
571             qdict_put_str(output_opts, "host-key-check.mode", "none");
572         } else if (strncmp(host_key_check, "md5:", 4) == 0) {
573             qdict_put_str(output_opts, "host-key-check.mode", "hash");
574             qdict_put_str(output_opts, "host-key-check.type", "md5");
575             qdict_put_str(output_opts, "host-key-check.hash",
576                           &host_key_check[4]);
577         } else if (strncmp(host_key_check, "sha1:", 5) == 0) {
578             qdict_put_str(output_opts, "host-key-check.mode", "hash");
579             qdict_put_str(output_opts, "host-key-check.type", "sha1");
580             qdict_put_str(output_opts, "host-key-check.hash",
581                           &host_key_check[5]);
582         } else if (strcmp(host_key_check, "yes") == 0) {
583             qdict_put_str(output_opts, "host-key-check.mode", "known_hosts");
584         } else {
585             error_setg(errp, "unknown host_key_check setting (%s)",
586                        host_key_check);
587             return false;
588         }
589     }
590 
591     return true;
592 }
593 
594 static BlockdevOptionsSsh *ssh_parse_options(QDict *options, Error **errp)
595 {
596     BlockdevOptionsSsh *result = NULL;
597     QemuOpts *opts = NULL;
598     Error *local_err = NULL;
599     const QDictEntry *e;
600     Visitor *v;
601 
602     /* Translate legacy options */
603     opts = qemu_opts_create(&ssh_runtime_opts, NULL, 0, &error_abort);
604     qemu_opts_absorb_qdict(opts, options, &local_err);
605     if (local_err) {
606         error_propagate(errp, local_err);
607         goto fail;
608     }
609 
610     if (!ssh_process_legacy_options(options, opts, errp)) {
611         goto fail;
612     }
613 
614     /* Create the QAPI object */
615     v = qobject_input_visitor_new_flat_confused(options, errp);
616     if (!v) {
617         goto fail;
618     }
619 
620     visit_type_BlockdevOptionsSsh(v, NULL, &result, &local_err);
621     visit_free(v);
622 
623     if (local_err) {
624         error_propagate(errp, local_err);
625         goto fail;
626     }
627 
628     /* Remove the processed options from the QDict (the visitor processes
629      * _all_ options in the QDict) */
630     while ((e = qdict_first(options))) {
631         qdict_del(options, e->key);
632     }
633 
634 fail:
635     qemu_opts_del(opts);
636     return result;
637 }
638 
639 static int connect_to_ssh(BDRVSSHState *s, BlockdevOptionsSsh *opts,
640                           int ssh_flags, int creat_mode, Error **errp)
641 {
642     int r, ret;
643     long port = 0;
644 
645     if (opts->has_user) {
646         s->user = g_strdup(opts->user);
647     } else {
648         s->user = g_strdup(g_get_user_name());
649         if (!s->user) {
650             error_setg_errno(errp, errno, "Can't get user name");
651             ret = -errno;
652             goto err;
653         }
654     }
655 
656     /* Pop the config into our state object, Exit if invalid */
657     s->inet = opts->server;
658     opts->server = NULL;
659 
660     if (qemu_strtol(s->inet->port, NULL, 10, &port) < 0) {
661         error_setg(errp, "Use only numeric port value");
662         ret = -EINVAL;
663         goto err;
664     }
665 
666     /* Open the socket and connect. */
667     s->sock = inet_connect_saddr(s->inet, errp);
668     if (s->sock < 0) {
669         ret = -EIO;
670         goto err;
671     }
672 
673     /* Create SSH session. */
674     s->session = libssh2_session_init();
675     if (!s->session) {
676         ret = -EINVAL;
677         session_error_setg(errp, s, "failed to initialize libssh2 session");
678         goto err;
679     }
680 
681 #if TRACE_LIBSSH2 != 0
682     libssh2_trace(s->session, TRACE_LIBSSH2);
683 #endif
684 
685     r = libssh2_session_handshake(s->session, s->sock);
686     if (r != 0) {
687         ret = -EINVAL;
688         session_error_setg(errp, s, "failed to establish SSH session");
689         goto err;
690     }
691 
692     /* Check the remote host's key against known_hosts. */
693     ret = check_host_key(s, s->inet->host, port, opts->host_key_check, errp);
694     if (ret < 0) {
695         goto err;
696     }
697 
698     /* Authenticate. */
699     ret = authenticate(s, s->user, errp);
700     if (ret < 0) {
701         goto err;
702     }
703 
704     /* Start SFTP. */
705     s->sftp = libssh2_sftp_init(s->session);
706     if (!s->sftp) {
707         session_error_setg(errp, s, "failed to initialize sftp handle");
708         ret = -EINVAL;
709         goto err;
710     }
711 
712     /* Open the remote file. */
713     trace_ssh_connect_to_ssh(opts->path, ssh_flags, creat_mode);
714     s->sftp_handle = libssh2_sftp_open(s->sftp, opts->path, ssh_flags,
715                                        creat_mode);
716     if (!s->sftp_handle) {
717         session_error_setg(errp, s, "failed to open remote file '%s'",
718                            opts->path);
719         ret = -EINVAL;
720         goto err;
721     }
722 
723     r = libssh2_sftp_fstat(s->sftp_handle, &s->attrs);
724     if (r < 0) {
725         sftp_error_setg(errp, s, "failed to read file attributes");
726         return -EINVAL;
727     }
728 
729     return 0;
730 
731  err:
732     if (s->sftp_handle) {
733         libssh2_sftp_close(s->sftp_handle);
734     }
735     s->sftp_handle = NULL;
736     if (s->sftp) {
737         libssh2_sftp_shutdown(s->sftp);
738     }
739     s->sftp = NULL;
740     if (s->session) {
741         libssh2_session_disconnect(s->session,
742                                    "from qemu ssh client: "
743                                    "error opening connection");
744         libssh2_session_free(s->session);
745     }
746     s->session = NULL;
747 
748     return ret;
749 }
750 
751 static int ssh_file_open(BlockDriverState *bs, QDict *options, int bdrv_flags,
752                          Error **errp)
753 {
754     BDRVSSHState *s = bs->opaque;
755     BlockdevOptionsSsh *opts;
756     int ret;
757     int ssh_flags;
758 
759     ssh_state_init(s);
760 
761     ssh_flags = LIBSSH2_FXF_READ;
762     if (bdrv_flags & BDRV_O_RDWR) {
763         ssh_flags |= LIBSSH2_FXF_WRITE;
764     }
765 
766     opts = ssh_parse_options(options, errp);
767     if (opts == NULL) {
768         return -EINVAL;
769     }
770 
771     /* Start up SSH. */
772     ret = connect_to_ssh(s, opts, ssh_flags, 0, errp);
773     if (ret < 0) {
774         goto err;
775     }
776 
777     /* Go non-blocking. */
778     libssh2_session_set_blocking(s->session, 0);
779 
780     qapi_free_BlockdevOptionsSsh(opts);
781 
782     return 0;
783 
784  err:
785     if (s->sock >= 0) {
786         close(s->sock);
787     }
788     s->sock = -1;
789 
790     qapi_free_BlockdevOptionsSsh(opts);
791 
792     return ret;
793 }
794 
795 /* Note: This is a blocking operation */
796 static int ssh_grow_file(BDRVSSHState *s, int64_t offset, Error **errp)
797 {
798     ssize_t ret;
799     char c[1] = { '\0' };
800     int was_blocking = libssh2_session_get_blocking(s->session);
801 
802     /* offset must be strictly greater than the current size so we do
803      * not overwrite anything */
804     assert(offset > 0 && offset > s->attrs.filesize);
805 
806     libssh2_session_set_blocking(s->session, 1);
807 
808     libssh2_sftp_seek64(s->sftp_handle, offset - 1);
809     ret = libssh2_sftp_write(s->sftp_handle, c, 1);
810 
811     libssh2_session_set_blocking(s->session, was_blocking);
812 
813     if (ret < 0) {
814         sftp_error_setg(errp, s, "Failed to grow file");
815         return -EIO;
816     }
817 
818     s->attrs.filesize = offset;
819     return 0;
820 }
821 
822 static QemuOptsList ssh_create_opts = {
823     .name = "ssh-create-opts",
824     .head = QTAILQ_HEAD_INITIALIZER(ssh_create_opts.head),
825     .desc = {
826         {
827             .name = BLOCK_OPT_SIZE,
828             .type = QEMU_OPT_SIZE,
829             .help = "Virtual disk size"
830         },
831         { /* end of list */ }
832     }
833 };
834 
835 static int ssh_co_create(BlockdevCreateOptions *options, Error **errp)
836 {
837     BlockdevCreateOptionsSsh *opts = &options->u.ssh;
838     BDRVSSHState s;
839     int ret;
840 
841     assert(options->driver == BLOCKDEV_DRIVER_SSH);
842 
843     ssh_state_init(&s);
844 
845     ret = connect_to_ssh(&s, opts->location,
846                          LIBSSH2_FXF_READ|LIBSSH2_FXF_WRITE|
847                          LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC,
848                          0644, errp);
849     if (ret < 0) {
850         goto fail;
851     }
852 
853     if (opts->size > 0) {
854         ret = ssh_grow_file(&s, opts->size, errp);
855         if (ret < 0) {
856             goto fail;
857         }
858     }
859 
860     ret = 0;
861 fail:
862     ssh_state_free(&s);
863     return ret;
864 }
865 
866 static int coroutine_fn ssh_co_create_opts(const char *filename, QemuOpts *opts,
867                                            Error **errp)
868 {
869     BlockdevCreateOptions *create_options;
870     BlockdevCreateOptionsSsh *ssh_opts;
871     int ret;
872     QDict *uri_options = NULL;
873 
874     create_options = g_new0(BlockdevCreateOptions, 1);
875     create_options->driver = BLOCKDEV_DRIVER_SSH;
876     ssh_opts = &create_options->u.ssh;
877 
878     /* Get desired file size. */
879     ssh_opts->size = ROUND_UP(qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0),
880                               BDRV_SECTOR_SIZE);
881     trace_ssh_co_create_opts(ssh_opts->size);
882 
883     uri_options = qdict_new();
884     ret = parse_uri(filename, uri_options, errp);
885     if (ret < 0) {
886         goto out;
887     }
888 
889     ssh_opts->location = ssh_parse_options(uri_options, errp);
890     if (ssh_opts->location == NULL) {
891         ret = -EINVAL;
892         goto out;
893     }
894 
895     ret = ssh_co_create(create_options, errp);
896 
897  out:
898     qobject_unref(uri_options);
899     qapi_free_BlockdevCreateOptions(create_options);
900     return ret;
901 }
902 
903 static void ssh_close(BlockDriverState *bs)
904 {
905     BDRVSSHState *s = bs->opaque;
906 
907     ssh_state_free(s);
908 }
909 
910 static int ssh_has_zero_init(BlockDriverState *bs)
911 {
912     BDRVSSHState *s = bs->opaque;
913     /* Assume false, unless we can positively prove it's true. */
914     int has_zero_init = 0;
915 
916     if (s->attrs.flags & LIBSSH2_SFTP_ATTR_PERMISSIONS) {
917         if (s->attrs.permissions & LIBSSH2_SFTP_S_IFREG) {
918             has_zero_init = 1;
919         }
920     }
921 
922     return has_zero_init;
923 }
924 
925 typedef struct BDRVSSHRestart {
926     BlockDriverState *bs;
927     Coroutine *co;
928 } BDRVSSHRestart;
929 
930 static void restart_coroutine(void *opaque)
931 {
932     BDRVSSHRestart *restart = opaque;
933     BlockDriverState *bs = restart->bs;
934     BDRVSSHState *s = bs->opaque;
935     AioContext *ctx = bdrv_get_aio_context(bs);
936 
937     trace_ssh_restart_coroutine(restart->co);
938     aio_set_fd_handler(ctx, s->sock, false, NULL, NULL, NULL, NULL);
939 
940     aio_co_wake(restart->co);
941 }
942 
943 /* A non-blocking call returned EAGAIN, so yield, ensuring the
944  * handlers are set up so that we'll be rescheduled when there is an
945  * interesting event on the socket.
946  */
947 static coroutine_fn void co_yield(BDRVSSHState *s, BlockDriverState *bs)
948 {
949     int r;
950     IOHandler *rd_handler = NULL, *wr_handler = NULL;
951     BDRVSSHRestart restart = {
952         .bs = bs,
953         .co = qemu_coroutine_self()
954     };
955 
956     r = libssh2_session_block_directions(s->session);
957 
958     if (r & LIBSSH2_SESSION_BLOCK_INBOUND) {
959         rd_handler = restart_coroutine;
960     }
961     if (r & LIBSSH2_SESSION_BLOCK_OUTBOUND) {
962         wr_handler = restart_coroutine;
963     }
964 
965     trace_ssh_co_yield(s->sock, rd_handler, wr_handler);
966 
967     aio_set_fd_handler(bdrv_get_aio_context(bs), s->sock,
968                        false, rd_handler, wr_handler, NULL, &restart);
969     qemu_coroutine_yield();
970     trace_ssh_co_yield_back(s->sock);
971 }
972 
973 /* SFTP has a function `libssh2_sftp_seek64' which seeks to a position
974  * in the remote file.  Notice that it just updates a field in the
975  * sftp_handle structure, so there is no network traffic and it cannot
976  * fail.
977  *
978  * However, `libssh2_sftp_seek64' does have a catastrophic effect on
979  * performance since it causes the handle to throw away all in-flight
980  * reads and buffered readahead data.  Therefore this function tries
981  * to be intelligent about when to call the underlying libssh2 function.
982  */
983 #define SSH_SEEK_WRITE 0
984 #define SSH_SEEK_READ  1
985 #define SSH_SEEK_FORCE 2
986 
987 static void ssh_seek(BDRVSSHState *s, int64_t offset, int flags)
988 {
989     bool op_read = (flags & SSH_SEEK_READ) != 0;
990     bool force = (flags & SSH_SEEK_FORCE) != 0;
991 
992     if (force || op_read != s->offset_op_read || offset != s->offset) {
993         trace_ssh_seek(offset);
994         libssh2_sftp_seek64(s->sftp_handle, offset);
995         s->offset = offset;
996         s->offset_op_read = op_read;
997     }
998 }
999 
1000 static coroutine_fn int ssh_read(BDRVSSHState *s, BlockDriverState *bs,
1001                                  int64_t offset, size_t size,
1002                                  QEMUIOVector *qiov)
1003 {
1004     ssize_t r;
1005     size_t got;
1006     char *buf, *end_of_vec;
1007     struct iovec *i;
1008 
1009     trace_ssh_read(offset, size);
1010 
1011     ssh_seek(s, offset, SSH_SEEK_READ);
1012 
1013     /* This keeps track of the current iovec element ('i'), where we
1014      * will write to next ('buf'), and the end of the current iovec
1015      * ('end_of_vec').
1016      */
1017     i = &qiov->iov[0];
1018     buf = i->iov_base;
1019     end_of_vec = i->iov_base + i->iov_len;
1020 
1021     /* libssh2 has a hard-coded limit of 2000 bytes per request,
1022      * although it will also do readahead behind our backs.  Therefore
1023      * we may have to do repeated reads here until we have read 'size'
1024      * bytes.
1025      */
1026     for (got = 0; got < size; ) {
1027     again:
1028         trace_ssh_read_buf(buf, end_of_vec - buf);
1029         r = libssh2_sftp_read(s->sftp_handle, buf, end_of_vec - buf);
1030         trace_ssh_read_return(r);
1031 
1032         if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1033             co_yield(s, bs);
1034             goto again;
1035         }
1036         if (r < 0) {
1037             sftp_error_trace(s, "read");
1038             s->offset = -1;
1039             return -EIO;
1040         }
1041         if (r == 0) {
1042             /* EOF: Short read so pad the buffer with zeroes and return it. */
1043             qemu_iovec_memset(qiov, got, 0, size - got);
1044             return 0;
1045         }
1046 
1047         got += r;
1048         buf += r;
1049         s->offset += r;
1050         if (buf >= end_of_vec && got < size) {
1051             i++;
1052             buf = i->iov_base;
1053             end_of_vec = i->iov_base + i->iov_len;
1054         }
1055     }
1056 
1057     return 0;
1058 }
1059 
1060 static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
1061                                      int64_t sector_num,
1062                                      int nb_sectors, QEMUIOVector *qiov)
1063 {
1064     BDRVSSHState *s = bs->opaque;
1065     int ret;
1066 
1067     qemu_co_mutex_lock(&s->lock);
1068     ret = ssh_read(s, bs, sector_num * BDRV_SECTOR_SIZE,
1069                    nb_sectors * BDRV_SECTOR_SIZE, qiov);
1070     qemu_co_mutex_unlock(&s->lock);
1071 
1072     return ret;
1073 }
1074 
1075 static int ssh_write(BDRVSSHState *s, BlockDriverState *bs,
1076                      int64_t offset, size_t size,
1077                      QEMUIOVector *qiov)
1078 {
1079     ssize_t r;
1080     size_t written;
1081     char *buf, *end_of_vec;
1082     struct iovec *i;
1083 
1084     trace_ssh_write(offset, size);
1085 
1086     ssh_seek(s, offset, SSH_SEEK_WRITE);
1087 
1088     /* This keeps track of the current iovec element ('i'), where we
1089      * will read from next ('buf'), and the end of the current iovec
1090      * ('end_of_vec').
1091      */
1092     i = &qiov->iov[0];
1093     buf = i->iov_base;
1094     end_of_vec = i->iov_base + i->iov_len;
1095 
1096     for (written = 0; written < size; ) {
1097     again:
1098         trace_ssh_write_buf(buf, end_of_vec - buf);
1099         r = libssh2_sftp_write(s->sftp_handle, buf, end_of_vec - buf);
1100         trace_ssh_write_return(r);
1101 
1102         if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1103             co_yield(s, bs);
1104             goto again;
1105         }
1106         if (r < 0) {
1107             sftp_error_trace(s, "write");
1108             s->offset = -1;
1109             return -EIO;
1110         }
1111         /* The libssh2 API is very unclear about this.  A comment in
1112          * the code says "nothing was acked, and no EAGAIN was
1113          * received!" which apparently means that no data got sent
1114          * out, and the underlying channel didn't return any EAGAIN
1115          * indication.  I think this is a bug in either libssh2 or
1116          * OpenSSH (server-side).  In any case, forcing a seek (to
1117          * discard libssh2 internal buffers), and then trying again
1118          * works for me.
1119          */
1120         if (r == 0) {
1121             ssh_seek(s, offset + written, SSH_SEEK_WRITE|SSH_SEEK_FORCE);
1122             co_yield(s, bs);
1123             goto again;
1124         }
1125 
1126         written += r;
1127         buf += r;
1128         s->offset += r;
1129         if (buf >= end_of_vec && written < size) {
1130             i++;
1131             buf = i->iov_base;
1132             end_of_vec = i->iov_base + i->iov_len;
1133         }
1134 
1135         if (offset + written > s->attrs.filesize)
1136             s->attrs.filesize = offset + written;
1137     }
1138 
1139     return 0;
1140 }
1141 
1142 static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
1143                                       int64_t sector_num,
1144                                       int nb_sectors, QEMUIOVector *qiov,
1145                                       int flags)
1146 {
1147     BDRVSSHState *s = bs->opaque;
1148     int ret;
1149 
1150     assert(!flags);
1151     qemu_co_mutex_lock(&s->lock);
1152     ret = ssh_write(s, bs, sector_num * BDRV_SECTOR_SIZE,
1153                     nb_sectors * BDRV_SECTOR_SIZE, qiov);
1154     qemu_co_mutex_unlock(&s->lock);
1155 
1156     return ret;
1157 }
1158 
1159 static void unsafe_flush_warning(BDRVSSHState *s, const char *what)
1160 {
1161     if (!s->unsafe_flush_warning) {
1162         warn_report("ssh server %s does not support fsync",
1163                     s->inet->host);
1164         if (what) {
1165             error_report("to support fsync, you need %s", what);
1166         }
1167         s->unsafe_flush_warning = true;
1168     }
1169 }
1170 
1171 #ifdef HAS_LIBSSH2_SFTP_FSYNC
1172 
1173 static coroutine_fn int ssh_flush(BDRVSSHState *s, BlockDriverState *bs)
1174 {
1175     int r;
1176 
1177     trace_ssh_flush();
1178  again:
1179     r = libssh2_sftp_fsync(s->sftp_handle);
1180     if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
1181         co_yield(s, bs);
1182         goto again;
1183     }
1184     if (r == LIBSSH2_ERROR_SFTP_PROTOCOL &&
1185         libssh2_sftp_last_error(s->sftp) == LIBSSH2_FX_OP_UNSUPPORTED) {
1186         unsafe_flush_warning(s, "OpenSSH >= 6.3");
1187         return 0;
1188     }
1189     if (r < 0) {
1190         sftp_error_trace(s, "fsync");
1191         return -EIO;
1192     }
1193 
1194     return 0;
1195 }
1196 
1197 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1198 {
1199     BDRVSSHState *s = bs->opaque;
1200     int ret;
1201 
1202     qemu_co_mutex_lock(&s->lock);
1203     ret = ssh_flush(s, bs);
1204     qemu_co_mutex_unlock(&s->lock);
1205 
1206     return ret;
1207 }
1208 
1209 #else /* !HAS_LIBSSH2_SFTP_FSYNC */
1210 
1211 static coroutine_fn int ssh_co_flush(BlockDriverState *bs)
1212 {
1213     BDRVSSHState *s = bs->opaque;
1214 
1215     unsafe_flush_warning(s, "libssh2 >= 1.4.4");
1216     return 0;
1217 }
1218 
1219 #endif /* !HAS_LIBSSH2_SFTP_FSYNC */
1220 
1221 static int64_t ssh_getlength(BlockDriverState *bs)
1222 {
1223     BDRVSSHState *s = bs->opaque;
1224     int64_t length;
1225 
1226     /* Note we cannot make a libssh2 call here. */
1227     length = (int64_t) s->attrs.filesize;
1228     trace_ssh_getlength(length);
1229 
1230     return length;
1231 }
1232 
1233 static int coroutine_fn ssh_co_truncate(BlockDriverState *bs, int64_t offset,
1234                                         PreallocMode prealloc, Error **errp)
1235 {
1236     BDRVSSHState *s = bs->opaque;
1237 
1238     if (prealloc != PREALLOC_MODE_OFF) {
1239         error_setg(errp, "Unsupported preallocation mode '%s'",
1240                    PreallocMode_str(prealloc));
1241         return -ENOTSUP;
1242     }
1243 
1244     if (offset < s->attrs.filesize) {
1245         error_setg(errp, "ssh driver does not support shrinking files");
1246         return -ENOTSUP;
1247     }
1248 
1249     if (offset == s->attrs.filesize) {
1250         return 0;
1251     }
1252 
1253     return ssh_grow_file(s, offset, errp);
1254 }
1255 
1256 static void ssh_refresh_filename(BlockDriverState *bs)
1257 {
1258     BDRVSSHState *s = bs->opaque;
1259     const char *path, *host_key_check;
1260     int ret;
1261 
1262     /*
1263      * None of these options can be represented in a plain "host:port"
1264      * format, so if any was given, we have to abort.
1265      */
1266     if (s->inet->has_ipv4 || s->inet->has_ipv6 || s->inet->has_to ||
1267         s->inet->has_numeric)
1268     {
1269         return;
1270     }
1271 
1272     path = qdict_get_try_str(bs->full_open_options, "path");
1273     assert(path); /* mandatory option */
1274 
1275     host_key_check = qdict_get_try_str(bs->full_open_options, "host_key_check");
1276 
1277     ret = snprintf(bs->exact_filename, sizeof(bs->exact_filename),
1278                    "ssh://%s@%s:%s%s%s%s",
1279                    s->user, s->inet->host, s->inet->port, path,
1280                    host_key_check ? "?host_key_check=" : "",
1281                    host_key_check ?: "");
1282     if (ret >= sizeof(bs->exact_filename)) {
1283         /* An overflow makes the filename unusable, so do not report any */
1284         bs->exact_filename[0] = '\0';
1285     }
1286 }
1287 
1288 static char *ssh_bdrv_dirname(BlockDriverState *bs, Error **errp)
1289 {
1290     if (qdict_haskey(bs->full_open_options, "host_key_check")) {
1291         /*
1292          * We cannot generate a simple prefix if we would have to
1293          * append a query string.
1294          */
1295         error_setg(errp,
1296                    "Cannot generate a base directory with host_key_check set");
1297         return NULL;
1298     }
1299 
1300     if (bs->exact_filename[0] == '\0') {
1301         error_setg(errp, "Cannot generate a base directory for this ssh node");
1302         return NULL;
1303     }
1304 
1305     return path_combine(bs->exact_filename, "");
1306 }
1307 
1308 static const char *const ssh_strong_runtime_opts[] = {
1309     "host",
1310     "port",
1311     "path",
1312     "user",
1313     "host_key_check",
1314     "server.",
1315 
1316     NULL
1317 };
1318 
1319 static BlockDriver bdrv_ssh = {
1320     .format_name                  = "ssh",
1321     .protocol_name                = "ssh",
1322     .instance_size                = sizeof(BDRVSSHState),
1323     .bdrv_parse_filename          = ssh_parse_filename,
1324     .bdrv_file_open               = ssh_file_open,
1325     .bdrv_co_create               = ssh_co_create,
1326     .bdrv_co_create_opts          = ssh_co_create_opts,
1327     .bdrv_close                   = ssh_close,
1328     .bdrv_has_zero_init           = ssh_has_zero_init,
1329     .bdrv_co_readv                = ssh_co_readv,
1330     .bdrv_co_writev               = ssh_co_writev,
1331     .bdrv_getlength               = ssh_getlength,
1332     .bdrv_co_truncate             = ssh_co_truncate,
1333     .bdrv_co_flush_to_disk        = ssh_co_flush,
1334     .bdrv_refresh_filename        = ssh_refresh_filename,
1335     .bdrv_dirname                 = ssh_bdrv_dirname,
1336     .create_opts                  = &ssh_create_opts,
1337     .strong_runtime_opts          = ssh_strong_runtime_opts,
1338 };
1339 
1340 static void bdrv_ssh_init(void)
1341 {
1342     int r;
1343 
1344     r = libssh2_init(0);
1345     if (r != 0) {
1346         fprintf(stderr, "libssh2 initialization failed, %d\n", r);
1347         exit(EXIT_FAILURE);
1348     }
1349 
1350     bdrv_register(&bdrv_ssh);
1351 }
1352 
1353 block_init(bdrv_ssh_init);
1354