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