1 /* $OpenBSD: sshconnect2.c,v 1.375 2024/09/09 02:39:57 djm Exp $ */ 2 /* 3 * Copyright (c) 2000 Markus Friedl. All rights reserved. 4 * Copyright (c) 2008 Damien Miller. All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 */ 26 27 #include "includes.h" 28 29 #include <sys/types.h> 30 #include <sys/socket.h> 31 #include <sys/wait.h> 32 #include <sys/stat.h> 33 34 #include <errno.h> 35 #include <fcntl.h> 36 #include <limits.h> 37 #include <netdb.h> 38 #include <pwd.h> 39 #include <signal.h> 40 #include <stdio.h> 41 #include <string.h> 42 #include <stdarg.h> 43 #include <unistd.h> 44 #if defined(HAVE_STRNVIS) && defined(HAVE_VIS_H) && !defined(BROKEN_STRNVIS) 45 #include <vis.h> 46 #endif 47 48 #include "openbsd-compat/sys-queue.h" 49 50 #include "xmalloc.h" 51 #include "ssh.h" 52 #include "ssh2.h" 53 #include "sshbuf.h" 54 #include "packet.h" 55 #include "compat.h" 56 #include "cipher.h" 57 #include "sshkey.h" 58 #include "kex.h" 59 #include "sshconnect.h" 60 #include "authfile.h" 61 #include "dh.h" 62 #include "authfd.h" 63 #include "log.h" 64 #include "misc.h" 65 #include "readconf.h" 66 #include "match.h" 67 #include "dispatch.h" 68 #include "canohost.h" 69 #include "msg.h" 70 #include "pathnames.h" 71 #include "uidswap.h" 72 #include "hostfile.h" 73 #include "ssherr.h" 74 #include "utf8.h" 75 #include "ssh-sk.h" 76 #include "sk-api.h" 77 78 #ifdef GSSAPI 79 #include "ssh-gss.h" 80 #endif 81 82 /* import */ 83 extern Options options; 84 85 /* 86 * SSH2 key exchange 87 */ 88 89 static char *xxx_host; 90 static struct sockaddr *xxx_hostaddr; 91 static const struct ssh_conn_info *xxx_conn_info; 92 93 static int 94 verify_host_key_callback(struct sshkey *hostkey, struct ssh *ssh) 95 { 96 int r; 97 98 if ((r = sshkey_check_rsa_length(hostkey, 99 options.required_rsa_size)) != 0) 100 fatal_r(r, "Bad server host key"); 101 if (verify_host_key(xxx_host, xxx_hostaddr, hostkey, 102 xxx_conn_info) != 0) 103 fatal("Host key verification failed."); 104 return 0; 105 } 106 107 /* Returns the first item from a comma-separated algorithm list */ 108 static char * 109 first_alg(const char *algs) 110 { 111 char *ret, *cp; 112 113 ret = xstrdup(algs); 114 if ((cp = strchr(ret, ',')) != NULL) 115 *cp = '\0'; 116 return ret; 117 } 118 119 static char * 120 order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port, 121 const struct ssh_conn_info *cinfo) 122 { 123 char *oavail = NULL, *avail = NULL, *first = NULL, *last = NULL; 124 char *alg = NULL, *hostname = NULL, *ret = NULL, *best = NULL; 125 size_t maxlen; 126 struct hostkeys *hostkeys = NULL; 127 int ktype; 128 u_int i; 129 130 /* Find all hostkeys for this hostname */ 131 get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL); 132 hostkeys = init_hostkeys(); 133 for (i = 0; i < options.num_user_hostfiles; i++) 134 load_hostkeys(hostkeys, hostname, options.user_hostfiles[i], 0); 135 for (i = 0; i < options.num_system_hostfiles; i++) { 136 load_hostkeys(hostkeys, hostname, 137 options.system_hostfiles[i], 0); 138 } 139 if (options.known_hosts_command != NULL) { 140 load_hostkeys_command(hostkeys, options.known_hosts_command, 141 "ORDER", cinfo, NULL, hostname); 142 } 143 /* 144 * If a plain public key exists that matches the type of the best 145 * preference HostkeyAlgorithms, then use the whole list as is. 146 * Note that we ignore whether the best preference algorithm is a 147 * certificate type, as sshconnect.c will downgrade certs to 148 * plain keys if necessary. 149 */ 150 best = first_alg(options.hostkeyalgorithms); 151 if (lookup_key_in_hostkeys_by_type(hostkeys, 152 sshkey_type_plain(sshkey_type_from_name(best)), 153 sshkey_ecdsa_nid_from_name(best), NULL)) { 154 debug3_f("have matching best-preference key type %s, " 155 "using HostkeyAlgorithms verbatim", best); 156 ret = xstrdup(options.hostkeyalgorithms); 157 goto out; 158 } 159 160 /* 161 * Otherwise, prefer the host key algorithms that match known keys 162 * while keeping the ordering of HostkeyAlgorithms as much as possible. 163 */ 164 oavail = avail = xstrdup(options.hostkeyalgorithms); 165 maxlen = strlen(avail) + 1; 166 first = xmalloc(maxlen); 167 last = xmalloc(maxlen); 168 *first = *last = '\0'; 169 170 #define ALG_APPEND(to, from) \ 171 do { \ 172 if (*to != '\0') \ 173 strlcat(to, ",", maxlen); \ 174 strlcat(to, from, maxlen); \ 175 } while (0) 176 177 while ((alg = strsep(&avail, ",")) && *alg != '\0') { 178 if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC) 179 fatal_f("unknown alg %s", alg); 180 /* 181 * If we have a @cert-authority marker in known_hosts then 182 * prefer all certificate algorithms. 183 */ 184 if (sshkey_type_is_cert(ktype) && 185 lookup_marker_in_hostkeys(hostkeys, MRK_CA)) { 186 ALG_APPEND(first, alg); 187 continue; 188 } 189 /* If the key appears in known_hosts then prefer it */ 190 if (lookup_key_in_hostkeys_by_type(hostkeys, 191 sshkey_type_plain(ktype), 192 sshkey_ecdsa_nid_from_name(alg), NULL)) { 193 ALG_APPEND(first, alg); 194 continue; 195 } 196 /* Otherwise, put it last */ 197 ALG_APPEND(last, alg); 198 } 199 #undef ALG_APPEND 200 xasprintf(&ret, "%s%s%s", first, 201 (*first == '\0' || *last == '\0') ? "" : ",", last); 202 if (*first != '\0') 203 debug3_f("prefer hostkeyalgs: %s", first); 204 else 205 debug3_f("no algorithms matched; accept original"); 206 out: 207 free(best); 208 free(first); 209 free(last); 210 free(hostname); 211 free(oavail); 212 free_hostkeys(hostkeys); 213 214 return ret; 215 } 216 217 void 218 ssh_kex2(struct ssh *ssh, char *host, struct sockaddr *hostaddr, u_short port, 219 const struct ssh_conn_info *cinfo) 220 { 221 char *myproposal[PROPOSAL_MAX]; 222 char *all_key, *hkalgs = NULL; 223 int r, use_known_hosts_order = 0; 224 225 xxx_host = host; 226 xxx_hostaddr = hostaddr; 227 xxx_conn_info = cinfo; 228 229 if (options.rekey_limit || options.rekey_interval) 230 ssh_packet_set_rekey_limits(ssh, options.rekey_limit, 231 options.rekey_interval); 232 233 /* 234 * If the user has not specified HostkeyAlgorithms, or has only 235 * appended or removed algorithms from that list then prefer algorithms 236 * that are in the list that are supported by known_hosts keys. 237 */ 238 if (options.hostkeyalgorithms == NULL || 239 options.hostkeyalgorithms[0] == '-' || 240 options.hostkeyalgorithms[0] == '+') 241 use_known_hosts_order = 1; 242 243 /* Expand or fill in HostkeyAlgorithms */ 244 all_key = sshkey_alg_list(0, 0, 1, ','); 245 if ((r = kex_assemble_names(&options.hostkeyalgorithms, 246 kex_default_pk_alg(), all_key)) != 0) 247 fatal_fr(r, "kex_assemble_namelist"); 248 free(all_key); 249 250 if (use_known_hosts_order) 251 hkalgs = order_hostkeyalgs(host, hostaddr, port, cinfo); 252 253 kex_proposal_populate_entries(ssh, myproposal, 254 options.kex_algorithms, options.ciphers, options.macs, 255 compression_alg_list(options.compression), 256 hkalgs ? hkalgs : options.hostkeyalgorithms); 257 258 free(hkalgs); 259 260 /* start key exchange */ 261 if ((r = kex_setup(ssh, myproposal)) != 0) 262 fatal_r(r, "kex_setup"); 263 #ifdef WITH_OPENSSL 264 ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client; 265 ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client; 266 ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client; 267 ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client; 268 ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client; 269 ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client; 270 ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client; 271 # ifdef OPENSSL_HAS_ECC 272 ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client; 273 # endif 274 #endif 275 ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client; 276 ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client; 277 ssh->kex->kex[KEX_KEM_MLKEM768X25519_SHA256] = kex_gen_client; 278 ssh->kex->verify_host_key=&verify_host_key_callback; 279 280 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &ssh->kex->done); 281 kex_proposal_free_entries(myproposal); 282 283 #ifdef DEBUG_KEXDH 284 /* send 1st encrypted/maced/compressed message */ 285 if ((r = sshpkt_start(ssh, SSH2_MSG_IGNORE)) != 0 || 286 (r = sshpkt_put_cstring(ssh, "markus")) != 0 || 287 (r = sshpkt_send(ssh)) != 0 || 288 (r = ssh_packet_write_wait(ssh)) != 0) 289 fatal_fr(r, "send packet"); 290 #endif 291 } 292 293 /* 294 * Authenticate user 295 */ 296 297 typedef struct cauthctxt Authctxt; 298 typedef struct cauthmethod Authmethod; 299 typedef struct identity Identity; 300 typedef struct idlist Idlist; 301 302 struct identity { 303 TAILQ_ENTRY(identity) next; 304 int agent_fd; /* >=0 if agent supports key */ 305 struct sshkey *key; /* public/private key */ 306 char *filename; /* comment for agent-only keys */ 307 int tried; 308 int isprivate; /* key points to the private key */ 309 int userprovided; 310 }; 311 TAILQ_HEAD(idlist, identity); 312 313 struct cauthctxt { 314 const char *server_user; 315 const char *local_user; 316 const char *host; 317 const char *service; 318 struct cauthmethod *method; 319 sig_atomic_t success; 320 char *authlist; 321 #ifdef GSSAPI 322 /* gssapi */ 323 gss_OID_set gss_supported_mechs; 324 u_int mech_tried; 325 #endif 326 /* pubkey */ 327 struct idlist keys; 328 int agent_fd; 329 /* hostbased */ 330 Sensitive *sensitive; 331 char *oktypes, *ktypes; 332 const char *active_ktype; 333 /* kbd-interactive */ 334 int info_req_seen; 335 int attempt_kbdint; 336 /* password */ 337 int attempt_passwd; 338 /* generic */ 339 void *methoddata; 340 }; 341 342 struct cauthmethod { 343 char *name; /* string to compare against server's list */ 344 int (*userauth)(struct ssh *ssh); 345 void (*cleanup)(struct ssh *ssh); 346 int *enabled; /* flag in option struct that enables method */ 347 int *batch_flag; /* flag in option struct that disables method */ 348 }; 349 350 static int input_userauth_service_accept(int, u_int32_t, struct ssh *); 351 static int input_userauth_success(int, u_int32_t, struct ssh *); 352 static int input_userauth_failure(int, u_int32_t, struct ssh *); 353 static int input_userauth_banner(int, u_int32_t, struct ssh *); 354 static int input_userauth_error(int, u_int32_t, struct ssh *); 355 static int input_userauth_info_req(int, u_int32_t, struct ssh *); 356 static int input_userauth_pk_ok(int, u_int32_t, struct ssh *); 357 static int input_userauth_passwd_changereq(int, u_int32_t, struct ssh *); 358 359 static int userauth_none(struct ssh *); 360 static int userauth_pubkey(struct ssh *); 361 static int userauth_passwd(struct ssh *); 362 static int userauth_kbdint(struct ssh *); 363 static int userauth_hostbased(struct ssh *); 364 365 #ifdef GSSAPI 366 static int userauth_gssapi(struct ssh *); 367 static void userauth_gssapi_cleanup(struct ssh *); 368 static int input_gssapi_response(int type, u_int32_t, struct ssh *); 369 static int input_gssapi_token(int type, u_int32_t, struct ssh *); 370 static int input_gssapi_error(int, u_int32_t, struct ssh *); 371 static int input_gssapi_errtok(int, u_int32_t, struct ssh *); 372 #endif 373 374 void userauth(struct ssh *, char *); 375 376 static void pubkey_cleanup(struct ssh *); 377 static int sign_and_send_pubkey(struct ssh *ssh, Identity *); 378 static void pubkey_prepare(struct ssh *, Authctxt *); 379 static void pubkey_reset(Authctxt *); 380 static struct sshkey *load_identity_file(Identity *); 381 382 static Authmethod *authmethod_get(char *authlist); 383 static Authmethod *authmethod_lookup(const char *name); 384 static char *authmethods_get(void); 385 386 Authmethod authmethods[] = { 387 #ifdef GSSAPI 388 {"gssapi-with-mic", 389 userauth_gssapi, 390 userauth_gssapi_cleanup, 391 &options.gss_authentication, 392 NULL}, 393 #endif 394 {"hostbased", 395 userauth_hostbased, 396 NULL, 397 &options.hostbased_authentication, 398 NULL}, 399 {"publickey", 400 userauth_pubkey, 401 NULL, 402 &options.pubkey_authentication, 403 NULL}, 404 {"keyboard-interactive", 405 userauth_kbdint, 406 NULL, 407 &options.kbd_interactive_authentication, 408 &options.batch_mode}, 409 {"password", 410 userauth_passwd, 411 NULL, 412 &options.password_authentication, 413 &options.batch_mode}, 414 {"none", 415 userauth_none, 416 NULL, 417 NULL, 418 NULL}, 419 {NULL, NULL, NULL, NULL, NULL} 420 }; 421 422 void 423 ssh_userauth2(struct ssh *ssh, const char *local_user, 424 const char *server_user, char *host, Sensitive *sensitive) 425 { 426 Authctxt authctxt; 427 int r; 428 429 if (options.preferred_authentications == NULL) 430 options.preferred_authentications = authmethods_get(); 431 432 /* setup authentication context */ 433 memset(&authctxt, 0, sizeof(authctxt)); 434 authctxt.server_user = server_user; 435 authctxt.local_user = local_user; 436 authctxt.host = host; 437 authctxt.service = "ssh-connection"; /* service name */ 438 authctxt.success = 0; 439 authctxt.method = authmethod_lookup("none"); 440 authctxt.authlist = NULL; 441 authctxt.methoddata = NULL; 442 authctxt.sensitive = sensitive; 443 authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL; 444 authctxt.info_req_seen = 0; 445 authctxt.attempt_kbdint = 0; 446 authctxt.attempt_passwd = 0; 447 #if GSSAPI 448 authctxt.gss_supported_mechs = NULL; 449 authctxt.mech_tried = 0; 450 #endif 451 authctxt.agent_fd = -1; 452 if (authctxt.method == NULL) 453 fatal_f("internal error: cannot send userauth none request"); 454 455 if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 || 456 (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 || 457 (r = sshpkt_send(ssh)) != 0) 458 fatal_fr(r, "send packet"); 459 460 ssh->authctxt = &authctxt; 461 ssh_dispatch_init(ssh, &input_userauth_error); 462 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, kex_input_ext_info); 463 ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept); 464 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt.success); /* loop until success */ 465 pubkey_cleanup(ssh); 466 #ifdef GSSAPI 467 if (authctxt.gss_supported_mechs != NULL) { 468 u_int ms; 469 470 gss_release_oid_set(&ms, &authctxt.gss_supported_mechs); 471 authctxt.gss_supported_mechs = NULL; 472 } 473 #endif 474 ssh->authctxt = NULL; 475 476 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL); 477 478 if (!authctxt.success) 479 fatal("Authentication failed."); 480 if (ssh_packet_connection_is_on_socket(ssh)) { 481 verbose("Authenticated to %s ([%s]:%d) using \"%s\".", host, 482 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), 483 authctxt.method->name); 484 } else { 485 verbose("Authenticated to %s (via proxy) using \"%s\".", host, 486 authctxt.method->name); 487 } 488 } 489 490 static int 491 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh) 492 { 493 int r; 494 495 if (ssh_packet_remaining(ssh) > 0) { 496 char *reply; 497 498 if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0) 499 goto out; 500 debug2("service_accept: %s", reply); 501 free(reply); 502 } else { 503 debug2("buggy server: service_accept w/o service"); 504 } 505 if ((r = sshpkt_get_end(ssh)) != 0) 506 goto out; 507 debug("SSH2_MSG_SERVICE_ACCEPT received"); 508 509 /* initial userauth request */ 510 userauth_none(ssh); 511 512 /* accept EXT_INFO at any time during userauth */ 513 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, ssh->kex->ext_info_s ? 514 &kex_input_ext_info : &input_userauth_error); 515 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success); 516 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure); 517 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner); 518 r = 0; 519 out: 520 return r; 521 } 522 523 void 524 userauth(struct ssh *ssh, char *authlist) 525 { 526 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 527 528 if (authctxt->method != NULL && authctxt->method->cleanup != NULL) 529 authctxt->method->cleanup(ssh); 530 531 free(authctxt->methoddata); 532 authctxt->methoddata = NULL; 533 if (authlist == NULL) { 534 authlist = authctxt->authlist; 535 } else { 536 free(authctxt->authlist); 537 authctxt->authlist = authlist; 538 } 539 for (;;) { 540 Authmethod *method = authmethod_get(authlist); 541 if (method == NULL) 542 fatal("%s@%s: Permission denied (%s).", 543 authctxt->server_user, authctxt->host, authlist); 544 authctxt->method = method; 545 546 /* reset the per method handler */ 547 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_PER_METHOD_MIN, 548 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL); 549 550 /* and try new method */ 551 if (method->userauth(ssh) != 0) { 552 debug2("we sent a %s packet, wait for reply", method->name); 553 break; 554 } else { 555 debug2("we did not send a packet, disable method"); 556 method->enabled = NULL; 557 } 558 } 559 } 560 561 static int 562 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh) 563 { 564 fatal_f("bad message during authentication: type %d", type); 565 return 0; 566 } 567 568 static int 569 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh) 570 { 571 char *msg = NULL; 572 size_t len; 573 int r; 574 575 debug3_f("entering"); 576 if ((r = sshpkt_get_cstring(ssh, &msg, &len)) != 0 || 577 (r = sshpkt_get_cstring(ssh, NULL, NULL)) != 0) 578 goto out; 579 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO) 580 fmprintf(stderr, "%s", msg); 581 r = 0; 582 out: 583 free(msg); 584 return r; 585 } 586 587 static int 588 input_userauth_success(int type, u_int32_t seq, struct ssh *ssh) 589 { 590 Authctxt *authctxt = ssh->authctxt; 591 592 if (authctxt == NULL) 593 fatal_f("no authentication context"); 594 free(authctxt->authlist); 595 authctxt->authlist = NULL; 596 if (authctxt->method != NULL && authctxt->method->cleanup != NULL) 597 authctxt->method->cleanup(ssh); 598 free(authctxt->methoddata); 599 authctxt->methoddata = NULL; 600 authctxt->success = 1; /* break out */ 601 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, dispatch_protocol_error); 602 return 0; 603 } 604 605 #if 0 606 static int 607 input_userauth_success_unexpected(int type, u_int32_t seq, struct ssh *ssh) 608 { 609 Authctxt *authctxt = ssh->authctxt; 610 611 if (authctxt == NULL) 612 fatal_f("no authentication context"); 613 614 fatal("Unexpected authentication success during %s.", 615 authctxt->method->name); 616 return 0; 617 } 618 #endif 619 620 static int 621 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh) 622 { 623 Authctxt *authctxt = ssh->authctxt; 624 char *authlist = NULL; 625 u_char partial; 626 627 if (authctxt == NULL) 628 fatal("input_userauth_failure: no authentication context"); 629 630 if (sshpkt_get_cstring(ssh, &authlist, NULL) != 0 || 631 sshpkt_get_u8(ssh, &partial) != 0 || 632 sshpkt_get_end(ssh) != 0) 633 goto out; 634 635 if (partial != 0) { 636 verbose("Authenticated using \"%s\" with partial success.", 637 authctxt->method->name); 638 /* reset state */ 639 pubkey_reset(authctxt); 640 } 641 debug("Authentications that can continue: %s", authlist); 642 643 userauth(ssh, authlist); 644 authlist = NULL; 645 out: 646 free(authlist); 647 return 0; 648 } 649 650 /* 651 * Format an identity for logging including filename, key type, fingerprint 652 * and location (agent, etc.). Caller must free. 653 */ 654 static char * 655 format_identity(Identity *id) 656 { 657 char *fp = NULL, *ret = NULL; 658 const char *note = ""; 659 660 if (id->key != NULL) { 661 fp = sshkey_fingerprint(id->key, options.fingerprint_hash, 662 SSH_FP_DEFAULT); 663 } 664 if (id->key) { 665 if ((id->key->flags & SSHKEY_FLAG_EXT) != 0) 666 note = " token"; 667 else if (sshkey_is_sk(id->key)) 668 note = " authenticator"; 669 } 670 xasprintf(&ret, "%s %s%s%s%s%s%s", 671 id->filename, 672 id->key ? sshkey_type(id->key) : "", id->key ? " " : "", 673 fp ? fp : "", 674 id->userprovided ? " explicit" : "", note, 675 id->agent_fd != -1 ? " agent" : ""); 676 free(fp); 677 return ret; 678 } 679 680 static int 681 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh) 682 { 683 Authctxt *authctxt = ssh->authctxt; 684 struct sshkey *key = NULL; 685 Identity *id = NULL; 686 int pktype, found = 0, sent = 0; 687 size_t blen; 688 char *pkalg = NULL, *fp = NULL, *ident = NULL; 689 u_char *pkblob = NULL; 690 int r; 691 692 if (authctxt == NULL) 693 fatal("input_userauth_pk_ok: no authentication context"); 694 695 if ((r = sshpkt_get_cstring(ssh, &pkalg, NULL)) != 0 || 696 (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 || 697 (r = sshpkt_get_end(ssh)) != 0) 698 goto done; 699 700 if ((pktype = sshkey_type_from_name(pkalg)) == KEY_UNSPEC) { 701 debug_f("server sent unknown pkalg %s", pkalg); 702 r = SSH_ERR_INVALID_FORMAT; 703 goto done; 704 } 705 if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) { 706 debug_r(r, "no key from blob. pkalg %s", pkalg); 707 goto done; 708 } 709 if (key->type != pktype) { 710 error("input_userauth_pk_ok: type mismatch " 711 "for decoded key (received %d, expected %d)", 712 key->type, pktype); 713 r = SSH_ERR_INVALID_FORMAT; 714 goto done; 715 } 716 717 /* 718 * search keys in the reverse order, because last candidate has been 719 * moved to the end of the queue. this also avoids confusion by 720 * duplicate keys 721 */ 722 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) { 723 if (sshkey_equal(key, id->key)) { 724 found = 1; 725 break; 726 } 727 } 728 if (!found || id == NULL) { 729 fp = sshkey_fingerprint(key, options.fingerprint_hash, 730 SSH_FP_DEFAULT); 731 error_f("server replied with unknown key: %s %s", 732 sshkey_type(key), fp == NULL ? "<ERROR>" : fp); 733 r = SSH_ERR_INVALID_FORMAT; 734 goto done; 735 } 736 ident = format_identity(id); 737 debug("Server accepts key: %s", ident); 738 sent = sign_and_send_pubkey(ssh, id); 739 r = 0; 740 done: 741 sshkey_free(key); 742 free(ident); 743 free(fp); 744 free(pkalg); 745 free(pkblob); 746 747 /* try another method if we did not send a packet */ 748 if (r == 0 && sent == 0) 749 userauth(ssh, NULL); 750 return r; 751 } 752 753 #ifdef GSSAPI 754 static int 755 userauth_gssapi(struct ssh *ssh) 756 { 757 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 758 Gssctxt *gssctxt = NULL; 759 OM_uint32 min; 760 int r, ok = 0; 761 gss_OID mech = NULL; 762 763 /* Try one GSSAPI method at a time, rather than sending them all at 764 * once. */ 765 766 if (authctxt->gss_supported_mechs == NULL) 767 gss_indicate_mechs(&min, &authctxt->gss_supported_mechs); 768 769 /* Check to see whether the mechanism is usable before we offer it */ 770 while (authctxt->mech_tried < authctxt->gss_supported_mechs->count && 771 !ok) { 772 mech = &authctxt->gss_supported_mechs-> 773 elements[authctxt->mech_tried]; 774 /* My DER encoding requires length<128 */ 775 if (mech->length < 128 && ssh_gssapi_check_mechanism(&gssctxt, 776 mech, authctxt->host)) { 777 ok = 1; /* Mechanism works */ 778 } else { 779 authctxt->mech_tried++; 780 } 781 } 782 783 if (!ok || mech == NULL) 784 return 0; 785 786 authctxt->methoddata=(void *)gssctxt; 787 788 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 789 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 || 790 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 || 791 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 || 792 (r = sshpkt_put_u32(ssh, 1)) != 0 || 793 (r = sshpkt_put_u32(ssh, (mech->length) + 2)) != 0 || 794 (r = sshpkt_put_u8(ssh, SSH_GSS_OIDTYPE)) != 0 || 795 (r = sshpkt_put_u8(ssh, mech->length)) != 0 || 796 (r = sshpkt_put(ssh, mech->elements, mech->length)) != 0 || 797 (r = sshpkt_send(ssh)) != 0) 798 fatal_fr(r, "send packet"); 799 800 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response); 801 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token); 802 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error); 803 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok); 804 805 authctxt->mech_tried++; /* Move along to next candidate */ 806 807 return 1; 808 } 809 810 static void 811 userauth_gssapi_cleanup(struct ssh *ssh) 812 { 813 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 814 Gssctxt *gssctxt = (Gssctxt *)authctxt->methoddata; 815 816 ssh_gssapi_delete_ctx(&gssctxt); 817 authctxt->methoddata = NULL; 818 } 819 820 static OM_uint32 821 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok) 822 { 823 Authctxt *authctxt = ssh->authctxt; 824 Gssctxt *gssctxt = authctxt->methoddata; 825 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER; 826 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER; 827 gss_buffer_desc gssbuf; 828 OM_uint32 status, ms, flags; 829 int r; 830 831 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds, 832 recv_tok, &send_tok, &flags); 833 834 if (send_tok.length > 0) { 835 u_char type = GSS_ERROR(status) ? 836 SSH2_MSG_USERAUTH_GSSAPI_ERRTOK : 837 SSH2_MSG_USERAUTH_GSSAPI_TOKEN; 838 839 if ((r = sshpkt_start(ssh, type)) != 0 || 840 (r = sshpkt_put_string(ssh, send_tok.value, 841 send_tok.length)) != 0 || 842 (r = sshpkt_send(ssh)) != 0) 843 fatal_fr(r, "send %u packet", type); 844 845 gss_release_buffer(&ms, &send_tok); 846 } 847 848 if (status == GSS_S_COMPLETE) { 849 /* send either complete or MIC, depending on mechanism */ 850 if (!(flags & GSS_C_INTEG_FLAG)) { 851 if ((r = sshpkt_start(ssh, 852 SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE)) != 0 || 853 (r = sshpkt_send(ssh)) != 0) 854 fatal_fr(r, "send completion"); 855 } else { 856 struct sshbuf *b; 857 858 if ((b = sshbuf_new()) == NULL) 859 fatal_f("sshbuf_new failed"); 860 ssh_gssapi_buildmic(b, authctxt->server_user, 861 authctxt->service, "gssapi-with-mic", 862 ssh->kex->session_id); 863 864 if ((gssbuf.value = sshbuf_mutable_ptr(b)) == NULL) 865 fatal_f("sshbuf_mutable_ptr failed"); 866 gssbuf.length = sshbuf_len(b); 867 868 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic); 869 870 if (!GSS_ERROR(status)) { 871 if ((r = sshpkt_start(ssh, 872 SSH2_MSG_USERAUTH_GSSAPI_MIC)) != 0 || 873 (r = sshpkt_put_string(ssh, mic.value, 874 mic.length)) != 0 || 875 (r = sshpkt_send(ssh)) != 0) 876 fatal_fr(r, "send MIC"); 877 } 878 879 sshbuf_free(b); 880 gss_release_buffer(&ms, &mic); 881 } 882 } 883 884 return status; 885 } 886 887 static int 888 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh) 889 { 890 Authctxt *authctxt = ssh->authctxt; 891 Gssctxt *gssctxt; 892 size_t oidlen; 893 u_char *oidv = NULL; 894 int r; 895 896 if (authctxt == NULL) 897 fatal("input_gssapi_response: no authentication context"); 898 gssctxt = authctxt->methoddata; 899 900 /* Setup our OID */ 901 if ((r = sshpkt_get_string(ssh, &oidv, &oidlen)) != 0) 902 goto done; 903 904 if (oidlen <= 2 || 905 oidv[0] != SSH_GSS_OIDTYPE || 906 oidv[1] != oidlen - 2) { 907 debug("Badly encoded mechanism OID received"); 908 userauth(ssh, NULL); 909 goto ok; 910 } 911 912 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2)) 913 fatal("Server returned different OID than expected"); 914 915 if ((r = sshpkt_get_end(ssh)) != 0) 916 goto done; 917 918 if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) { 919 /* Start again with next method on list */ 920 debug("Trying to start again"); 921 userauth(ssh, NULL); 922 goto ok; 923 } 924 ok: 925 r = 0; 926 done: 927 free(oidv); 928 return r; 929 } 930 931 static int 932 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh) 933 { 934 Authctxt *authctxt = ssh->authctxt; 935 gss_buffer_desc recv_tok; 936 u_char *p = NULL; 937 size_t len; 938 OM_uint32 status; 939 int r; 940 941 if (authctxt == NULL) 942 fatal("input_gssapi_response: no authentication context"); 943 944 if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 || 945 (r = sshpkt_get_end(ssh)) != 0) 946 goto out; 947 948 recv_tok.value = p; 949 recv_tok.length = len; 950 status = process_gssapi_token(ssh, &recv_tok); 951 952 /* Start again with the next method in the list */ 953 if (GSS_ERROR(status)) { 954 userauth(ssh, NULL); 955 /* ok */ 956 } 957 r = 0; 958 out: 959 free(p); 960 return r; 961 } 962 963 static int 964 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh) 965 { 966 Authctxt *authctxt = ssh->authctxt; 967 Gssctxt *gssctxt; 968 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER; 969 gss_buffer_desc recv_tok; 970 OM_uint32 ms; 971 u_char *p = NULL; 972 size_t len; 973 int r; 974 975 if (authctxt == NULL) 976 fatal("input_gssapi_response: no authentication context"); 977 gssctxt = authctxt->methoddata; 978 979 if ((r = sshpkt_get_string(ssh, &p, &len)) != 0 || 980 (r = sshpkt_get_end(ssh)) != 0) { 981 free(p); 982 return r; 983 } 984 985 /* Stick it into GSSAPI and see what it says */ 986 recv_tok.value = p; 987 recv_tok.length = len; 988 (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds, 989 &recv_tok, &send_tok, NULL); 990 free(p); 991 gss_release_buffer(&ms, &send_tok); 992 993 /* Server will be returning a failed packet after this one */ 994 return 0; 995 } 996 997 static int 998 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh) 999 { 1000 char *msg = NULL; 1001 char *lang = NULL; 1002 int r; 1003 1004 if ((r = sshpkt_get_u32(ssh, NULL)) != 0 || /* maj */ 1005 (r = sshpkt_get_u32(ssh, NULL)) != 0 || /* min */ 1006 (r = sshpkt_get_cstring(ssh, &msg, NULL)) != 0 || 1007 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0) 1008 goto out; 1009 r = sshpkt_get_end(ssh); 1010 debug("Server GSSAPI Error:\n%s", msg); 1011 out: 1012 free(msg); 1013 free(lang); 1014 return r; 1015 } 1016 #endif /* GSSAPI */ 1017 1018 static int 1019 userauth_none(struct ssh *ssh) 1020 { 1021 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 1022 int r; 1023 1024 /* initial userauth request */ 1025 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1026 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 || 1027 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 || 1028 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 || 1029 (r = sshpkt_send(ssh)) != 0) 1030 fatal_fr(r, "send packet"); 1031 return 1; 1032 } 1033 1034 static int 1035 userauth_passwd(struct ssh *ssh) 1036 { 1037 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 1038 char *password, *prompt = NULL; 1039 const char *host = options.host_key_alias ? options.host_key_alias : 1040 authctxt->host; 1041 int r; 1042 1043 if (authctxt->attempt_passwd++ >= options.number_of_password_prompts) 1044 return 0; 1045 1046 if (authctxt->attempt_passwd != 1) 1047 error("Permission denied, please try again."); 1048 1049 xasprintf(&prompt, "%s@%s's password: ", authctxt->server_user, host); 1050 password = read_passphrase(prompt, 0); 1051 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1052 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 || 1053 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 || 1054 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 || 1055 (r = sshpkt_put_u8(ssh, 0)) != 0 || 1056 (r = sshpkt_put_cstring(ssh, password)) != 0 || 1057 (r = sshpkt_add_padding(ssh, 64)) != 0 || 1058 (r = sshpkt_send(ssh)) != 0) 1059 fatal_fr(r, "send packet"); 1060 1061 free(prompt); 1062 if (password != NULL) 1063 freezero(password, strlen(password)); 1064 1065 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, 1066 &input_userauth_passwd_changereq); 1067 1068 return 1; 1069 } 1070 1071 /* 1072 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST 1073 */ 1074 static int 1075 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh) 1076 { 1077 Authctxt *authctxt = ssh->authctxt; 1078 char *info = NULL, *lang = NULL, *password = NULL, *retype = NULL; 1079 char prompt[256]; 1080 const char *host; 1081 int r; 1082 1083 debug2("input_userauth_passwd_changereq"); 1084 1085 if (authctxt == NULL) 1086 fatal("input_userauth_passwd_changereq: " 1087 "no authentication context"); 1088 host = options.host_key_alias ? options.host_key_alias : authctxt->host; 1089 1090 if ((r = sshpkt_get_cstring(ssh, &info, NULL)) != 0 || 1091 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0) 1092 goto out; 1093 if (strlen(info) > 0) 1094 logit("%s", info); 1095 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1096 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 || 1097 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 || 1098 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 || 1099 (r = sshpkt_put_u8(ssh, 1)) != 0) /* additional info */ 1100 goto out; 1101 1102 snprintf(prompt, sizeof(prompt), 1103 "Enter %.30s@%.128s's old password: ", 1104 authctxt->server_user, host); 1105 password = read_passphrase(prompt, 0); 1106 if ((r = sshpkt_put_cstring(ssh, password)) != 0) 1107 goto out; 1108 1109 freezero(password, strlen(password)); 1110 password = NULL; 1111 while (password == NULL) { 1112 snprintf(prompt, sizeof(prompt), 1113 "Enter %.30s@%.128s's new password: ", 1114 authctxt->server_user, host); 1115 password = read_passphrase(prompt, RP_ALLOW_EOF); 1116 if (password == NULL) { 1117 /* bail out */ 1118 r = 0; 1119 goto out; 1120 } 1121 snprintf(prompt, sizeof(prompt), 1122 "Retype %.30s@%.128s's new password: ", 1123 authctxt->server_user, host); 1124 retype = read_passphrase(prompt, 0); 1125 if (strcmp(password, retype) != 0) { 1126 freezero(password, strlen(password)); 1127 logit("Mismatch; try again, EOF to quit."); 1128 password = NULL; 1129 } 1130 freezero(retype, strlen(retype)); 1131 } 1132 if ((r = sshpkt_put_cstring(ssh, password)) != 0 || 1133 (r = sshpkt_add_padding(ssh, 64)) != 0 || 1134 (r = sshpkt_send(ssh)) != 0) 1135 goto out; 1136 1137 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, 1138 &input_userauth_passwd_changereq); 1139 r = 0; 1140 out: 1141 if (password) 1142 freezero(password, strlen(password)); 1143 free(info); 1144 free(lang); 1145 return r; 1146 } 1147 1148 /* 1149 * Select an algorithm for publickey signatures. 1150 * Returns algorithm (caller must free) or NULL if no mutual algorithm found. 1151 * 1152 * Call with ssh==NULL to ignore server-sig-algs extension list and 1153 * only attempt with the key's base signature type. 1154 */ 1155 static char * 1156 key_sig_algorithm(struct ssh *ssh, const struct sshkey *key) 1157 { 1158 char *allowed, *oallowed, *cp, *tmp, *alg = NULL; 1159 const char *server_sig_algs; 1160 1161 /* 1162 * The signature algorithm will only differ from the key algorithm 1163 * for RSA keys/certs and when the server advertises support for 1164 * newer (SHA2) algorithms. 1165 */ 1166 if (ssh == NULL || ssh->kex->server_sig_algs == NULL || 1167 (key->type != KEY_RSA && key->type != KEY_RSA_CERT) || 1168 (key->type == KEY_RSA_CERT && (ssh->compat & SSH_BUG_SIGTYPE))) { 1169 /* Filter base key signature alg against our configuration */ 1170 return match_list(sshkey_ssh_name(key), 1171 options.pubkey_accepted_algos, NULL); 1172 } 1173 1174 /* 1175 * Workaround OpenSSH 7.4 bug: this version supports RSA/SHA-2 but 1176 * fails to advertise it via SSH2_MSG_EXT_INFO. 1177 */ 1178 server_sig_algs = ssh->kex->server_sig_algs; 1179 if (key->type == KEY_RSA && (ssh->compat & SSH_BUG_SIGTYPE74)) 1180 server_sig_algs = "rsa-sha2-256,rsa-sha2-512"; 1181 1182 /* 1183 * For RSA keys/certs, since these might have a different sig type: 1184 * find the first entry in PubkeyAcceptedAlgorithms of the right type 1185 * that also appears in the supported signature algorithms list from 1186 * the server. 1187 */ 1188 oallowed = allowed = xstrdup(options.pubkey_accepted_algos); 1189 while ((cp = strsep(&allowed, ",")) != NULL) { 1190 if (sshkey_type_from_name(cp) != key->type) 1191 continue; 1192 tmp = match_list(sshkey_sigalg_by_name(cp), 1193 server_sig_algs, NULL); 1194 if (tmp != NULL) 1195 alg = xstrdup(cp); 1196 free(tmp); 1197 if (alg != NULL) 1198 break; 1199 } 1200 free(oallowed); 1201 return alg; 1202 } 1203 1204 static int 1205 identity_sign(struct identity *id, u_char **sigp, size_t *lenp, 1206 const u_char *data, size_t datalen, u_int compat, const char *alg) 1207 { 1208 struct sshkey *sign_key = NULL, *prv = NULL; 1209 int is_agent = 0, retried = 0, r = SSH_ERR_INTERNAL_ERROR; 1210 struct notifier_ctx *notifier = NULL; 1211 char *fp = NULL, *pin = NULL, *prompt = NULL; 1212 1213 *sigp = NULL; 1214 *lenp = 0; 1215 1216 /* The agent supports this key. */ 1217 if (id->key != NULL && id->agent_fd != -1) { 1218 return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp, 1219 data, datalen, alg, compat); 1220 } 1221 1222 /* 1223 * We have already loaded the private key or the private key is 1224 * stored in external hardware. 1225 */ 1226 if (id->key != NULL && 1227 (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))) { 1228 sign_key = id->key; 1229 is_agent = 1; 1230 } else { 1231 /* Load the private key from the file. */ 1232 if ((prv = load_identity_file(id)) == NULL) 1233 return SSH_ERR_KEY_NOT_FOUND; 1234 if (id->key != NULL && !sshkey_equal_public(prv, id->key)) { 1235 error_f("private key %s contents do not match public", 1236 id->filename); 1237 r = SSH_ERR_KEY_NOT_FOUND; 1238 goto out; 1239 } 1240 sign_key = prv; 1241 } 1242 retry_pin: 1243 /* Prompt for touch for non-agent FIDO keys that request UP */ 1244 if (!is_agent && sshkey_is_sk(sign_key) && 1245 (sign_key->sk_flags & SSH_SK_USER_PRESENCE_REQD)) { 1246 /* XXX should batch mode just skip these? */ 1247 if ((fp = sshkey_fingerprint(sign_key, 1248 options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) 1249 fatal_f("fingerprint failed"); 1250 notifier = notify_start(options.batch_mode, 1251 "Confirm user presence for key %s %s", 1252 sshkey_type(sign_key), fp); 1253 free(fp); 1254 } 1255 if ((r = sshkey_sign(sign_key, sigp, lenp, data, datalen, 1256 alg, options.sk_provider, pin, compat)) != 0) { 1257 debug_fr(r, "sshkey_sign"); 1258 if (!retried && pin == NULL && !is_agent && 1259 sshkey_is_sk(sign_key) && 1260 r == SSH_ERR_KEY_WRONG_PASSPHRASE) { 1261 notify_complete(notifier, NULL); 1262 notifier = NULL; 1263 xasprintf(&prompt, "Enter PIN for %s key %s: ", 1264 sshkey_type(sign_key), id->filename); 1265 pin = read_passphrase(prompt, 0); 1266 retried = 1; 1267 goto retry_pin; 1268 } 1269 goto out; 1270 } 1271 1272 /* 1273 * PKCS#11 tokens may not support all signature algorithms, 1274 * so check what we get back. 1275 */ 1276 if ((r = sshkey_check_sigtype(*sigp, *lenp, alg)) != 0) { 1277 debug_fr(r, "sshkey_check_sigtype"); 1278 goto out; 1279 } 1280 /* success */ 1281 r = 0; 1282 out: 1283 free(prompt); 1284 if (pin != NULL) 1285 freezero(pin, strlen(pin)); 1286 notify_complete(notifier, r == 0 ? "User presence confirmed" : NULL); 1287 sshkey_free(prv); 1288 return r; 1289 } 1290 1291 static int 1292 id_filename_matches(Identity *id, Identity *private_id) 1293 { 1294 static const char * const suffixes[] = { ".pub", "-cert.pub", NULL }; 1295 size_t len = strlen(id->filename), plen = strlen(private_id->filename); 1296 size_t i, slen; 1297 1298 if (strcmp(id->filename, private_id->filename) == 0) 1299 return 1; 1300 for (i = 0; suffixes[i]; i++) { 1301 slen = strlen(suffixes[i]); 1302 if (len > slen && plen == len - slen && 1303 strcmp(id->filename + (len - slen), suffixes[i]) == 0 && 1304 memcmp(id->filename, private_id->filename, plen) == 0) 1305 return 1; 1306 } 1307 return 0; 1308 } 1309 1310 static int 1311 sign_and_send_pubkey(struct ssh *ssh, Identity *id) 1312 { 1313 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 1314 struct sshbuf *b = NULL; 1315 Identity *private_id, *sign_id = NULL; 1316 u_char *signature = NULL; 1317 size_t slen = 0, skip = 0; 1318 int r, fallback_sigtype, sent = 0; 1319 char *alg = NULL, *fp = NULL; 1320 const char *loc = "", *method = "publickey"; 1321 int hostbound = 0; 1322 1323 /* prefer host-bound pubkey signatures if supported by server */ 1324 if ((ssh->kex->flags & KEX_HAS_PUBKEY_HOSTBOUND) != 0 && 1325 (options.pubkey_authentication & SSH_PUBKEY_AUTH_HBOUND) != 0) { 1326 hostbound = 1; 1327 method = "publickey-hostbound-v00@openssh.com"; 1328 } 1329 1330 if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash, 1331 SSH_FP_DEFAULT)) == NULL) 1332 return 0; 1333 1334 debug3_f("using %s with %s %s", method, sshkey_type(id->key), fp); 1335 1336 /* 1337 * If the key is an certificate, try to find a matching private key 1338 * and use it to complete the signature. 1339 * If no such private key exists, fall back to trying the certificate 1340 * key itself in case it has a private half already loaded. 1341 * This will try to set sign_id to the private key that will perform 1342 * the signature. 1343 */ 1344 if (sshkey_is_cert(id->key)) { 1345 TAILQ_FOREACH(private_id, &authctxt->keys, next) { 1346 if (sshkey_equal_public(id->key, private_id->key) && 1347 id->key->type != private_id->key->type) { 1348 sign_id = private_id; 1349 break; 1350 } 1351 } 1352 /* 1353 * Exact key matches are preferred, but also allow 1354 * filename matches for non-PKCS#11/agent keys that 1355 * didn't load public keys. This supports the case 1356 * of keeping just a private key file and public 1357 * certificate on disk. 1358 */ 1359 if (sign_id == NULL && 1360 !id->isprivate && id->agent_fd == -1 && 1361 (id->key->flags & SSHKEY_FLAG_EXT) == 0) { 1362 TAILQ_FOREACH(private_id, &authctxt->keys, next) { 1363 if (private_id->key == NULL && 1364 id_filename_matches(id, private_id)) { 1365 sign_id = private_id; 1366 break; 1367 } 1368 } 1369 } 1370 if (sign_id != NULL) { 1371 debug2_f("using private key \"%s\"%s for " 1372 "certificate", sign_id->filename, 1373 sign_id->agent_fd != -1 ? " from agent" : ""); 1374 } else { 1375 debug_f("no separate private key for certificate " 1376 "\"%s\"", id->filename); 1377 } 1378 } 1379 1380 /* 1381 * If the above didn't select another identity to do the signing 1382 * then default to the one we started with. 1383 */ 1384 if (sign_id == NULL) 1385 sign_id = id; 1386 1387 /* assemble and sign data */ 1388 for (fallback_sigtype = 0; fallback_sigtype <= 1; fallback_sigtype++) { 1389 free(alg); 1390 slen = 0; 1391 signature = NULL; 1392 if ((alg = key_sig_algorithm(fallback_sigtype ? NULL : ssh, 1393 id->key)) == NULL) { 1394 error_f("no mutual signature supported"); 1395 goto out; 1396 } 1397 debug3_f("signing using %s %s", alg, fp); 1398 1399 sshbuf_free(b); 1400 if ((b = sshbuf_new()) == NULL) 1401 fatal_f("sshbuf_new failed"); 1402 if (ssh->compat & SSH_OLD_SESSIONID) { 1403 if ((r = sshbuf_putb(b, ssh->kex->session_id)) != 0) 1404 fatal_fr(r, "sshbuf_putb"); 1405 } else { 1406 if ((r = sshbuf_put_stringb(b, 1407 ssh->kex->session_id)) != 0) 1408 fatal_fr(r, "sshbuf_put_stringb"); 1409 } 1410 skip = sshbuf_len(b); 1411 if ((r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1412 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 || 1413 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 || 1414 (r = sshbuf_put_cstring(b, method)) != 0 || 1415 (r = sshbuf_put_u8(b, 1)) != 0 || 1416 (r = sshbuf_put_cstring(b, alg)) != 0 || 1417 (r = sshkey_puts(id->key, b)) != 0) { 1418 fatal_fr(r, "assemble signed data"); 1419 } 1420 if (hostbound) { 1421 if (ssh->kex->initial_hostkey == NULL) { 1422 fatal_f("internal error: initial hostkey " 1423 "not recorded"); 1424 } 1425 if ((r = sshkey_puts(ssh->kex->initial_hostkey, b)) != 0) 1426 fatal_fr(r, "assemble %s hostkey", method); 1427 } 1428 /* generate signature */ 1429 r = identity_sign(sign_id, &signature, &slen, 1430 sshbuf_ptr(b), sshbuf_len(b), ssh->compat, alg); 1431 if (r == 0) 1432 break; 1433 else if (r == SSH_ERR_KEY_NOT_FOUND) 1434 goto out; /* soft failure */ 1435 else if (r == SSH_ERR_SIGN_ALG_UNSUPPORTED && 1436 !fallback_sigtype) { 1437 if (sign_id->agent_fd != -1) 1438 loc = "agent "; 1439 else if ((sign_id->key->flags & SSHKEY_FLAG_EXT) != 0) 1440 loc = "token "; 1441 logit("%skey %s %s returned incorrect signature type", 1442 loc, sshkey_type(id->key), fp); 1443 continue; 1444 } 1445 error_fr(r, "signing failed for %s \"%s\"%s", 1446 sshkey_type(sign_id->key), sign_id->filename, 1447 id->agent_fd != -1 ? " from agent" : ""); 1448 goto out; 1449 } 1450 if (slen == 0 || signature == NULL) /* shouldn't happen */ 1451 fatal_f("no signature"); 1452 1453 /* append signature */ 1454 if ((r = sshbuf_put_string(b, signature, slen)) != 0) 1455 fatal_fr(r, "append signature"); 1456 1457 #ifdef DEBUG_PK 1458 sshbuf_dump(b, stderr); 1459 #endif 1460 /* skip session id and packet type */ 1461 if ((r = sshbuf_consume(b, skip + 1)) != 0) 1462 fatal_fr(r, "consume"); 1463 1464 /* put remaining data from buffer into packet */ 1465 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1466 (r = sshpkt_putb(ssh, b)) != 0 || 1467 (r = sshpkt_send(ssh)) != 0) 1468 fatal_fr(r, "enqueue request"); 1469 1470 /* success */ 1471 sent = 1; 1472 1473 out: 1474 free(fp); 1475 free(alg); 1476 sshbuf_free(b); 1477 freezero(signature, slen); 1478 return sent; 1479 } 1480 1481 static int 1482 send_pubkey_test(struct ssh *ssh, Identity *id) 1483 { 1484 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 1485 u_char *blob = NULL; 1486 char *alg = NULL; 1487 size_t bloblen; 1488 u_int have_sig = 0; 1489 int sent = 0, r; 1490 1491 if ((alg = key_sig_algorithm(ssh, id->key)) == NULL) { 1492 debug_f("no mutual signature algorithm"); 1493 goto out; 1494 } 1495 1496 if ((r = sshkey_to_blob(id->key, &blob, &bloblen)) != 0) { 1497 /* we cannot handle this key */ 1498 debug3_f("cannot handle key"); 1499 goto out; 1500 } 1501 /* register callback for USERAUTH_PK_OK message */ 1502 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok); 1503 1504 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1505 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 || 1506 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 || 1507 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 || 1508 (r = sshpkt_put_u8(ssh, have_sig)) != 0 || 1509 (r = sshpkt_put_cstring(ssh, alg)) != 0 || 1510 (r = sshpkt_put_string(ssh, blob, bloblen)) != 0 || 1511 (r = sshpkt_send(ssh)) != 0) 1512 fatal_fr(r, "send packet"); 1513 sent = 1; 1514 1515 out: 1516 free(alg); 1517 free(blob); 1518 return sent; 1519 } 1520 1521 static struct sshkey * 1522 load_identity_file(Identity *id) 1523 { 1524 struct sshkey *private = NULL; 1525 char prompt[300], *passphrase, *comment; 1526 int r, quit = 0, i; 1527 struct stat st; 1528 1529 if (stat(id->filename, &st) == -1) { 1530 do_log2(id->userprovided ? 1531 SYSLOG_LEVEL_INFO : SYSLOG_LEVEL_DEBUG3, 1532 "no such identity: %s: %s", id->filename, strerror(errno)); 1533 return NULL; 1534 } 1535 snprintf(prompt, sizeof prompt, 1536 "Enter passphrase for key '%.100s': ", id->filename); 1537 for (i = 0; i <= options.number_of_password_prompts; i++) { 1538 if (i == 0) 1539 passphrase = ""; 1540 else { 1541 passphrase = read_passphrase(prompt, 0); 1542 if (*passphrase == '\0') { 1543 debug2("no passphrase given, try next key"); 1544 free(passphrase); 1545 break; 1546 } 1547 } 1548 switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename, 1549 passphrase, &private, &comment))) { 1550 case 0: 1551 break; 1552 case SSH_ERR_KEY_WRONG_PASSPHRASE: 1553 if (options.batch_mode) { 1554 quit = 1; 1555 break; 1556 } 1557 if (i != 0) 1558 debug2("bad passphrase given, try again..."); 1559 break; 1560 case SSH_ERR_SYSTEM_ERROR: 1561 if (errno == ENOENT) { 1562 debug2_r(r, "Load key \"%s\"", id->filename); 1563 quit = 1; 1564 break; 1565 } 1566 /* FALLTHROUGH */ 1567 default: 1568 error_r(r, "Load key \"%s\"", id->filename); 1569 quit = 1; 1570 break; 1571 } 1572 if (private != NULL && sshkey_is_sk(private) && 1573 options.sk_provider == NULL) { 1574 debug("key \"%s\" is an authenticator-hosted key, " 1575 "but no provider specified", id->filename); 1576 sshkey_free(private); 1577 private = NULL; 1578 quit = 1; 1579 } 1580 if (!quit && (r = sshkey_check_rsa_length(private, 1581 options.required_rsa_size)) != 0) { 1582 debug_fr(r, "Skipping key %s", id->filename); 1583 sshkey_free(private); 1584 private = NULL; 1585 quit = 1; 1586 } 1587 if (!quit && private != NULL && id->agent_fd == -1 && 1588 !(id->key && id->isprivate)) 1589 maybe_add_key_to_agent(id->filename, private, comment, 1590 passphrase); 1591 if (i > 0) 1592 freezero(passphrase, strlen(passphrase)); 1593 free(comment); 1594 if (private != NULL || quit) 1595 break; 1596 } 1597 return private; 1598 } 1599 1600 static int 1601 key_type_allowed_by_config(struct sshkey *key) 1602 { 1603 if (match_pattern_list(sshkey_ssh_name(key), 1604 options.pubkey_accepted_algos, 0) == 1) 1605 return 1; 1606 1607 /* RSA keys/certs might be allowed by alternate signature types */ 1608 switch (key->type) { 1609 case KEY_RSA: 1610 if (match_pattern_list("rsa-sha2-512", 1611 options.pubkey_accepted_algos, 0) == 1) 1612 return 1; 1613 if (match_pattern_list("rsa-sha2-256", 1614 options.pubkey_accepted_algos, 0) == 1) 1615 return 1; 1616 break; 1617 case KEY_RSA_CERT: 1618 if (match_pattern_list("rsa-sha2-512-cert-v01@openssh.com", 1619 options.pubkey_accepted_algos, 0) == 1) 1620 return 1; 1621 if (match_pattern_list("rsa-sha2-256-cert-v01@openssh.com", 1622 options.pubkey_accepted_algos, 0) == 1) 1623 return 1; 1624 break; 1625 } 1626 return 0; 1627 } 1628 1629 /* obtain a list of keys from the agent */ 1630 static int 1631 get_agent_identities(struct ssh *ssh, int *agent_fdp, 1632 struct ssh_identitylist **idlistp) 1633 { 1634 int r, agent_fd; 1635 struct ssh_identitylist *idlist; 1636 1637 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) { 1638 if (r != SSH_ERR_AGENT_NOT_PRESENT) 1639 debug_fr(r, "ssh_get_authentication_socket"); 1640 return r; 1641 } 1642 if ((r = ssh_agent_bind_hostkey(agent_fd, ssh->kex->initial_hostkey, 1643 ssh->kex->session_id, ssh->kex->initial_sig, 0)) == 0) 1644 debug_f("bound agent to hostkey"); 1645 else 1646 debug2_fr(r, "ssh_agent_bind_hostkey"); 1647 1648 if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) { 1649 debug_fr(r, "ssh_fetch_identitylist"); 1650 close(agent_fd); 1651 return r; 1652 } 1653 /* success */ 1654 *agent_fdp = agent_fd; 1655 *idlistp = idlist; 1656 debug_f("agent returned %zu keys", idlist->nkeys); 1657 return 0; 1658 } 1659 1660 /* 1661 * try keys in the following order: 1662 * 1. certificates listed in the config file 1663 * 2. other input certificates 1664 * 3. agent keys that are found in the config file 1665 * 4. other agent keys 1666 * 5. keys that are only listed in the config file 1667 */ 1668 static void 1669 pubkey_prepare(struct ssh *ssh, Authctxt *authctxt) 1670 { 1671 struct identity *id, *id2, *tmp; 1672 struct idlist agent, files, *preferred; 1673 struct sshkey *key; 1674 int disallowed, agent_fd = -1, i, r, found; 1675 size_t j; 1676 struct ssh_identitylist *idlist; 1677 char *cp, *ident; 1678 1679 TAILQ_INIT(&agent); /* keys from the agent */ 1680 TAILQ_INIT(&files); /* keys from the config file */ 1681 preferred = &authctxt->keys; 1682 TAILQ_INIT(preferred); /* preferred order of keys */ 1683 1684 /* list of keys stored in the filesystem and PKCS#11 */ 1685 for (i = 0; i < options.num_identity_files; i++) { 1686 key = options.identity_keys[i]; 1687 if (key && key->cert && 1688 key->cert->type != SSH2_CERT_TYPE_USER) { 1689 debug_f("ignoring certificate %s: not a user " 1690 "certificate", options.identity_files[i]); 1691 continue; 1692 } 1693 if (key && sshkey_is_sk(key) && options.sk_provider == NULL) { 1694 debug_f("ignoring authenticator-hosted key %s as no " 1695 "SecurityKeyProvider has been specified", 1696 options.identity_files[i]); 1697 continue; 1698 } 1699 options.identity_keys[i] = NULL; 1700 id = xcalloc(1, sizeof(*id)); 1701 id->agent_fd = -1; 1702 id->key = key; 1703 id->filename = xstrdup(options.identity_files[i]); 1704 id->userprovided = options.identity_file_userprovided[i]; 1705 TAILQ_INSERT_TAIL(&files, id, next); 1706 } 1707 /* list of certificates specified by user */ 1708 for (i = 0; i < options.num_certificate_files; i++) { 1709 key = options.certificates[i]; 1710 if (!sshkey_is_cert(key) || key->cert == NULL || 1711 key->cert->type != SSH2_CERT_TYPE_USER) { 1712 debug_f("ignoring certificate %s: not a user " 1713 "certificate", options.identity_files[i]); 1714 continue; 1715 } 1716 if (key && sshkey_is_sk(key) && options.sk_provider == NULL) { 1717 debug_f("ignoring authenticator-hosted key " 1718 "certificate %s as no " 1719 "SecurityKeyProvider has been specified", 1720 options.identity_files[i]); 1721 continue; 1722 } 1723 id = xcalloc(1, sizeof(*id)); 1724 id->agent_fd = -1; 1725 id->key = key; 1726 id->filename = xstrdup(options.certificate_files[i]); 1727 id->userprovided = options.certificate_file_userprovided[i]; 1728 TAILQ_INSERT_TAIL(preferred, id, next); 1729 } 1730 /* list of keys supported by the agent */ 1731 if ((r = get_agent_identities(ssh, &agent_fd, &idlist)) == 0) { 1732 for (j = 0; j < idlist->nkeys; j++) { 1733 if ((r = sshkey_check_rsa_length(idlist->keys[j], 1734 options.required_rsa_size)) != 0) { 1735 debug_fr(r, "ignoring %s agent key", 1736 sshkey_ssh_name(idlist->keys[j])); 1737 continue; 1738 } 1739 found = 0; 1740 TAILQ_FOREACH(id, &files, next) { 1741 /* 1742 * agent keys from the config file are 1743 * preferred 1744 */ 1745 if (sshkey_equal(idlist->keys[j], id->key)) { 1746 TAILQ_REMOVE(&files, id, next); 1747 TAILQ_INSERT_TAIL(preferred, id, next); 1748 id->agent_fd = agent_fd; 1749 found = 1; 1750 break; 1751 } 1752 } 1753 if (!found && !options.identities_only) { 1754 id = xcalloc(1, sizeof(*id)); 1755 /* XXX "steals" key/comment from idlist */ 1756 id->key = idlist->keys[j]; 1757 id->filename = idlist->comments[j]; 1758 idlist->keys[j] = NULL; 1759 idlist->comments[j] = NULL; 1760 id->agent_fd = agent_fd; 1761 TAILQ_INSERT_TAIL(&agent, id, next); 1762 } 1763 } 1764 ssh_free_identitylist(idlist); 1765 /* append remaining agent keys */ 1766 TAILQ_CONCAT(preferred, &agent, next); 1767 authctxt->agent_fd = agent_fd; 1768 } 1769 /* Prefer PKCS11 keys that are explicitly listed */ 1770 TAILQ_FOREACH_SAFE(id, &files, next, tmp) { 1771 if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0) 1772 continue; 1773 found = 0; 1774 TAILQ_FOREACH(id2, &files, next) { 1775 if (id2->key == NULL || 1776 (id2->key->flags & SSHKEY_FLAG_EXT) != 0) 1777 continue; 1778 if (sshkey_equal(id->key, id2->key)) { 1779 TAILQ_REMOVE(&files, id, next); 1780 TAILQ_INSERT_TAIL(preferred, id, next); 1781 found = 1; 1782 break; 1783 } 1784 } 1785 /* If IdentitiesOnly set and key not found then don't use it */ 1786 if (!found && options.identities_only) { 1787 TAILQ_REMOVE(&files, id, next); 1788 freezero(id, sizeof(*id)); 1789 } 1790 } 1791 /* append remaining keys from the config file */ 1792 TAILQ_CONCAT(preferred, &files, next); 1793 /* finally, filter by PubkeyAcceptedAlgorithms */ 1794 TAILQ_FOREACH_SAFE(id, preferred, next, id2) { 1795 disallowed = 0; 1796 cp = NULL; 1797 if (id->key == NULL) 1798 continue; 1799 if (!key_type_allowed_by_config(id->key)) { 1800 debug("Skipping %s key %s - corresponding algorithm " 1801 "not in PubkeyAcceptedAlgorithms", 1802 sshkey_ssh_name(id->key), id->filename); 1803 disallowed = 1; 1804 } else if (ssh->kex->server_sig_algs != NULL && 1805 (cp = key_sig_algorithm(ssh, id->key)) == NULL) { 1806 debug("Skipping %s key %s - corresponding algorithm " 1807 "not supported by server", 1808 sshkey_ssh_name(id->key), id->filename); 1809 disallowed = 1; 1810 } 1811 free(cp); 1812 if (!disallowed) 1813 continue; 1814 /* remove key */ 1815 TAILQ_REMOVE(preferred, id, next); 1816 sshkey_free(id->key); 1817 free(id->filename); 1818 memset(id, 0, sizeof(*id)); 1819 } 1820 /* List the keys we plan on using */ 1821 TAILQ_FOREACH_SAFE(id, preferred, next, id2) { 1822 ident = format_identity(id); 1823 debug("Will attempt key: %s", ident); 1824 free(ident); 1825 } 1826 debug2_f("done"); 1827 } 1828 1829 static void 1830 pubkey_cleanup(struct ssh *ssh) 1831 { 1832 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 1833 Identity *id; 1834 1835 if (authctxt->agent_fd != -1) { 1836 ssh_close_authentication_socket(authctxt->agent_fd); 1837 authctxt->agent_fd = -1; 1838 } 1839 for (id = TAILQ_FIRST(&authctxt->keys); id; 1840 id = TAILQ_FIRST(&authctxt->keys)) { 1841 TAILQ_REMOVE(&authctxt->keys, id, next); 1842 sshkey_free(id->key); 1843 free(id->filename); 1844 free(id); 1845 } 1846 } 1847 1848 static void 1849 pubkey_reset(Authctxt *authctxt) 1850 { 1851 Identity *id; 1852 1853 TAILQ_FOREACH(id, &authctxt->keys, next) 1854 id->tried = 0; 1855 } 1856 1857 static int 1858 userauth_pubkey(struct ssh *ssh) 1859 { 1860 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 1861 Identity *id; 1862 int sent = 0; 1863 char *ident; 1864 static int prepared; 1865 1866 if (!prepared) { 1867 pubkey_prepare(ssh, authctxt); 1868 prepared = 1; 1869 } 1870 1871 while ((id = TAILQ_FIRST(&authctxt->keys))) { 1872 if (id->tried++) 1873 return (0); 1874 /* move key to the end of the queue */ 1875 TAILQ_REMOVE(&authctxt->keys, id, next); 1876 TAILQ_INSERT_TAIL(&authctxt->keys, id, next); 1877 /* 1878 * send a test message if we have the public key. for 1879 * encrypted keys we cannot do this and have to load the 1880 * private key instead 1881 */ 1882 if (id->key != NULL) { 1883 ident = format_identity(id); 1884 debug("Offering public key: %s", ident); 1885 free(ident); 1886 sent = send_pubkey_test(ssh, id); 1887 } else { 1888 debug("Trying private key: %s", id->filename); 1889 id->key = load_identity_file(id); 1890 if (id->key != NULL) { 1891 if (id->key != NULL) { 1892 id->isprivate = 1; 1893 sent = sign_and_send_pubkey(ssh, id); 1894 } 1895 sshkey_free(id->key); 1896 id->key = NULL; 1897 id->isprivate = 0; 1898 } 1899 } 1900 if (sent) 1901 return (sent); 1902 } 1903 return (0); 1904 } 1905 1906 /* 1907 * Send userauth request message specifying keyboard-interactive method. 1908 */ 1909 static int 1910 userauth_kbdint(struct ssh *ssh) 1911 { 1912 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 1913 int r; 1914 1915 if (authctxt->attempt_kbdint++ >= options.number_of_password_prompts) 1916 return 0; 1917 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */ 1918 if (authctxt->attempt_kbdint > 1 && !authctxt->info_req_seen) { 1919 debug3("userauth_kbdint: disable: no info_req_seen"); 1920 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, NULL); 1921 return 0; 1922 } 1923 1924 debug2("userauth_kbdint"); 1925 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1926 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 || 1927 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 || 1928 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 || 1929 (r = sshpkt_put_cstring(ssh, "")) != 0 || /* lang */ 1930 (r = sshpkt_put_cstring(ssh, options.kbd_interactive_devices ? 1931 options.kbd_interactive_devices : "")) != 0 || 1932 (r = sshpkt_send(ssh)) != 0) 1933 fatal_fr(r, "send packet"); 1934 1935 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req); 1936 return 1; 1937 } 1938 1939 /* 1940 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE 1941 */ 1942 static int 1943 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh) 1944 { 1945 Authctxt *authctxt = ssh->authctxt; 1946 char *name = NULL, *inst = NULL, *lang = NULL, *prompt = NULL; 1947 char *display_prompt = NULL, *response = NULL; 1948 u_char echo = 0; 1949 u_int num_prompts, i; 1950 int r; 1951 1952 debug2_f("entering"); 1953 1954 if (authctxt == NULL) 1955 fatal_f("no authentication context"); 1956 1957 authctxt->info_req_seen = 1; 1958 1959 if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0 || 1960 (r = sshpkt_get_cstring(ssh, &inst, NULL)) != 0 || 1961 (r = sshpkt_get_cstring(ssh, &lang, NULL)) != 0) 1962 goto out; 1963 if (strlen(name) > 0) 1964 logit("%s", name); 1965 if (strlen(inst) > 0) 1966 logit("%s", inst); 1967 1968 if ((r = sshpkt_get_u32(ssh, &num_prompts)) != 0) 1969 goto out; 1970 /* 1971 * Begin to build info response packet based on prompts requested. 1972 * We commit to providing the correct number of responses, so if 1973 * further on we run into a problem that prevents this, we have to 1974 * be sure and clean this up and send a correct error response. 1975 */ 1976 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_INFO_RESPONSE)) != 0 || 1977 (r = sshpkt_put_u32(ssh, num_prompts)) != 0) 1978 goto out; 1979 1980 debug2_f("num_prompts %d", num_prompts); 1981 for (i = 0; i < num_prompts; i++) { 1982 if ((r = sshpkt_get_cstring(ssh, &prompt, NULL)) != 0 || 1983 (r = sshpkt_get_u8(ssh, &echo)) != 0) 1984 goto out; 1985 if (asmprintf(&display_prompt, INT_MAX, NULL, "(%s@%s) %s", 1986 authctxt->server_user, options.host_key_alias ? 1987 options.host_key_alias : authctxt->host, prompt) == -1) 1988 fatal_f("asmprintf failed"); 1989 response = read_passphrase(display_prompt, echo ? RP_ECHO : 0); 1990 if ((r = sshpkt_put_cstring(ssh, response)) != 0) 1991 goto out; 1992 freezero(response, strlen(response)); 1993 free(prompt); 1994 free(display_prompt); 1995 display_prompt = response = prompt = NULL; 1996 } 1997 /* done with parsing incoming message. */ 1998 if ((r = sshpkt_get_end(ssh)) != 0 || 1999 (r = sshpkt_add_padding(ssh, 64)) != 0) 2000 goto out; 2001 r = sshpkt_send(ssh); 2002 out: 2003 if (response) 2004 freezero(response, strlen(response)); 2005 free(prompt); 2006 free(display_prompt); 2007 free(name); 2008 free(inst); 2009 free(lang); 2010 return r; 2011 } 2012 2013 static int 2014 ssh_keysign(struct ssh *ssh, struct sshkey *key, u_char **sigp, size_t *lenp, 2015 const u_char *data, size_t datalen) 2016 { 2017 struct sshbuf *b; 2018 struct stat st; 2019 pid_t pid; 2020 int r, to[2], from[2], status; 2021 int sock = ssh_packet_get_connection_in(ssh); 2022 u_char rversion = 0, version = 2; 2023 void (*osigchld)(int); 2024 2025 *sigp = NULL; 2026 *lenp = 0; 2027 2028 if (stat(_PATH_SSH_KEY_SIGN, &st) == -1) { 2029 error_f("not installed: %s", strerror(errno)); 2030 return -1; 2031 } 2032 if (fflush(stdout) != 0) { 2033 error_f("fflush: %s", strerror(errno)); 2034 return -1; 2035 } 2036 if (pipe(to) == -1) { 2037 error_f("pipe: %s", strerror(errno)); 2038 return -1; 2039 } 2040 if (pipe(from) == -1) { 2041 error_f("pipe: %s", strerror(errno)); 2042 return -1; 2043 } 2044 if ((pid = fork()) == -1) { 2045 error_f("fork: %s", strerror(errno)); 2046 return -1; 2047 } 2048 osigchld = ssh_signal(SIGCHLD, SIG_DFL); 2049 if (pid == 0) { 2050 close(from[0]); 2051 if (dup2(from[1], STDOUT_FILENO) == -1) 2052 fatal_f("dup2: %s", strerror(errno)); 2053 close(to[1]); 2054 if (dup2(to[0], STDIN_FILENO) == -1) 2055 fatal_f("dup2: %s", strerror(errno)); 2056 close(from[1]); 2057 close(to[0]); 2058 2059 if (dup2(sock, STDERR_FILENO + 1) == -1) 2060 fatal_f("dup2: %s", strerror(errno)); 2061 sock = STDERR_FILENO + 1; 2062 if (fcntl(sock, F_SETFD, 0) == -1) /* keep the socket on exec */ 2063 debug3_f("fcntl F_SETFD: %s", strerror(errno)); 2064 closefrom(sock + 1); 2065 2066 debug3_f("[child] pid=%ld, exec %s", 2067 (long)getpid(), _PATH_SSH_KEY_SIGN); 2068 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL); 2069 fatal_f("exec(%s): %s", _PATH_SSH_KEY_SIGN, 2070 strerror(errno)); 2071 } 2072 close(from[1]); 2073 close(to[0]); 2074 sock = STDERR_FILENO + 1; 2075 2076 if ((b = sshbuf_new()) == NULL) 2077 fatal_f("sshbuf_new failed"); 2078 /* send # of sock, data to be signed */ 2079 if ((r = sshbuf_put_u32(b, sock)) != 0 || 2080 (r = sshbuf_put_string(b, data, datalen)) != 0) 2081 fatal_fr(r, "buffer error"); 2082 if (ssh_msg_send(to[1], version, b) == -1) 2083 fatal_f("couldn't send request"); 2084 sshbuf_reset(b); 2085 r = ssh_msg_recv(from[0], b); 2086 close(from[0]); 2087 close(to[1]); 2088 if (r < 0) { 2089 error_f("no reply"); 2090 goto fail; 2091 } 2092 2093 errno = 0; 2094 while (waitpid(pid, &status, 0) == -1) { 2095 if (errno != EINTR) { 2096 error_f("waitpid %ld: %s", (long)pid, strerror(errno)); 2097 goto fail; 2098 } 2099 } 2100 if (!WIFEXITED(status)) { 2101 error_f("exited abnormally"); 2102 goto fail; 2103 } 2104 if (WEXITSTATUS(status) != 0) { 2105 error_f("exited with status %d", WEXITSTATUS(status)); 2106 goto fail; 2107 } 2108 if ((r = sshbuf_get_u8(b, &rversion)) != 0) { 2109 error_fr(r, "buffer error"); 2110 goto fail; 2111 } 2112 if (rversion != version) { 2113 error_f("bad version"); 2114 goto fail; 2115 } 2116 if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) { 2117 error_fr(r, "buffer error"); 2118 fail: 2119 ssh_signal(SIGCHLD, osigchld); 2120 sshbuf_free(b); 2121 return -1; 2122 } 2123 ssh_signal(SIGCHLD, osigchld); 2124 sshbuf_free(b); 2125 2126 return 0; 2127 } 2128 2129 static int 2130 userauth_hostbased(struct ssh *ssh) 2131 { 2132 Authctxt *authctxt = (Authctxt *)ssh->authctxt; 2133 struct sshkey *private = NULL; 2134 struct sshbuf *b = NULL; 2135 u_char *sig = NULL, *keyblob = NULL; 2136 char *fp = NULL, *chost = NULL, *lname = NULL; 2137 size_t siglen = 0, keylen = 0; 2138 int i, r, success = 0; 2139 2140 if (authctxt->ktypes == NULL) { 2141 authctxt->oktypes = xstrdup(options.hostbased_accepted_algos); 2142 authctxt->ktypes = authctxt->oktypes; 2143 } 2144 2145 /* 2146 * Work through each listed type pattern in HostbasedAcceptedAlgorithms, 2147 * trying each hostkey that matches the type in turn. 2148 */ 2149 for (;;) { 2150 if (authctxt->active_ktype == NULL) 2151 authctxt->active_ktype = strsep(&authctxt->ktypes, ","); 2152 if (authctxt->active_ktype == NULL || 2153 *authctxt->active_ktype == '\0') 2154 break; 2155 debug3_f("trying key type %s", authctxt->active_ktype); 2156 2157 /* check for a useful key */ 2158 private = NULL; 2159 for (i = 0; i < authctxt->sensitive->nkeys; i++) { 2160 if (authctxt->sensitive->keys[i] == NULL || 2161 authctxt->sensitive->keys[i]->type == KEY_UNSPEC) 2162 continue; 2163 if (!sshkey_match_keyname_to_sigalgs( 2164 sshkey_ssh_name(authctxt->sensitive->keys[i]), 2165 authctxt->active_ktype)) 2166 continue; 2167 /* we take and free the key */ 2168 private = authctxt->sensitive->keys[i]; 2169 authctxt->sensitive->keys[i] = NULL; 2170 break; 2171 } 2172 /* Found one */ 2173 if (private != NULL) 2174 break; 2175 /* No more keys of this type; advance */ 2176 authctxt->active_ktype = NULL; 2177 } 2178 if (private == NULL) { 2179 free(authctxt->oktypes); 2180 authctxt->oktypes = authctxt->ktypes = NULL; 2181 authctxt->active_ktype = NULL; 2182 debug("No more client hostkeys for hostbased authentication."); 2183 goto out; 2184 } 2185 2186 if ((fp = sshkey_fingerprint(private, options.fingerprint_hash, 2187 SSH_FP_DEFAULT)) == NULL) { 2188 error_f("sshkey_fingerprint failed"); 2189 goto out; 2190 } 2191 debug_f("trying hostkey %s %s using sigalg %s", 2192 sshkey_ssh_name(private), fp, authctxt->active_ktype); 2193 2194 /* figure out a name for the client host */ 2195 lname = get_local_name(ssh_packet_get_connection_in(ssh)); 2196 if (lname == NULL) { 2197 error_f("cannot get local ipaddr/name"); 2198 goto out; 2199 } 2200 2201 /* XXX sshbuf_put_stringf? */ 2202 xasprintf(&chost, "%s.", lname); 2203 debug2_f("chost %s", chost); 2204 2205 /* construct data */ 2206 if ((b = sshbuf_new()) == NULL) { 2207 error_f("sshbuf_new failed"); 2208 goto out; 2209 } 2210 if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) { 2211 error_fr(r, "sshkey_to_blob"); 2212 goto out; 2213 } 2214 if ((r = sshbuf_put_stringb(b, ssh->kex->session_id)) != 0 || 2215 (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 2216 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 || 2217 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 || 2218 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 || 2219 (r = sshbuf_put_cstring(b, authctxt->active_ktype)) != 0 || 2220 (r = sshbuf_put_string(b, keyblob, keylen)) != 0 || 2221 (r = sshbuf_put_cstring(b, chost)) != 0 || 2222 (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) { 2223 error_fr(r, "buffer error"); 2224 goto out; 2225 } 2226 2227 #ifdef DEBUG_PK 2228 sshbuf_dump(b, stderr); 2229 #endif 2230 if ((r = ssh_keysign(ssh, private, &sig, &siglen, 2231 sshbuf_ptr(b), sshbuf_len(b))) != 0) { 2232 error("sign using hostkey %s %s failed", 2233 sshkey_ssh_name(private), fp); 2234 goto out; 2235 } 2236 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 2237 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 || 2238 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 || 2239 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 || 2240 (r = sshpkt_put_cstring(ssh, authctxt->active_ktype)) != 0 || 2241 (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 || 2242 (r = sshpkt_put_cstring(ssh, chost)) != 0 || 2243 (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 || 2244 (r = sshpkt_put_string(ssh, sig, siglen)) != 0 || 2245 (r = sshpkt_send(ssh)) != 0) { 2246 error_fr(r, "packet error"); 2247 goto out; 2248 } 2249 success = 1; 2250 2251 out: 2252 if (sig != NULL) 2253 freezero(sig, siglen); 2254 free(keyblob); 2255 free(lname); 2256 free(fp); 2257 free(chost); 2258 sshkey_free(private); 2259 sshbuf_free(b); 2260 2261 return success; 2262 } 2263 2264 /* find auth method */ 2265 2266 /* 2267 * given auth method name, if configurable options permit this method fill 2268 * in auth_ident field and return true, otherwise return false. 2269 */ 2270 static int 2271 authmethod_is_enabled(Authmethod *method) 2272 { 2273 if (method == NULL) 2274 return 0; 2275 /* return false if options indicate this method is disabled */ 2276 if (method->enabled == NULL || *method->enabled == 0) 2277 return 0; 2278 /* return false if batch mode is enabled but method needs interactive mode */ 2279 if (method->batch_flag != NULL && *method->batch_flag != 0) 2280 return 0; 2281 return 1; 2282 } 2283 2284 static Authmethod * 2285 authmethod_lookup(const char *name) 2286 { 2287 Authmethod *method = NULL; 2288 if (name != NULL) 2289 for (method = authmethods; method->name != NULL; method++) 2290 if (strcmp(name, method->name) == 0) 2291 return method; 2292 debug2("Unrecognized authentication method name: %s", name ? name : "NULL"); 2293 return NULL; 2294 } 2295 2296 /* XXX internal state */ 2297 static Authmethod *current = NULL; 2298 static char *supported = NULL; 2299 static char *preferred = NULL; 2300 2301 /* 2302 * Given the authentication method list sent by the server, return the 2303 * next method we should try. If the server initially sends a nil list, 2304 * use a built-in default list. 2305 */ 2306 static Authmethod * 2307 authmethod_get(char *authlist) 2308 { 2309 char *name = NULL; 2310 u_int next; 2311 2312 /* Use a suitable default if we're passed a nil list. */ 2313 if (authlist == NULL || strlen(authlist) == 0) 2314 authlist = options.preferred_authentications; 2315 2316 if (supported == NULL || strcmp(authlist, supported) != 0) { 2317 debug3("start over, passed a different list %s", authlist); 2318 free(supported); 2319 supported = xstrdup(authlist); 2320 preferred = options.preferred_authentications; 2321 debug3("preferred %s", preferred); 2322 current = NULL; 2323 } else if (current != NULL && authmethod_is_enabled(current)) 2324 return current; 2325 2326 for (;;) { 2327 if ((name = match_list(preferred, supported, &next)) == NULL) { 2328 debug("No more authentication methods to try."); 2329 current = NULL; 2330 return NULL; 2331 } 2332 preferred += next; 2333 debug3("authmethod_lookup %s", name); 2334 debug3("remaining preferred: %s", preferred); 2335 if ((current = authmethod_lookup(name)) != NULL && 2336 authmethod_is_enabled(current)) { 2337 debug3("authmethod_is_enabled %s", name); 2338 debug("Next authentication method: %s", name); 2339 free(name); 2340 return current; 2341 } 2342 free(name); 2343 } 2344 } 2345 2346 static char * 2347 authmethods_get(void) 2348 { 2349 Authmethod *method = NULL; 2350 struct sshbuf *b; 2351 char *list; 2352 int r; 2353 2354 if ((b = sshbuf_new()) == NULL) 2355 fatal_f("sshbuf_new failed"); 2356 for (method = authmethods; method->name != NULL; method++) { 2357 if (authmethod_is_enabled(method)) { 2358 if ((r = sshbuf_putf(b, "%s%s", 2359 sshbuf_len(b) ? "," : "", method->name)) != 0) 2360 fatal_fr(r, "buffer error"); 2361 } 2362 } 2363 if ((list = sshbuf_dup_string(b)) == NULL) 2364 fatal_f("sshbuf_dup_string failed"); 2365 sshbuf_free(b); 2366 return list; 2367 } 2368