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