diff mbox

[v4] block: Add support for Secure Shell (ssh) block device.

Message ID 1364399849-5518-2-git-send-email-rjones@redhat.com
State New
Headers show

Commit Message

Richard W.M. Jones March 27, 2013, 3:57 p.m. UTC
From: "Richard W.M. Jones" <rjones@redhat.com>

  qemu-system-x86_64 -drive file=ssh://hostname/some/image

QEMU will ssh into 'hostname' and open '/some/image' which is made
available as a standard block device.

You can specify a username (ssh://user@host/...) and/or a port number
(ssh://host:port/...).  You can also use an alternate syntax using
properties (file.user, file.host, file.port, file.path).

Current limitations:

- Authentication must be done without passwords or passphrases, using
  ssh-agent.  Other authentication methods are not supported.

- Uses a single connection, instead of concurrent AIO with multiple
  SSH connections.

This is implemented using libssh2 on the client side.  The server just
requires a regular ssh daemon with sftp-server support.  Most ssh
daemons on Unix/Linux systems will work out of the box.

Signed-off-by: Richard W.M. Jones <rjones@redhat.com>
Cc: Stefan Hajnoczi <stefanha@gmail.com>
Cc: Kevin Wolf <kwolf@redhat.com>
---
 block/Makefile.objs |   1 +
 block/ssh.c         | 878 ++++++++++++++++++++++++++++++++++++++++++++++++++++
 configure           |  47 +++
 qemu-doc.texi       |  40 +++
 qemu-options.hx     |  12 +
 5 files changed, 978 insertions(+)
 create mode 100644 block/ssh.c

Comments

Stefan Hajnoczi March 28, 2013, 10:47 a.m. UTC | #1
On Wed, Mar 27, 2013 at 03:57:29PM +0000, Richard W.M. Jones wrote:
> From: "Richard W.M. Jones" <rjones@redhat.com>
> 
>   qemu-system-x86_64 -drive file=ssh://hostname/some/image
> 
> QEMU will ssh into 'hostname' and open '/some/image' which is made
> available as a standard block device.
> 
> You can specify a username (ssh://user@host/...) and/or a port number
> (ssh://host:port/...).  You can also use an alternate syntax using
> properties (file.user, file.host, file.port, file.path).
> 
> Current limitations:
> 
> - Authentication must be done without passwords or passphrases, using
>   ssh-agent.  Other authentication methods are not supported.
> 
> - Uses a single connection, instead of concurrent AIO with multiple
>   SSH connections.
> 
> This is implemented using libssh2 on the client side.  The server just
> requires a regular ssh daemon with sftp-server support.  Most ssh
> daemons on Unix/Linux systems will work out of the box.
> 
> Signed-off-by: Richard W.M. Jones <rjones@redhat.com>
> Cc: Stefan Hajnoczi <stefanha@gmail.com>
> Cc: Kevin Wolf <kwolf@redhat.com>
> ---
>  block/Makefile.objs |   1 +
>  block/ssh.c         | 878 ++++++++++++++++++++++++++++++++++++++++++++++++++++
>  configure           |  47 +++
>  qemu-doc.texi       |  40 +++
>  qemu-options.hx     |  12 +
>  5 files changed, 978 insertions(+)
>  create mode 100644 block/ssh.c

Please run qemu-iotests, see tests/qemu-iotests/check.  For example,
with NBD:

  $ cd tests/qemu-iotests
  $ QEMU_PROG=$HOME/qemu/x86_64-softmmu/qemu-system-x86_64 PATH=$HOME/qemu:$PATH \
    ./check -nbd

A patch will be required to add -ssh support to ./check.

> +/* Wrappers around error_report which make sure to dump as much
> + * information from libssh2 as possible.
> + */
> +static void
> +session_error_report(BDRVSSHState *s, const char *fs, ...)
> +{
> +    va_list args;
> +
> +    va_start(args, fs);
> +
> +    if ((s)->session) {
> +        char *ssh_err;
> +        int ssh_err_len = sizeof ssh_err;

This variable is unused and initialization to sizeof ssh_err seems
wrong.  Please drop it and pass NULL to libssh2_session_last_error(3).

> +        int ssh_err_code;
> +
> +        libssh2_session_last_error((s)->session,
> +                                   &ssh_err, &ssh_err_len, 0);
> +        /* This is not an errno.  See <libssh2.h>. */
> +        ssh_err_code = libssh2_session_last_errno((s)->session);
> +
> +        error_vprintf(fs, args);
> +        error_printf(": %s (libssh2 error code: %d)", ssh_err, ssh_err_code);
> +    }
> +    else {

QEMU tends to use } else { on a single line.

> +        error_vprintf(fs, args);
> +    }

In fact this else statement can be avoided:

error_vprintf(fs, args);
if (s->session) {
    ...
    error_printf(": %s (libssh2 error code: %d)", ssh_err, ssh_err_code);
}

> +
> +    va_end(args);
> +    error_printf("\n");
> +}
> +
> +static void
> +sftp_error_report(BDRVSSHState *s, const char *fs, ...)
> +{
> +    va_list args;
> +
> +    va_start(args, fs);
> +
> +    if ((s)->sftp) {
> +        char *ssh_err;
> +        int ssh_err_len = sizeof ssh_err;
> +        int ssh_err_code;
> +        unsigned long sftp_err_code;
> +
> +        libssh2_session_last_error((s)->session,
> +                                   &ssh_err, &ssh_err_len, 0);
> +        /* This is not an errno.  See <libssh2.h>. */
> +        ssh_err_code = libssh2_session_last_errno((s)->session);
> +        /* See <libssh2_sftp.h>. */
> +        sftp_err_code = libssh2_sftp_last_error((s)->sftp);
> +
> +        error_vprintf(fs, args);
> +        error_printf(": %s (libssh2 error code: %d, sftp error code: %lu)",
> +                     ssh_err, ssh_err_code, sftp_err_code);
> +    }
> +    else {
> +        error_vprintf(fs, args);
> +    }

Same comments apply to sftp_error_report().

> +
> +    va_end(args);
> +    error_printf("\n");
> +}
> +
> +#ifndef _WIN32
> +static const char *get_username(void)
> +{
> +    struct passwd *pwd;
> +
> +    pwd = getpwuid(geteuid ());
> +    if (!pwd) {
> +        error_report("failed to get current user name");
> +        return NULL;
> +    }
> +    return pwd->pw_name;
> +}
> +#else
> +static const char *get_username(void)
> +{
> +    error_report("on Windows, specify a remote user name in the URI");
> +    return NULL;
> +}
> +#endif

This is ugly since it's platform-specific and uses getpwuid(3) which is
not reentrant.

Does ssh(1) even use getpwuid(geteuid()) or does it check .ssh/config
and then getenv("USER")?  Perhaps we can just getenv("USER")?

> +
> +static int parse_uri(const char *filename, QDict *options)

Use Error **errp argument instead of error_report()?

> +{
> +    URI *uri;
> +    char *host = NULL;

Unused variable.

> +static int check_host_key(BDRVSSHState *s, const char *host, int port)
> +{
> +    int ret;
> +    const char *home;
> +    char *knh_file = NULL;
> +    LIBSSH2_KNOWNHOSTS *knh = NULL;
> +    const char *fingerprint;
> +    size_t len;
> +    int type;
> +
> +    knh = libssh2_knownhost_init(s->session);
> +    if (!knh) {
> +        ret = -EINVAL;
> +        session_error_report(s, "failed to initialize known hosts support");
> +        goto out;
> +    }
> +
> +    home = getenv("HOME");
> +    if (home) {
> +        knh_file = g_strdup_printf("%s/.ssh/known_hosts", home);
> +    } else {
> +        knh_file = g_strdup_printf("/root/.ssh/known_hosts");
> +    }

Windows support?

> +
> +    /* Read all known hosts from OpenSSH-style known_hosts file. */
> +    libssh2_knownhost_readfile(knh, knh_file, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
> +
> +    fingerprint = libssh2_session_hostkey(s->session, &len, &type);
> +    if (fingerprint) {
> +        struct libssh2_knownhost *found;
> +        int r;
> +
> +        r = libssh2_knownhost_checkp(knh, host, port, fingerprint, len,
> +                                     LIBSSH2_KNOWNHOST_TYPE_PLAIN|
> +                                     LIBSSH2_KNOWNHOST_KEYENC_RAW,
> +                                     &found);
> +        switch (r) {
> +        case LIBSSH2_KNOWNHOST_CHECK_MATCH:
> +            /* OK */
> +            DPRINTF("host key OK: %s", found->key);
> +            break;
> +        case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:
> +            ret = -EINVAL;
> +            session_error_report(s, "host key does not match the one in known_hosts (found key %s)",
> +                                 found->key);

Does the user know the offending known_hosts line?  ssh(1) normally says
something like "Mismatch with line ~/.ssh/known_hosts:35" so you know
which hostkey to drop if you wish to proceed.

> +            goto out;
> +        case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND:
> +            ret = -EINVAL;
> +            session_error_report(s, "no host key was found in known_hosts");
> +            goto out;

ssh(1) prompts the user to accept the hostkey.  When QEMU fails like
this the user needs to run ssh(1) first to populate known_hosts?

> @@ -1166,6 +1171,7 @@ echo "  --disable-glusterfs      disable GlusterFS backend"
>  echo "  --enable-gcov            enable test coverage analysis with gcov"
>  echo "  --gcov=GCOV              use specified gcov [$gcov_tool]"
>  echo "  --enable-tpm             enable TPM support"
> +echo "  --enable-libssh2         enable ssh block device support"

Most options seem to also document --disable-FOO.  Please do that.
Richard W.M. Jones March 28, 2013, 11:16 a.m. UTC | #2
On Thu, Mar 28, 2013 at 11:47:32AM +0100, Stefan Hajnoczi wrote:
> ssh(1) prompts the user to accept the hostkey.  When QEMU fails like
> this the user needs to run ssh(1) first to populate known_hosts?

Yes - I tested this and qemu will simply fail to open the disk with
the error message about the host key not being found.  Currently you
have to manually log in (eg. with ssh), accept the key in ssh, and
then retry the qemu command.

Not that I think this is much of a problem, as long as the error is
clear.

But ... if I wanted to make qemu interactively ask about host keys, or
even accept passwords, how would I do that?  Is there a block device
driver that asks for passwords that I can look at?

[The only mention of 'password' is in the iscsi driver, and that seems
to be related to passing passwords in the URL (!?!)]

Rich.
Stefan Hajnoczi March 28, 2013, 1:29 p.m. UTC | #3
On Thu, Mar 28, 2013 at 11:16:58AM +0000, Richard W.M. Jones wrote:
> On Thu, Mar 28, 2013 at 11:47:32AM +0100, Stefan Hajnoczi wrote:
> > ssh(1) prompts the user to accept the hostkey.  When QEMU fails like
> > this the user needs to run ssh(1) first to populate known_hosts?
> 
> Yes - I tested this and qemu will simply fail to open the disk with
> the error message about the host key not being found.  Currently you
> have to manually log in (eg. with ssh), accept the key in ssh, and
> then retry the qemu command.
> 
> Not that I think this is much of a problem, as long as the error is
> clear.
> 
> But ... if I wanted to make qemu interactively ask about host keys, or
> even accept passwords, how would I do that?  Is there a block device
> driver that asks for passwords that I can look at?
> 
> [The only mention of 'password' is in the iscsi driver, and that seems
> to be related to passing passwords in the URL (!?!)]

There is an API to prompt for a image encryption key, see
.bdrv_set_key().

Stefan
Richard W.M. Jones April 3, 2013, 10:14 p.m. UTC | #4
On Thu, Mar 28, 2013 at 11:47:32AM +0100, Stefan Hajnoczi wrote:
> On Wed, Mar 27, 2013 at 03:57:29PM +0000, Richard W.M. Jones wrote:
[...]

Thanks for reviewing this patch.  I will post an updated v5 on this
list soon, but I also have some comments (below).

> Please run qemu-iotests, see tests/qemu-iotests/check.  For example,
> with NBD:
> 
>   $ cd tests/qemu-iotests
>   $ QEMU_PROG=$HOME/qemu/x86_64-softmmu/qemu-system-x86_64 PATH=$HOME/qemu:$PATH \
>     ./check -nbd
> 
> A patch will be required to add -ssh support to ./check.

I have added this in the updated patch.

A question: Are the -qcow2 tests meant to pass?  Many don't pass for
my ssh driver (ie. './check -ssh -qcow2').  I tried using the nbd
driver (ie. './check -nbd -qcow2') and a large number of those fail as
well.  To take an example, test 013 fails because it tries to run the
'mv' command on the nbd: URL (or the ssh: URL when running the test on
my block driver).  It looks like this and other qcow2 tests are a bit
broken on anything other than plain files.

[...]

> Does ssh(1) even use getpwuid(geteuid()) or does it check .ssh/config
> and then getenv("USER")?  Perhaps we can just getenv("USER")?

ssh uses getpwuid too.

The updated patch adds some thread-safe code to osdep.c, but still
doesn't work on Windows.

> > +    home = getenv("HOME");
> > +    if (home) {
> > +        knh_file = g_strdup_printf("%s/.ssh/known_hosts", home);
> > +    } else {
> > +        knh_file = g_strdup_printf("/root/.ssh/known_hosts");
> > +    }
> 
> Windows support?

I have no idea what Windows does for this, so I punted on the problem.

> > +        case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:
> > +            ret = -EINVAL;
> > +            session_error_report(s, "host key does not match the one in known_hosts (found key %s)",
> > +                                 found->key);
> 
> Does the user know the offending known_hosts line?  ssh(1) normally says
> something like "Mismatch with line ~/.ssh/known_hosts:35" so you know
> which hostkey to drop if you wish to proceed.

Unfortunately it doesn't appear that libssh2 keeps the original line
number around.

Rich.
Stefan Hajnoczi April 8, 2013, 11:37 a.m. UTC | #5
On Wed, Apr 03, 2013 at 11:14:30PM +0100, Richard W.M. Jones wrote:
> On Thu, Mar 28, 2013 at 11:47:32AM +0100, Stefan Hajnoczi wrote:
> > On Wed, Mar 27, 2013 at 03:57:29PM +0000, Richard W.M. Jones wrote:
> > Please run qemu-iotests, see tests/qemu-iotests/check.  For example,
> > with NBD:
> > 
> >   $ cd tests/qemu-iotests
> >   $ QEMU_PROG=$HOME/qemu/x86_64-softmmu/qemu-system-x86_64 PATH=$HOME/qemu:$PATH \
> >     ./check -nbd
> > 
> > A patch will be required to add -ssh support to ./check.
> 
> I have added this in the updated patch.
> 
> A question: Are the -qcow2 tests meant to pass?  Many don't pass for
> my ssh driver (ie. './check -ssh -qcow2').  I tried using the nbd
> driver (ie. './check -nbd -qcow2') and a large number of those fail as
> well.  To take an example, test 013 fails because it tries to run the
> 'mv' command on the nbd: URL (or the ssh: URL when running the test on
> my block driver).  It looks like this and other qcow2 tests are a bit
> broken on anything other than plain files.

Yes, I don't expect qemu-iotests to work with qcow2-on-nbd.

Just ./check -nbd and ./check -ssh should work.

Stefan
Richard W.M. Jones April 8, 2013, 1:01 p.m. UTC | #6
On Mon, Apr 08, 2013 at 01:37:28PM +0200, Stefan Hajnoczi wrote:
> Just ./check -nbd and ./check -ssh should work.

Both work 100% for me (with patch v7).

Rich.
Richard W.M. Jones April 8, 2013, 1:05 p.m. UTC | #7
More specifically, here's the output on my machine:

rjones@choo:~/d/qemu/tests/qemu-iotests$ QEMU_PROG=~/d/qemu/x86_64-softmmu/qemu-system-x86_64 PATH=~/d/qemu:$PATH ./check -ssh
QEMU          -- /home/rjones/d/qemu/x86_64-softmmu/qemu-system-x86_64
QEMU_IMG      -- /home/rjones/d/qemu/qemu-img
QEMU_IO       -- /home/rjones/d/qemu/qemu-io 
IMGFMT        -- raw
IMGPROTO      -- ssh
PLATFORM      -- Linux/x86_64 choo 3.7.2-204.fc18.x86_64

001 7s ...
002 11s ...
003 11s ...
004 19s ...
005 4s ...
006  [not run] not suitable for this image format: raw
007 18s ... [not run] not suitable for this image format: raw
008 8s ...
009 3s ...
010 4s ...
011 17s ...
012  [not run] not suitable for this image protocol: ssh
013   [not run] not suitable for this image format: raw
014    [not run] not suitable for this image format: raw
015 53s ... [not run] not suitable for this image format: raw
016  [not run] not suitable for this image protocol: ssh
017   [not run] not suitable for this image format: raw
018    [not run] not suitable for this image format: raw
019     [not run] not suitable for this image format: raw
020	 [not run] not suitable for this image format: raw
021 48s ...
022 37s ... [not run] not suitable for this image format: raw
023  [not run] not suitable for this image format: raw
024   [not run] not suitable for this image format: raw
025    [not run] not suitable for this image protocol: ssh
026     [not run] not suitable for this image format: raw
027 7s ... [not run] not suitable for this image format: raw
028  [not run] not suitable for this image format: raw
029 10s ... [not run] not suitable for this image format: raw
030  [not run] not suitable for this image format: raw
031   [not run] not suitable for this image format: raw
032 5s ...
033 14s ...
034  [not run] not suitable for this image format: raw
035 3s ... [not run] not suitable for this image format: raw
036  [not run] not suitable for this image format: raw
037   [not run] not suitable for this image format: raw
038    [not run] not suitable for this image format: raw
039     [not run] not suitable for this image format: raw
040 10s ... [not run] not suitable for this image format: raw
041 20s ... [not run] not suitable for this image format: raw
042  [not run] not suitable for this image format: raw
043   [not run] not suitable for this image format: raw
044 29s ... [not run] not suitable for this image format: raw
045 1s ...
046  [not run] not suitable for this image format: raw
047 2s ... [not run] not suitable for this image format: raw
048  [not run] not suitable for this image protocol: ssh
049   [not run] not suitable for this image format: raw
050    [not run] not suitable for this image format: raw
052 13s ...
Not run: 006 007 012 013 014 015 016 017 018 019 020 022 023 024 025 026 027 028 029 030 031 034 035 036 037 038 039 040 041 042 043 044 046 047 048 049 050
Passed all 14 tests

Rich.
Stefan Hajnoczi April 8, 2013, 2:58 p.m. UTC | #8
On Mon, Apr 8, 2013 at 3:05 PM, Richard W.M. Jones <rjones@redhat.com> wrote:
> More specifically, here's the output on my machine:
>
> rjones@choo:~/d/qemu/tests/qemu-iotests$ QEMU_PROG=~/d/qemu/x86_64-softmmu/qemu-system-x86_64 PATH=~/d/qemu:$PATH ./check -ssh

gah, I just hit a libssh2 limitation.  In my .ssh/config I have:
NoHostAuthenticationForLocalhost yes

This stops ssh from complaining when I hope to another host through an
ssh tunnel (the host key wouldn't match localhost).

$ ssh localhost
...works fine...
$ ./qemu-img info ssh://localhost/home/stefanha/qemu/test.img
no host key was found in known_hosts:  (libssh2 error code: 0)
qemu-img: Could not open
'ssh://localhost/home/stefanha/qemu/test.img': Invalid argument

From what I can see libssh2 does not support loading .ssh/config.
This is a limitation not just for NoHostAuthenticationForLocalhost but
also for all the Hostname aliases with User options that I have in my
.ssh/config - I can't use them.  I remember the Fabric tool had
similar issues, it uses Python paramiko ssh implementation, and I
think they added to code to parse .ssh/config so all these
conveniences work:
https://github.com/paramiko/paramiko/blob/master/paramiko/config.py

What do you think?

Stefan
Stefan Hajnoczi April 8, 2013, 8:21 p.m. UTC | #9
On Mon, Apr 8, 2013 at 4:58 PM, Stefan Hajnoczi <stefanha@gmail.com> wrote:
> On Mon, Apr 8, 2013 at 3:05 PM, Richard W.M. Jones <rjones@redhat.com> wrote:
> From what I can see libssh2 does not support loading .ssh/config.

I was told that sshfs *does* handle .ssh/config.  Turns out that sshfs
spawns "ssh -s sftp" to get a SFTP subsystem channel.  Then it
directly implements the SFTP application protocol.

This way they don't need to link against libssh2.  They spawn ssh with
a socketpair on stdin/stdout.  They send/receive SFTP messages
directly.

The benefit is that everything works (options, host key handling, and
configuration files) like you'd expect from ssh/sftp/scp.

You may be tired of trying different alternatives, but perhaps
switching to this model is worth it.  It would solve these
integration/user friendliness issues that a libssh2 implementation
has.

Stefan
Richard W.M. Jones April 9, 2013, 7:30 a.m. UTC | #10
On Mon, Apr 08, 2013 at 10:21:44PM +0200, Stefan Hajnoczi wrote:
> On Mon, Apr 8, 2013 at 4:58 PM, Stefan Hajnoczi <stefanha@gmail.com> wrote:
> > On Mon, Apr 8, 2013 at 3:05 PM, Richard W.M. Jones <rjones@redhat.com> wrote:
> > From what I can see libssh2 does not support loading .ssh/config.
> 
> I was told that sshfs *does* handle .ssh/config.  Turns out that sshfs
> spawns "ssh -s sftp" to get a SFTP subsystem channel.  Then it
> directly implements the SFTP application protocol.
> 
> This way they don't need to link against libssh2.  They spawn ssh with
> a socketpair on stdin/stdout.  They send/receive SFTP messages
> directly.

Indeed, as I mentioned in an earlier message, sshfs implements the
complete SFTP stack itself and uses an external ssh process.

It's up to 5 times as much code to do so:

sshfs-fuse-2.4$ wc -l *.c
   589 cache.c
  3930 sshfs.c
    18 sshnodelay.c
  4537 total

qemu/block$ wc -l ssh.c
914 ssh.c

I don't think having an entire SFTP stack inside qemu would help.

> I just hit a libssh2 limitation.  In my .ssh/config I have:
> NoHostAuthenticationForLocalhost yes
> 
> This stops ssh from complaining when I hope to another host through an
> ssh tunnel (the host key wouldn't match localhost).

I'm using the ssh configuration attached for tunnelling through
another host.  It doesn't require toggling
'NoHostAuthenticationForLocalhost', and so is safer because it still
does host key checking.

I think a better and simpler way to solve this is simply to allow URLs
like:

  ssh://localhost/path?host_key_check=no

which is the same as NoHostAuthenticationForLocalhost (ie don't do any
host checking on this connection).

Even better would be to let people specify the key:

  ssh://localhost/path?host_key_check=aa:bb:cc:dd:ee:ff

This means that management applications can parse .ssh/config if they
feel like doing that.

Rich.

----------------------------------------------------------------------

My ssh tunnelling configuration:

Host tunnelled-host
  PreferredAuthentications publickey,keyboard-interactive,password
  ProxyCommand ssh -T -o ForwardAgent=yes proxy nc %h %p
Host proxy
  HostName proxy.example.com
Stefan Hajnoczi April 9, 2013, 12:56 p.m. UTC | #11
On Tue, Apr 09, 2013 at 08:30:44AM +0100, Richard W.M. Jones wrote:
> On Mon, Apr 08, 2013 at 10:21:44PM +0200, Stefan Hajnoczi wrote:
> > On Mon, Apr 8, 2013 at 4:58 PM, Stefan Hajnoczi <stefanha@gmail.com> wrote:
> > > On Mon, Apr 8, 2013 at 3:05 PM, Richard W.M. Jones <rjones@redhat.com> wrote:
> > > From what I can see libssh2 does not support loading .ssh/config.
> > 
> > I was told that sshfs *does* handle .ssh/config.  Turns out that sshfs
> > spawns "ssh -s sftp" to get a SFTP subsystem channel.  Then it
> > directly implements the SFTP application protocol.
> > 
> > This way they don't need to link against libssh2.  They spawn ssh with
> > a socketpair on stdin/stdout.  They send/receive SFTP messages
> > directly.
> 
> Indeed, as I mentioned in an earlier message, sshfs implements the
> complete SFTP stack itself and uses an external ssh process.
> 
> It's up to 5 times as much code to do so:
> 
> sshfs-fuse-2.4$ wc -l *.c
>    589 cache.c
>   3930 sshfs.c
>     18 sshnodelay.c
>   4537 total
> 
> qemu/block$ wc -l ssh.c
> 914 ssh.c
> 
> I don't think having an entire SFTP stack inside qemu would help.

How many SFTP messages do you need?  Probably just a handfull (read,
write, fsync, open, close).

sshfs does way more than just that.  It implements the entire FUSE VFS
interface and a cache.  So I think the lines of code comparison isn't
apples to apples.

The more practical reason for not spawning an external ssh process would
be that QEMU is increasingly being jailed and handed only file
descriptors.  This works well for a TCP socket but is messier if the
management stack has to launch SSH on behalf of QEMU first before
handing the socketpair.

Anyway, the reason I like the external ssh process approach is that we
get all the standard hostkey and configuration file handling.  Usability
is important, if the integration has too many rough edges, people will
not use the block driver.

> > I just hit a libssh2 limitation.  In my .ssh/config I have:
> > NoHostAuthenticationForLocalhost yes
> > 
> > This stops ssh from complaining when I hope to another host through an
> > ssh tunnel (the host key wouldn't match localhost).
> 
> I'm using the ssh configuration attached for tunnelling through
> another host.  It doesn't require toggling
> 'NoHostAuthenticationForLocalhost', and so is safer because it still
> does host key checking.

Cool, thanks for sharing that.

> I think a better and simpler way to solve this is simply to allow URLs
> like:
> 
>   ssh://localhost/path?host_key_check=no
> 
> which is the same as NoHostAuthenticationForLocalhost (ie don't do any
> host checking on this connection).
> 
> Even better would be to let people specify the key:
> 
>   ssh://localhost/path?host_key_check=aa:bb:cc:dd:ee:ff
> 
> This means that management applications can parse .ssh/config if they
> feel like doing that.

These are steps in the right direction of making -drive ssh:// easy to
use.

Stefan
diff mbox

Patch

diff --git a/block/Makefile.objs b/block/Makefile.objs
index c067f38..6c4b5bc 100644
--- a/block/Makefile.objs
+++ b/block/Makefile.objs
@@ -13,6 +13,7 @@  block-obj-$(CONFIG_LIBISCSI) += iscsi.o
 block-obj-$(CONFIG_CURL) += curl.o
 block-obj-$(CONFIG_RBD) += rbd.o
 block-obj-$(CONFIG_GLUSTERFS) += gluster.o
+block-obj-$(CONFIG_LIBSSH2) += ssh.o
 endif
 
 common-obj-y += stream.o
diff --git a/block/ssh.c b/block/ssh.c
new file mode 100644
index 0000000..c25e33f
--- /dev/null
+++ b/block/ssh.c
@@ -0,0 +1,878 @@ 
+/*
+ * Secure Shell (ssh) backend for QEMU.
+ *
+ * Copyright (C) 2013 Red Hat Inc., Richard W.M. Jones <rjones@redhat.com>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
+ * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <stdarg.h>
+
+#ifndef _WIN32
+#include <pwd.h>
+#endif
+
+#include <libssh2.h>
+#include <libssh2_sftp.h>
+
+#include "block/block_int.h"
+#include "qemu/sockets.h"
+#include "qemu/uri.h"
+#include "qapi/qmp/qint.h"
+
+#define DEBUG_SSH 0
+
+#if DEBUG_SSH
+#define DPRINTF(fmt,...)                                                \
+    do {                                                                \
+        fprintf(stderr, "ssh: %-15s " fmt "\n", __func__, ##__VA_ARGS__); \
+    } while (0)
+#else
+#define DPRINTF(fmt,...) /* nothing */
+#endif
+
+typedef struct BDRVSSHState {
+    /* Coroutine. */
+    CoMutex lock;
+
+    /* SSH connection. */
+    int sock;                         /* socket */
+    LIBSSH2_SESSION *session;         /* ssh session */
+    LIBSSH2_SFTP *sftp;               /* sftp session */
+    LIBSSH2_SFTP_HANDLE *sftp_handle; /* sftp remote file handle */
+
+    /* See ssh_seek() function below. */
+    int64_t offset;
+    bool offset_op_read;
+} BDRVSSHState;
+
+static void ssh_state_init(BDRVSSHState *s)
+{
+    memset(s, 0, sizeof *s);
+    s->sock = -1;
+    s->offset = -1;
+    qemu_co_mutex_init(&s->lock);
+}
+
+static void ssh_state_free(BDRVSSHState *s)
+{
+    if (s->sftp_handle) {
+        libssh2_sftp_close(s->sftp_handle);
+    }
+    if (s->sftp) {
+        libssh2_sftp_shutdown(s->sftp);
+    }
+    if (s->session) {
+        libssh2_session_disconnect(s->session,
+                                   "from qemu ssh client: "
+                                   "user closed the connection");
+        libssh2_session_free(s->session);
+    }
+    if (s->sock >= 0) {
+        close(s->sock);
+    }
+}
+
+/* Wrappers around error_report which make sure to dump as much
+ * information from libssh2 as possible.
+ */
+static void
+session_error_report(BDRVSSHState *s, const char *fs, ...)
+{
+    va_list args;
+
+    va_start(args, fs);
+
+    if ((s)->session) {
+        char *ssh_err;
+        int ssh_err_len = sizeof ssh_err;
+        int ssh_err_code;
+
+        libssh2_session_last_error((s)->session,
+                                   &ssh_err, &ssh_err_len, 0);
+        /* This is not an errno.  See <libssh2.h>. */
+        ssh_err_code = libssh2_session_last_errno((s)->session);
+
+        error_vprintf(fs, args);
+        error_printf(": %s (libssh2 error code: %d)", ssh_err, ssh_err_code);
+    }
+    else {
+        error_vprintf(fs, args);
+    }
+
+    va_end(args);
+    error_printf("\n");
+}
+
+static void
+sftp_error_report(BDRVSSHState *s, const char *fs, ...)
+{
+    va_list args;
+
+    va_start(args, fs);
+
+    if ((s)->sftp) {
+        char *ssh_err;
+        int ssh_err_len = sizeof ssh_err;
+        int ssh_err_code;
+        unsigned long sftp_err_code;
+
+        libssh2_session_last_error((s)->session,
+                                   &ssh_err, &ssh_err_len, 0);
+        /* This is not an errno.  See <libssh2.h>. */
+        ssh_err_code = libssh2_session_last_errno((s)->session);
+        /* See <libssh2_sftp.h>. */
+        sftp_err_code = libssh2_sftp_last_error((s)->sftp);
+
+        error_vprintf(fs, args);
+        error_printf(": %s (libssh2 error code: %d, sftp error code: %lu)",
+                     ssh_err, ssh_err_code, sftp_err_code);
+    }
+    else {
+        error_vprintf(fs, args);
+    }
+
+    va_end(args);
+    error_printf("\n");
+}
+
+#ifndef _WIN32
+static const char *get_username(void)
+{
+    struct passwd *pwd;
+
+    pwd = getpwuid(geteuid ());
+    if (!pwd) {
+        error_report("failed to get current user name");
+        return NULL;
+    }
+    return pwd->pw_name;
+}
+#else
+static const char *get_username(void)
+{
+    error_report("on Windows, specify a remote user name in the URI");
+    return NULL;
+}
+#endif
+
+static int parse_uri(const char *filename, QDict *options)
+{
+    URI *uri;
+    char *host = NULL;
+
+    uri = uri_parse(filename);
+    if (!uri) {
+        return -EINVAL;
+    }
+
+    if (strcmp(uri->scheme, "ssh") != 0) {
+        error_report("URI scheme must be 'ssh'");
+        goto err;
+    }
+
+    if (!uri->server || strcmp(uri->server, "") == 0) {
+        error_report("missing hostname in URI");
+        goto err;
+    }
+
+    if (!uri->path || strcmp(uri->path, "") == 0) {
+        error_report("missing remote path in URI");
+        goto err;
+    }
+
+    if(uri->user && strcmp(uri->user, "") != 0) {
+        qdict_put(options, "user", qstring_from_str(uri->user));
+    }
+
+    qdict_put(options, "host", qstring_from_str(uri->server));
+
+    if (uri->port) {
+        qdict_put(options, "port", qint_from_int(uri->port));
+    }
+
+    qdict_put(options, "path", qstring_from_str(uri->path));
+
+    uri_free(uri);
+    free(host);
+    return 0;
+
+ err:
+    uri_free(uri);
+    free(host);
+    return -EINVAL;
+}
+
+static void ssh_parse_filename(const char *filename, QDict *options,
+                               Error **errp)
+{
+    if (qdict_haskey(options, "user") ||
+        qdict_haskey(options, "host") ||
+        qdict_haskey(options, "port") ||
+        qdict_haskey(options, "path")) {
+        error_setg(errp, "user, host, port or path cannot be used at the same time as a file option");
+        return;
+    }
+
+    if (parse_uri(filename, options) < 0) {
+        error_setg(errp, "no valid URL specified");
+    }
+}
+
+static int check_host_key(BDRVSSHState *s, const char *host, int port)
+{
+    int ret;
+    const char *home;
+    char *knh_file = NULL;
+    LIBSSH2_KNOWNHOSTS *knh = NULL;
+    const char *fingerprint;
+    size_t len;
+    int type;
+
+    knh = libssh2_knownhost_init(s->session);
+    if (!knh) {
+        ret = -EINVAL;
+        session_error_report(s, "failed to initialize known hosts support");
+        goto out;
+    }
+
+    home = getenv("HOME");
+    if (home) {
+        knh_file = g_strdup_printf("%s/.ssh/known_hosts", home);
+    } else {
+        knh_file = g_strdup_printf("/root/.ssh/known_hosts");
+    }
+
+    /* Read all known hosts from OpenSSH-style known_hosts file. */
+    libssh2_knownhost_readfile(knh, knh_file, LIBSSH2_KNOWNHOST_FILE_OPENSSH);
+
+    fingerprint = libssh2_session_hostkey(s->session, &len, &type);
+    if (fingerprint) {
+        struct libssh2_knownhost *found;
+        int r;
+
+        r = libssh2_knownhost_checkp(knh, host, port, fingerprint, len,
+                                     LIBSSH2_KNOWNHOST_TYPE_PLAIN|
+                                     LIBSSH2_KNOWNHOST_KEYENC_RAW,
+                                     &found);
+        switch (r) {
+        case LIBSSH2_KNOWNHOST_CHECK_MATCH:
+            /* OK */
+            DPRINTF("host key OK: %s", found->key);
+            break;
+        case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:
+            ret = -EINVAL;
+            session_error_report(s, "host key does not match the one in known_hosts (found key %s)",
+                                 found->key);
+            goto out;
+        case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND:
+            ret = -EINVAL;
+            session_error_report(s, "no host key was found in known_hosts");
+            goto out;
+        case LIBSSH2_KNOWNHOST_CHECK_FAILURE:
+            ret = -EINVAL;
+            session_error_report(s, "failure matching the host key with known_hosts");
+            goto out;
+        default:
+            ret = -EINVAL;
+            session_error_report(s, "unknown error matching the host key with known_hosts (%d)",
+                                 r);
+            goto out;
+        }
+    }
+
+    ret = 0;
+
+ out:
+    if (knh != NULL) {
+        libssh2_knownhost_free(knh);
+    }
+    g_free(knh_file);
+    return ret;
+}
+
+static int authenticate(BDRVSSHState *s, const char *user)
+{
+    int r, ret;
+    const char *userauthlist;
+    LIBSSH2_AGENT *agent = NULL;
+    struct libssh2_agent_publickey *identity;
+    struct libssh2_agent_publickey *prev_identity = NULL;
+
+    userauthlist = libssh2_userauth_list(s->session, user, strlen(user));
+    if (strstr(userauthlist, "publickey") == NULL) {
+        ret = -EPERM;
+        error_report("remote server does not support \"publickey\" authentication");
+        goto out;
+    }
+
+    /* Connect to ssh-agent and try each identity in turn. */
+    agent = libssh2_agent_init(s->session);
+    if (!agent) {
+        ret = -EINVAL;
+        session_error_report(s, "failed to initialize ssh-agent support");
+        goto out;
+    }
+    if (libssh2_agent_connect(agent)) {
+        ret = -ECONNREFUSED;
+        session_error_report(s, "failed to connect to ssh-agent");
+        goto out;
+    }
+    if (libssh2_agent_list_identities(agent)) {
+        ret = -EINVAL;
+        session_error_report(s, "failed requesting identities from ssh-agent");
+        goto out;
+    }
+
+    for(;;) {
+        r = libssh2_agent_get_identity(agent, &identity, prev_identity);
+        if (r == 1) {           /* end of list */
+            break;
+        }
+        if (r < 0) {
+            ret = -EINVAL;
+            session_error_report(s, "failed to obtain identity from ssh-agent");
+            goto out;
+        }
+        r = libssh2_agent_userauth(agent, user, identity);
+        if (r == 0) {
+            /* Authenticated! */
+            ret = 0;
+            goto out;
+        }
+        /* Failed to authenticate with this identity, try the next one. */
+        prev_identity = identity;
+    }
+
+    ret = -EPERM;
+    error_report("failed to authenticate using publickey authentication "
+                 "and the identities held by your ssh-agent");
+
+ out:
+    if (agent != NULL) {
+        /* Note: libssh2 implementation implicitly calls
+         * libssh2_agent_disconnect if necessary.
+         */
+        libssh2_agent_free(agent);
+    }
+
+    return ret;
+}
+
+static int connect_to_ssh(BDRVSSHState *s, QDict *options,
+                          int ssh_flags, int creat_mode)
+{
+    int r, ret;
+    Error *err = NULL;
+    const char *host, *user, *path;
+    int port;
+    char *hostport = NULL;
+
+    host = qdict_get_str(options, "host");
+
+    if (qdict_haskey(options, "port")) {
+        port = qdict_get_int(options, "port");
+    } else {
+        port = 22;
+    }
+
+    path = qdict_get_str(options, "path");
+
+    if (qdict_haskey(options, "user")) {
+        user = qdict_get_str(options, "user");
+    } else {
+        user = get_username();
+        if (!user) {
+            ret = -EINVAL;
+            goto err;
+        }
+    }
+
+    /* Open the socket and connect. */
+    hostport = g_strdup_printf("%s:%d", host, port);
+    s->sock = inet_connect(hostport, &err);
+    if (err != NULL) {
+        ret = -errno;
+        qerror_report_err(err);
+        error_free(err);
+        goto err;
+    }
+
+    /* Create SSH session. */
+    s->session = libssh2_session_init();
+    if (!s->session) {
+        ret = -EINVAL;
+        session_error_report(s, "failed to initialize libssh2 session");
+        goto err;
+    }
+
+    r = libssh2_session_handshake(s->session, s->sock);
+    if (r != 0) {
+        ret = -EINVAL;
+        session_error_report(s, "failed to establish SSH session");
+        goto err;
+    }
+
+    /* Check the remote host's key against known_hosts. */
+    ret = check_host_key(s, host, port);
+    if (ret < 0) {
+        goto err;
+    }
+
+    /* Authenticate. */
+    ret = authenticate(s, user);
+    if (ret < 0) {
+        goto err;
+    }
+
+    /* Start SFTP. */
+    s->sftp = libssh2_sftp_init(s->session);
+    if (!s->sftp) {
+        session_error_report(s, "failed to initialize sftp handle");
+        ret = -EINVAL;
+        goto err;
+    }
+
+    /* Open the remote file. */
+    DPRINTF("opening file %s flags=0x%x creat_mode=0%o",
+            path, ssh_flags, creat_mode);
+    s->sftp_handle = libssh2_sftp_open(s->sftp, path, ssh_flags, creat_mode);
+    if (!s->sftp_handle) {
+        session_error_report(s, "failed to open remote file '%s'", path);
+        ret = -EINVAL;
+        goto err;
+    }
+
+    /* Delete the options we've used; any not deleted will cause the
+     * block layer to give an error about unused options.
+     */
+    qdict_del(options, "host");
+    qdict_del(options, "port");
+    qdict_del(options, "user");
+    qdict_del(options, "path");
+
+    g_free(hostport);
+    return 0;
+
+ err:
+    if (s->sftp_handle) {
+        libssh2_sftp_close(s->sftp_handle);
+    }
+    s->sftp_handle = NULL;
+    if (s->sftp) {
+        libssh2_sftp_shutdown(s->sftp);
+    }
+    s->sftp = NULL;
+    if (s->session) {
+        libssh2_session_disconnect(s->session,
+                                   "from qemu ssh client: "
+                                   "error opening connection");
+        libssh2_session_free(s->session);
+    }
+    s->session = NULL;
+    g_free(hostport);
+
+    return ret;
+}
+
+static int ssh_file_open(BlockDriverState *bs, const char *filename,
+                         QDict *options, int bdrv_flags)
+{
+    BDRVSSHState *s = bs->opaque;
+    int ret;
+    int ssh_flags;
+
+    ssh_state_init(s);
+
+    ssh_flags = LIBSSH2_FXF_READ;
+    if (bdrv_flags & BDRV_O_RDWR) {
+        ssh_flags |= LIBSSH2_FXF_WRITE;
+    }
+
+    /* Start up SSH. */
+    ret = connect_to_ssh(s, options, ssh_flags, 0);
+    if (ret < 0) {
+        goto err;
+    }
+
+    /* Go non-blocking. */
+    libssh2_session_set_blocking(s->session, 0);
+
+    return 0;
+
+ err:
+    if (s->sock >= 0) {
+        close(s->sock);
+    }
+    s->sock = -1;
+
+    return ret;
+}
+
+static QEMUOptionParameter ssh_create_options[] = {
+    {
+        .name = BLOCK_OPT_SIZE,
+        .type = OPT_SIZE,
+        .help = "Virtual disk size"
+    },
+    { NULL }
+};
+
+static int ssh_create(const char *filename, QEMUOptionParameter *options)
+{
+    int r, ret;
+    int64_t total_size = 0;
+    QDict *uri_options = NULL;
+    BDRVSSHState s;
+    ssize_t r2;
+    char c[1] = { '\0' };
+
+    ssh_state_init(&s);
+
+    /* Get desired file size. */
+    while (options && options->name) {
+        if (!strcmp(options->name, BLOCK_OPT_SIZE)) {
+            total_size = options->value.n;
+        }
+        options++;
+    }
+    DPRINTF("total_size=%" PRIi64, total_size);
+
+    uri_options = qdict_new();
+    r = parse_uri(filename, uri_options);
+    if (r < 0) {
+        ret = r;
+        goto out;
+    }
+
+    r = connect_to_ssh(&s, uri_options,
+                       LIBSSH2_FXF_READ|LIBSSH2_FXF_WRITE|
+                       LIBSSH2_FXF_CREAT|LIBSSH2_FXF_TRUNC, 0644);
+    if (r < 0) {
+        ret = r;
+        goto out;
+    }
+
+    if (total_size > 0) {
+        libssh2_sftp_seek64(s.sftp_handle, total_size-1);
+        r2 = libssh2_sftp_write(s.sftp_handle, c, 1);
+        if (r2 < 0) {
+            sftp_error_report(&s, "truncate failed");
+            ret = -EINVAL;
+            goto out;
+        }
+    }
+
+    ret = 0;
+
+ out:
+    ssh_state_free(&s);
+    if (uri_options != NULL) {
+        QDECREF(uri_options);
+    }
+    return ret;
+}
+
+static void ssh_close(BlockDriverState *bs)
+{
+    BDRVSSHState *s = bs->opaque;
+
+    ssh_state_free(s);
+}
+
+static void restart_coroutine(void *opaque)
+{
+    Coroutine *co = opaque;
+
+    qemu_coroutine_enter(co, NULL);
+}
+
+/* Always true because when we have called set_fd_handler there is
+ * always a request being processed.
+ */
+static int return_true(void *opaque)
+{
+    return 1;
+}
+
+static coroutine_fn void set_fd_handler(BDRVSSHState *s)
+{
+    int r;
+    IOHandler *rd_handler = NULL, *wr_handler = NULL;
+    Coroutine *co = qemu_coroutine_self();
+
+    r = libssh2_session_block_directions(s->session);
+
+    if (r & LIBSSH2_SESSION_BLOCK_INBOUND) {
+        rd_handler = restart_coroutine;
+    }
+    if (r & LIBSSH2_SESSION_BLOCK_OUTBOUND) {
+        wr_handler = restart_coroutine;
+    }
+
+    DPRINTF("s->sock=%d rd_handler=%p wr_handler=%p", s->sock,
+            rd_handler, wr_handler);
+
+    qemu_aio_set_fd_handler(s->sock, rd_handler, wr_handler, return_true, co);
+}
+
+static coroutine_fn void clear_fd_handler(BDRVSSHState *s)
+{
+    qemu_aio_set_fd_handler(s->sock, NULL, NULL, NULL, NULL);
+}
+
+/* A non-blocking call returned EAGAIN, so yield, ensuring the
+ * handlers are set up so that we'll be rescheduled when there is an
+ * interesting event on the socket.
+ */
+static coroutine_fn void co_yield(BDRVSSHState *s)
+{
+    set_fd_handler(s);
+    qemu_coroutine_yield();
+    clear_fd_handler(s);
+}
+
+/* SFTP has a function `libssh2_sftp_seek64' which seeks to a position
+ * in the remote file.  Notice that it just updates a field in the
+ * sftp_handle structure, so there is no network traffic and it cannot
+ * fail.
+ *
+ * However, `libssh2_sftp_seek64' does have a catastrophic effect on
+ * performance since it causes the handle to throw away all in-flight
+ * reads and buffered readahead data.  Therefore this function tries
+ * to be intelligent about when to call the underlying libssh2 function.
+ */
+#define SSH_SEEK_WRITE 0
+#define SSH_SEEK_READ  1
+#define SSH_SEEK_FORCE 2
+
+static void ssh_seek(BDRVSSHState *s, int64_t offset, int flags)
+{
+    bool op_read = (flags & SSH_SEEK_READ) != 0;
+    bool force = (flags & SSH_SEEK_FORCE) != 0;
+
+    if (force || op_read != s->offset_op_read || offset != s->offset) {
+        DPRINTF("seeking to offset=%" PRIi64, offset);
+        libssh2_sftp_seek64(s->sftp_handle, offset);
+        s->offset = offset;
+        s->offset_op_read = op_read;
+    }
+}
+
+static coroutine_fn int ssh_read(BDRVSSHState *s,
+                                 int64_t offset, size_t size,
+                                 QEMUIOVector *qiov)
+{
+    ssize_t r;
+    size_t got;
+    char *buf, *end_of_vec;
+    struct iovec *i;
+
+    DPRINTF("offset=%" PRIi64 " size=%zu", offset, size);
+
+    ssh_seek(s, offset, SSH_SEEK_READ);
+
+    /* This keeps track of the current iovec element ('i'), where we
+     * will write to next ('buf'), and the end of the current iovec
+     * ('end_of_vec').
+     */
+    i = &qiov->iov[0];
+    buf = i->iov_base;
+    end_of_vec = i->iov_base + i->iov_len;
+
+    /* libssh2 has a hard-coded limit of 2000 bytes per request,
+     * although it will also do readahead behind our backs.  Therefore
+     * we may have to do repeated reads here until we have read 'size'
+     * bytes.
+     */
+    for (got = 0; got < size; ) {
+    again:
+        DPRINTF("sftp_read buf=%p size=%zu", buf, end_of_vec - buf);
+        r = libssh2_sftp_read(s->sftp_handle, buf, end_of_vec - buf);
+        DPRINTF("sftp_read returned %zd", r);
+
+        if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
+            co_yield(s);
+            goto again;
+        }
+        if (r < 0) {
+            sftp_error_report(s, "read failed");
+            s->offset = -1;
+            return -EIO;
+        }
+        if (r == 0) {
+            /* EOF: Short read so pad the buffer with zeroes and return it. */
+            qemu_iovec_memset(qiov, got, 0, size - got);
+            return 0;
+        }
+
+        got += r;
+        buf += r;
+        s->offset += r;
+        if (buf >= end_of_vec && got < size) {
+            i++;
+            buf = i->iov_base;
+            end_of_vec = i->iov_base + i->iov_len;
+        }
+    }
+
+    return 0;
+}
+
+static coroutine_fn int ssh_co_readv(BlockDriverState *bs,
+                                     int64_t sector_num,
+                                     int nb_sectors, QEMUIOVector *qiov)
+{
+    BDRVSSHState *s = bs->opaque;
+    int ret;
+
+    qemu_co_mutex_lock(&s->lock);
+    ret = ssh_read(s, sector_num * BDRV_SECTOR_SIZE,
+                   nb_sectors * BDRV_SECTOR_SIZE, qiov);
+    qemu_co_mutex_unlock(&s->lock);
+
+    return ret;
+}
+
+static int ssh_write(BDRVSSHState *s,
+                     int64_t offset, size_t size,
+                     QEMUIOVector *qiov)
+{
+    ssize_t r;
+    size_t written;
+    char *buf, *end_of_vec;
+    struct iovec *i;
+
+    DPRINTF("offset=%" PRIi64 " size=%zu", offset, size);
+
+    ssh_seek(s, offset, SSH_SEEK_WRITE);
+
+    /* This keeps track of the current iovec element ('i'), where we
+     * will read from next ('buf'), and the end of the current iovec
+     * ('end_of_vec').
+     */
+    i = &qiov->iov[0];
+    buf = i->iov_base;
+    end_of_vec = i->iov_base + i->iov_len;
+
+    for (written = 0; written < size; ) {
+    again:
+        DPRINTF("sftp_write buf=%p size=%zu", buf, end_of_vec - buf);
+        r = libssh2_sftp_write(s->sftp_handle, buf, end_of_vec - buf);
+        DPRINTF("sftp_write returned %zd", r);
+
+        if (r == LIBSSH2_ERROR_EAGAIN || r == LIBSSH2_ERROR_TIMEOUT) {
+            co_yield(s);
+            goto again;
+        }
+        if (r < 0) {
+            sftp_error_report(s, "write failed");
+            s->offset = -1;
+            return -EIO;
+        }
+        /* The libssh2 API is very unclear about this.  A comment in
+         * the code says "nothing was acked, and no EAGAIN was
+         * received!" which apparently means that no data got sent
+         * out, and the underlying channel didn't return any EAGAIN
+         * indication.  I think this is a bug in either libssh2 or
+         * OpenSSH (server-side).  In any case, forcing a seek (to
+         * discard libssh2 internal buffers), and then trying again
+         * works for me.
+         */
+        if (r == 0) {
+            ssh_seek(s, offset + written, SSH_SEEK_WRITE|SSH_SEEK_FORCE);
+            co_yield(s);
+            goto again;
+        }
+
+        written += r;
+        buf += r;
+        s->offset += r;
+        if (buf >= end_of_vec && written < size) {
+            i++;
+            buf = i->iov_base;
+            end_of_vec = i->iov_base + i->iov_len;
+        }
+    }
+
+    return 0;
+}
+
+static coroutine_fn int ssh_co_writev(BlockDriverState *bs,
+                                      int64_t sector_num,
+                                      int nb_sectors, QEMUIOVector *qiov)
+{
+    BDRVSSHState *s = bs->opaque;
+    int ret;
+
+    qemu_co_mutex_lock(&s->lock);
+    ret = ssh_write(s, sector_num * BDRV_SECTOR_SIZE,
+                    nb_sectors * BDRV_SECTOR_SIZE, qiov);
+    qemu_co_mutex_unlock(&s->lock);
+
+    return ret;
+}
+
+static int64_t ssh_getlength(BlockDriverState *bs)
+{
+    BDRVSSHState *s = bs->opaque;
+    int r;
+    LIBSSH2_SFTP_ATTRIBUTES attrs;
+
+    libssh2_session_set_blocking(s->session, 1);
+    r = libssh2_sftp_fstat(s->sftp_handle, &attrs);
+    libssh2_session_set_blocking(s->session, 0);
+    if (r < 0) {
+        sftp_error_report(s, "failed to read file attributes");
+        return -EINVAL;
+    }
+
+    return (int64_t) attrs.filesize;
+}
+
+static BlockDriver bdrv_ssh = {
+    .format_name                  = "ssh",
+    .protocol_name                = "ssh",
+    .instance_size                = sizeof(BDRVSSHState),
+    .bdrv_parse_filename          = ssh_parse_filename,
+    .bdrv_file_open               = ssh_file_open,
+    .bdrv_create                  = ssh_create,
+    .bdrv_close                   = ssh_close,
+    .bdrv_co_readv                = ssh_co_readv,
+    .bdrv_co_writev               = ssh_co_writev,
+    .bdrv_getlength               = ssh_getlength,
+    .create_options               = ssh_create_options,
+};
+
+static void bdrv_ssh_init(void)
+{
+    int r;
+
+    r = libssh2_init(0);
+    if (r != 0) {
+        fprintf(stderr, "libssh2 initialization failed, %d\n", r);
+        exit(EXIT_FAILURE);
+    }
+
+    bdrv_register(&bdrv_ssh);
+}
+
+block_init(bdrv_ssh_init);
diff --git a/configure b/configure
index f2af714..d666066 100755
--- a/configure
+++ b/configure
@@ -229,6 +229,7 @@  virtio_blk_data_plane=""
 gtk=""
 gtkabi="2.0"
 tpm="no"
+libssh2=""
 
 # parse CC options first
 for opt do
@@ -908,6 +909,10 @@  for opt do
   ;;
   --enable-tpm) tpm="yes"
   ;;
+  --disable-libssh2) libssh2="no"
+  ;;
+  --enable-libssh2) libssh2="yes"
+  ;;
   *) echo "ERROR: unknown option $opt"; show_help="yes"
   ;;
   esac
@@ -1166,6 +1171,7 @@  echo "  --disable-glusterfs      disable GlusterFS backend"
 echo "  --enable-gcov            enable test coverage analysis with gcov"
 echo "  --gcov=GCOV              use specified gcov [$gcov_tool]"
 echo "  --enable-tpm             enable TPM support"
+echo "  --enable-libssh2         enable ssh block device support"
 echo ""
 echo "NOTE: The object files are built at the place where configure is launched"
 exit 1
@@ -2330,6 +2336,42 @@  EOF
 fi
 
 ##########################################
+# libssh2 probe
+if test "$libssh2" != "no" ; then
+  cat > $TMPC <<EOF
+#include <stdio.h>
+#include <libssh2.h>
+#include <libssh2_sftp.h>
+int main(void) {
+    LIBSSH2_SESSION *session;
+    session = libssh2_session_init ();
+    (void) libssh2_sftp_init (session);
+    return 0;
+}
+EOF
+
+  if $pkg_config libssh2 --modversion >/dev/null 2>&1; then
+    libssh2_cflags=`$pkg_config libssh2 --cflags`
+    libssh2_libs=`$pkg_config libssh2 --libs`
+  else
+    libssh2_cflags=
+    libssh2_libs="-lssh2"
+  fi
+
+  if compile_prog "$libssh2_cflags" "$libssh2_libs" ; then
+    libssh2=yes
+    libs_tools="$libssh2_libs $libs_tools"
+    libs_softmmu="$libssh2_libs $libs_softmmu"
+    QEMU_CFLAGS="$QEMU_CFLAGS $libssh2_cflags"
+  else
+    if test "$libssh2" = "yes" ; then
+      feature_not_found "libssh2"
+    fi
+    libssh2=no
+  fi
+fi
+
+##########################################
 # linux-aio probe
 
 if test "$linux_aio" != "no" ; then
@@ -3441,6 +3483,7 @@  echo "virtio-blk-data-plane $virtio_blk_data_plane"
 echo "gcov              $gcov_tool"
 echo "gcov enabled      $gcov"
 echo "TPM support       $tpm"
+echo "libssh2 support   $libssh2"
 
 if test "$sdl_too_old" = "yes"; then
 echo "-> Your SDL version is too old - please upgrade to have SDL support"
@@ -3806,6 +3849,10 @@  if test "$glusterfs" = "yes" ; then
   echo "CONFIG_GLUSTERFS=y" >> $config_host_mak
 fi
 
+if test "$libssh2" = "yes" ; then
+  echo "CONFIG_LIBSSH2=y" >> $config_host_mak
+fi
+
 if test "$virtio_blk_data_plane" = "yes" ; then
   echo "CONFIG_VIRTIO_BLK_DATA_PLANE=y" >> $config_host_mak
 fi
diff --git a/qemu-doc.texi b/qemu-doc.texi
index af84bef..7a0f373 100644
--- a/qemu-doc.texi
+++ b/qemu-doc.texi
@@ -423,6 +423,7 @@  snapshots.
 * disk_images_sheepdog::      Sheepdog disk images
 * disk_images_iscsi::         iSCSI LUNs
 * disk_images_gluster::       GlusterFS disk images
+* disk_images_ssh::           Secure Shell (ssh) disk images
 @end menu
 
 @node disk_images_quickstart
@@ -1038,6 +1039,45 @@  qemu-system-x86_64 -drive file=gluster+unix:///testvol/dir/a.img?socket=/tmp/glu
 qemu-system-x86_64 -drive file=gluster+rdma://1.2.3.4:24007/testvol/a.img
 @end example
 
+@node disk_images_ssh
+@subsection Secure Shell (ssh) disk images
+
+You can access disk images located on a remote ssh server
+by using the ssh protocol:
+
+@example
+qemu-system-x86_64 -drive file=ssh://[@var{user}@@]@var{server}[:@var{port}]/@var{path}
+@end example
+
+Alternative syntax using properties:
+
+@example
+qemu-system-x86_64 -drive file.driver=ssh[,file.user=@var{user}],file.host=@var{server}[,file.port=@var{port}],file.path=@var{path}
+@end example
+
+@var{ssh} is the protocol.
+
+@var{user} is the remote user.  If not specified, then the local
+username is tried.
+
+@var{server} specifies the remote ssh server.  Any ssh server can be
+used, but it must implement the sftp-server protocol.  Most Unix/Linux
+systems should work without requiring any extra configuration.
+
+@var{port} is the port number on which sshd is listening.  By default
+the standard ssh port (22) is used.
+
+@var{path} is the path to the disk image.
+
+Currently authentication must be done using ssh-agent.  Other
+authentication methods may be supported in future.
+
+Note: The ssh driver does not obey disk flush requests (ie. to commit
+data to the backing disk when the guest requests it).  This is because
+the underlying protocol (SFTP) does not support this.  Thus there is a
+risk of guest disk corruption if the remote server or network goes
+down during writes.
+
 @node pcsys_network
 @section Network emulation
 
diff --git a/qemu-options.hx b/qemu-options.hx
index c40ba55..667ab43 100644
--- a/qemu-options.hx
+++ b/qemu-options.hx
@@ -2106,6 +2106,18 @@  Example for Unix Domain Sockets
 qemu-system-i386 --drive file=nbd:unix:/tmp/nbd-socket
 @end example
 
+@item SSH
+QEMU supports SSH (Secure Shell) access to remote disks.
+
+Examples:
+@example
+qemu-system-i386 -drive file=ssh://user@@host/path/to/disk.img
+qemu-system-i386 -drive file.driver=ssh,file.user=user,file.host=host,file.port=22,file.path=/path/to/disk.img
+@end example
+
+Currently authentication must be done using ssh-agent.  Other
+authentication methods may be supported in future.
+
 @item Sheepdog
 Sheepdog is a distributed storage system for QEMU.
 QEMU supports using either local sheepdog devices or remote networked