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