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