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