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