1 /* $OpenBSD: sshconnect2.c,v 1.251 2016/12/04 23:54:02 djm Exp $ */ 2 /* 3 * Copyright (c) 2000 Markus Friedl. All rights reserved. 4 * Copyright (c) 2008 Damien Miller. All rights reserved. 5 * 6 * Redistribution and use in source and binary forms, with or without 7 * modification, are permitted provided that the following conditions 8 * are met: 9 * 1. Redistributions of source code must retain the above copyright 10 * notice, this list of conditions and the following disclaimer. 11 * 2. Redistributions in binary form must reproduce the above copyright 12 * notice, this list of conditions and the following disclaimer in the 13 * documentation and/or other materials provided with the distribution. 14 * 15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 25 */ 26 27 #include <sys/types.h> 28 #include <sys/socket.h> 29 #include <sys/wait.h> 30 #include <sys/queue.h> 31 #include <sys/stat.h> 32 33 #include <errno.h> 34 #include <fcntl.h> 35 #include <netdb.h> 36 #include <stdio.h> 37 #include <string.h> 38 #include <signal.h> 39 #include <pwd.h> 40 #include <unistd.h> 41 #include <vis.h> 42 43 #include "xmalloc.h" 44 #include "ssh.h" 45 #include "ssh2.h" 46 #include "buffer.h" 47 #include "packet.h" 48 #include "compat.h" 49 #include "cipher.h" 50 #include "key.h" 51 #include "kex.h" 52 #include "myproposal.h" 53 #include "sshconnect.h" 54 #include "authfile.h" 55 #include "dh.h" 56 #include "authfd.h" 57 #include "log.h" 58 #include "misc.h" 59 #include "readconf.h" 60 #include "match.h" 61 #include "dispatch.h" 62 #include "canohost.h" 63 #include "msg.h" 64 #include "pathnames.h" 65 #include "uidswap.h" 66 #include "hostfile.h" 67 #include "ssherr.h" 68 #include "utf8.h" 69 70 #ifdef GSSAPI 71 #include "ssh-gss.h" 72 #endif 73 74 /* import */ 75 extern char *client_version_string; 76 extern char *server_version_string; 77 extern Options options; 78 79 /* 80 * SSH2 key exchange 81 */ 82 83 u_char *session_id2 = NULL; 84 u_int session_id2_len = 0; 85 86 char *xxx_host; 87 struct sockaddr *xxx_hostaddr; 88 89 static int 90 verify_host_key_callback(Key *hostkey, struct ssh *ssh) 91 { 92 if (verify_host_key(xxx_host, xxx_hostaddr, hostkey) == -1) 93 fatal("Host key verification failed."); 94 return 0; 95 } 96 97 static char * 98 order_hostkeyalgs(char *host, struct sockaddr *hostaddr, u_short port) 99 { 100 char *oavail, *avail, *first, *last, *alg, *hostname, *ret; 101 size_t maxlen; 102 struct hostkeys *hostkeys; 103 int ktype; 104 u_int i; 105 106 /* Find all hostkeys for this hostname */ 107 get_hostfile_hostname_ipaddr(host, hostaddr, port, &hostname, NULL); 108 hostkeys = init_hostkeys(); 109 for (i = 0; i < options.num_user_hostfiles; i++) 110 load_hostkeys(hostkeys, hostname, options.user_hostfiles[i]); 111 for (i = 0; i < options.num_system_hostfiles; i++) 112 load_hostkeys(hostkeys, hostname, options.system_hostfiles[i]); 113 114 oavail = avail = xstrdup(KEX_DEFAULT_PK_ALG); 115 maxlen = strlen(avail) + 1; 116 first = xmalloc(maxlen); 117 last = xmalloc(maxlen); 118 *first = *last = '\0'; 119 120 #define ALG_APPEND(to, from) \ 121 do { \ 122 if (*to != '\0') \ 123 strlcat(to, ",", maxlen); \ 124 strlcat(to, from, maxlen); \ 125 } while (0) 126 127 while ((alg = strsep(&avail, ",")) && *alg != '\0') { 128 if ((ktype = sshkey_type_from_name(alg)) == KEY_UNSPEC) 129 fatal("%s: unknown alg %s", __func__, alg); 130 if (lookup_key_in_hostkeys_by_type(hostkeys, 131 sshkey_type_plain(ktype), NULL)) 132 ALG_APPEND(first, alg); 133 else 134 ALG_APPEND(last, alg); 135 } 136 #undef ALG_APPEND 137 xasprintf(&ret, "%s%s%s", first, 138 (*first == '\0' || *last == '\0') ? "" : ",", last); 139 if (*first != '\0') 140 debug3("%s: prefer hostkeyalgs: %s", __func__, first); 141 142 free(first); 143 free(last); 144 free(hostname); 145 free(oavail); 146 free_hostkeys(hostkeys); 147 148 return ret; 149 } 150 151 void 152 ssh_kex2(char *host, struct sockaddr *hostaddr, u_short port) 153 { 154 char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT }; 155 char *s; 156 struct kex *kex; 157 int r; 158 159 xxx_host = host; 160 xxx_hostaddr = hostaddr; 161 162 if ((s = kex_names_cat(options.kex_algorithms, "ext-info-c")) == NULL) 163 fatal("%s: kex_names_cat", __func__); 164 myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(s); 165 myproposal[PROPOSAL_ENC_ALGS_CTOS] = 166 compat_cipher_proposal(options.ciphers); 167 myproposal[PROPOSAL_ENC_ALGS_STOC] = 168 compat_cipher_proposal(options.ciphers); 169 myproposal[PROPOSAL_COMP_ALGS_CTOS] = 170 myproposal[PROPOSAL_COMP_ALGS_STOC] = options.compression ? 171 "zlib@openssh.com,zlib,none" : "none,zlib@openssh.com,zlib"; 172 myproposal[PROPOSAL_MAC_ALGS_CTOS] = 173 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs; 174 if (options.hostkeyalgorithms != NULL) { 175 if (kex_assemble_names(KEX_DEFAULT_PK_ALG, 176 &options.hostkeyalgorithms) != 0) 177 fatal("%s: kex_assemble_namelist", __func__); 178 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = 179 compat_pkalg_proposal(options.hostkeyalgorithms); 180 } else { 181 /* Enforce default */ 182 options.hostkeyalgorithms = xstrdup(KEX_DEFAULT_PK_ALG); 183 /* Prefer algorithms that we already have keys for */ 184 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = 185 compat_pkalg_proposal( 186 order_hostkeyalgs(host, hostaddr, port)); 187 } 188 189 if (options.rekey_limit || options.rekey_interval) 190 packet_set_rekey_limits((u_int32_t)options.rekey_limit, 191 (time_t)options.rekey_interval); 192 193 /* start key exchange */ 194 if ((r = kex_setup(active_state, myproposal)) != 0) 195 fatal("kex_setup: %s", ssh_err(r)); 196 kex = active_state->kex; 197 #ifdef WITH_OPENSSL 198 kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client; 199 kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client; 200 kex->kex[KEX_DH_GRP14_SHA256] = kexdh_client; 201 kex->kex[KEX_DH_GRP16_SHA512] = kexdh_client; 202 kex->kex[KEX_DH_GRP18_SHA512] = kexdh_client; 203 kex->kex[KEX_DH_GEX_SHA1] = kexgex_client; 204 kex->kex[KEX_DH_GEX_SHA256] = kexgex_client; 205 kex->kex[KEX_ECDH_SHA2] = kexecdh_client; 206 #endif 207 kex->kex[KEX_C25519_SHA256] = kexc25519_client; 208 kex->client_version_string=client_version_string; 209 kex->server_version_string=server_version_string; 210 kex->verify_host_key=&verify_host_key_callback; 211 212 dispatch_run(DISPATCH_BLOCK, &kex->done, active_state); 213 214 /* remove ext-info from the KEX proposals for rekeying */ 215 myproposal[PROPOSAL_KEX_ALGS] = 216 compat_kex_proposal(options.kex_algorithms); 217 if ((r = kex_prop2buf(kex->my, myproposal)) != 0) 218 fatal("kex_prop2buf: %s", ssh_err(r)); 219 220 session_id2 = kex->session_id; 221 session_id2_len = kex->session_id_len; 222 223 #ifdef DEBUG_KEXDH 224 /* send 1st encrypted/maced/compressed message */ 225 packet_start(SSH2_MSG_IGNORE); 226 packet_put_cstring("markus"); 227 packet_send(); 228 packet_write_wait(); 229 #endif 230 } 231 232 /* 233 * Authenticate user 234 */ 235 236 typedef struct cauthctxt Authctxt; 237 typedef struct cauthmethod Authmethod; 238 typedef struct identity Identity; 239 typedef struct idlist Idlist; 240 241 struct identity { 242 TAILQ_ENTRY(identity) next; 243 int agent_fd; /* >=0 if agent supports key */ 244 struct sshkey *key; /* public/private key */ 245 char *filename; /* comment for agent-only keys */ 246 int tried; 247 int isprivate; /* key points to the private key */ 248 int userprovided; 249 }; 250 TAILQ_HEAD(idlist, identity); 251 252 struct cauthctxt { 253 const char *server_user; 254 const char *local_user; 255 const char *host; 256 const char *service; 257 struct cauthmethod *method; 258 sig_atomic_t success; 259 char *authlist; 260 int attempt; 261 /* pubkey */ 262 struct idlist keys; 263 int agent_fd; 264 /* hostbased */ 265 Sensitive *sensitive; 266 char *oktypes, *ktypes; 267 const char *active_ktype; 268 /* kbd-interactive */ 269 int info_req_seen; 270 /* generic */ 271 void *methoddata; 272 }; 273 274 struct cauthmethod { 275 char *name; /* string to compare against server's list */ 276 int (*userauth)(Authctxt *authctxt); 277 void (*cleanup)(Authctxt *authctxt); 278 int *enabled; /* flag in option struct that enables method */ 279 int *batch_flag; /* flag in option struct that disables method */ 280 }; 281 282 int input_userauth_service_accept(int, u_int32_t, void *); 283 int input_userauth_ext_info(int, u_int32_t, void *); 284 int input_userauth_success(int, u_int32_t, void *); 285 int input_userauth_success_unexpected(int, u_int32_t, void *); 286 int input_userauth_failure(int, u_int32_t, void *); 287 int input_userauth_banner(int, u_int32_t, void *); 288 int input_userauth_error(int, u_int32_t, void *); 289 int input_userauth_info_req(int, u_int32_t, void *); 290 int input_userauth_pk_ok(int, u_int32_t, void *); 291 int input_userauth_passwd_changereq(int, u_int32_t, void *); 292 293 int userauth_none(Authctxt *); 294 int userauth_pubkey(Authctxt *); 295 int userauth_passwd(Authctxt *); 296 int userauth_kbdint(Authctxt *); 297 int userauth_hostbased(Authctxt *); 298 299 #ifdef GSSAPI 300 int userauth_gssapi(Authctxt *authctxt); 301 int input_gssapi_response(int type, u_int32_t, void *); 302 int input_gssapi_token(int type, u_int32_t, void *); 303 int input_gssapi_hash(int type, u_int32_t, void *); 304 int input_gssapi_error(int, u_int32_t, void *); 305 int input_gssapi_errtok(int, u_int32_t, void *); 306 #endif 307 308 void userauth(Authctxt *, char *); 309 310 static int sign_and_send_pubkey(Authctxt *, Identity *); 311 static void pubkey_prepare(Authctxt *); 312 static void pubkey_cleanup(Authctxt *); 313 static void pubkey_reset(Authctxt *); 314 static Key *load_identity_file(Identity *); 315 316 static Authmethod *authmethod_get(char *authlist); 317 static Authmethod *authmethod_lookup(const char *name); 318 static char *authmethods_get(void); 319 320 Authmethod authmethods[] = { 321 #ifdef GSSAPI 322 {"gssapi-with-mic", 323 userauth_gssapi, 324 NULL, 325 &options.gss_authentication, 326 NULL}, 327 #endif 328 {"hostbased", 329 userauth_hostbased, 330 NULL, 331 &options.hostbased_authentication, 332 NULL}, 333 {"publickey", 334 userauth_pubkey, 335 NULL, 336 &options.pubkey_authentication, 337 NULL}, 338 {"keyboard-interactive", 339 userauth_kbdint, 340 NULL, 341 &options.kbd_interactive_authentication, 342 &options.batch_mode}, 343 {"password", 344 userauth_passwd, 345 NULL, 346 &options.password_authentication, 347 &options.batch_mode}, 348 {"none", 349 userauth_none, 350 NULL, 351 NULL, 352 NULL}, 353 {NULL, NULL, NULL, NULL, NULL} 354 }; 355 356 void 357 ssh_userauth2(const char *local_user, const char *server_user, char *host, 358 Sensitive *sensitive) 359 { 360 struct ssh *ssh = active_state; 361 Authctxt authctxt; 362 int r; 363 364 if (options.challenge_response_authentication) 365 options.kbd_interactive_authentication = 1; 366 if (options.preferred_authentications == NULL) 367 options.preferred_authentications = authmethods_get(); 368 369 /* setup authentication context */ 370 memset(&authctxt, 0, sizeof(authctxt)); 371 pubkey_prepare(&authctxt); 372 authctxt.server_user = server_user; 373 authctxt.local_user = local_user; 374 authctxt.host = host; 375 authctxt.service = "ssh-connection"; /* service name */ 376 authctxt.success = 0; 377 authctxt.method = authmethod_lookup("none"); 378 authctxt.authlist = NULL; 379 authctxt.methoddata = NULL; 380 authctxt.sensitive = sensitive; 381 authctxt.active_ktype = authctxt.oktypes = authctxt.ktypes = NULL; 382 authctxt.info_req_seen = 0; 383 authctxt.agent_fd = -1; 384 if (authctxt.method == NULL) 385 fatal("ssh_userauth2: internal error: cannot send userauth none request"); 386 387 if ((r = sshpkt_start(ssh, SSH2_MSG_SERVICE_REQUEST)) != 0 || 388 (r = sshpkt_put_cstring(ssh, "ssh-userauth")) != 0 || 389 (r = sshpkt_send(ssh)) != 0) 390 fatal("%s: %s", __func__, ssh_err(r)); 391 392 ssh_dispatch_init(ssh, &input_userauth_error); 393 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_ext_info); 394 ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept); 395 ssh_dispatch_run(ssh, DISPATCH_BLOCK, &authctxt.success, &authctxt); /* loop until success */ 396 397 pubkey_cleanup(&authctxt); 398 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL); 399 400 if (!authctxt.success) 401 fatal("Authentication failed."); 402 debug("Authentication succeeded (%s).", authctxt.method->name); 403 } 404 405 /* ARGSUSED */ 406 int 407 input_userauth_service_accept(int type, u_int32_t seqnr, void *ctxt) 408 { 409 Authctxt *authctxt = ctxt; 410 struct ssh *ssh = active_state; 411 int r; 412 413 if (ssh_packet_remaining(ssh) > 0) { 414 char *reply; 415 416 if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0) 417 goto out; 418 debug2("service_accept: %s", reply); 419 free(reply); 420 } else { 421 debug2("buggy server: service_accept w/o service"); 422 } 423 if ((r = sshpkt_get_end(ssh)) != 0) 424 goto out; 425 debug("SSH2_MSG_SERVICE_ACCEPT received"); 426 427 /* initial userauth request */ 428 userauth_none(authctxt); 429 430 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error); 431 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success); 432 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure); 433 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner); 434 r = 0; 435 out: 436 return r; 437 } 438 439 /* ARGSUSED */ 440 int 441 input_userauth_ext_info(int type, u_int32_t seqnr, void *ctxt) 442 { 443 return kex_input_ext_info(type, seqnr, active_state); 444 } 445 446 void 447 userauth(Authctxt *authctxt, char *authlist) 448 { 449 if (authctxt->method != NULL && authctxt->method->cleanup != NULL) 450 authctxt->method->cleanup(authctxt); 451 452 free(authctxt->methoddata); 453 authctxt->methoddata = NULL; 454 if (authlist == NULL) { 455 authlist = authctxt->authlist; 456 } else { 457 free(authctxt->authlist); 458 authctxt->authlist = authlist; 459 } 460 for (;;) { 461 Authmethod *method = authmethod_get(authlist); 462 if (method == NULL) 463 fatal("Permission denied (%s).", authlist); 464 authctxt->method = method; 465 466 /* reset the per method handler */ 467 dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN, 468 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL); 469 470 /* and try new method */ 471 if (method->userauth(authctxt) != 0) { 472 debug2("we sent a %s packet, wait for reply", method->name); 473 break; 474 } else { 475 debug2("we did not send a packet, disable method"); 476 method->enabled = NULL; 477 } 478 } 479 } 480 481 /* ARGSUSED */ 482 int 483 input_userauth_error(int type, u_int32_t seq, void *ctxt) 484 { 485 fatal("input_userauth_error: bad message during authentication: " 486 "type %d", type); 487 return 0; 488 } 489 490 /* ARGSUSED */ 491 int 492 input_userauth_banner(int type, u_int32_t seq, void *ctxt) 493 { 494 char *msg, *lang; 495 u_int len; 496 497 debug3("%s", __func__); 498 msg = packet_get_string(&len); 499 lang = packet_get_string(NULL); 500 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO) 501 fmprintf(stderr, "%s", msg); 502 free(msg); 503 free(lang); 504 return 0; 505 } 506 507 /* ARGSUSED */ 508 int 509 input_userauth_success(int type, u_int32_t seq, void *ctxt) 510 { 511 Authctxt *authctxt = ctxt; 512 513 if (authctxt == NULL) 514 fatal("input_userauth_success: no authentication context"); 515 free(authctxt->authlist); 516 authctxt->authlist = NULL; 517 if (authctxt->method != NULL && authctxt->method->cleanup != NULL) 518 authctxt->method->cleanup(authctxt); 519 free(authctxt->methoddata); 520 authctxt->methoddata = NULL; 521 authctxt->success = 1; /* break out */ 522 return 0; 523 } 524 525 int 526 input_userauth_success_unexpected(int type, u_int32_t seq, void *ctxt) 527 { 528 Authctxt *authctxt = ctxt; 529 530 if (authctxt == NULL) 531 fatal("%s: no authentication context", __func__); 532 533 fatal("Unexpected authentication success during %s.", 534 authctxt->method->name); 535 return 0; 536 } 537 538 /* ARGSUSED */ 539 int 540 input_userauth_failure(int type, u_int32_t seq, void *ctxt) 541 { 542 Authctxt *authctxt = ctxt; 543 char *authlist = NULL; 544 int partial; 545 546 if (authctxt == NULL) 547 fatal("input_userauth_failure: no authentication context"); 548 549 authlist = packet_get_string(NULL); 550 partial = packet_get_char(); 551 packet_check_eom(); 552 553 if (partial != 0) { 554 verbose("Authenticated with partial success."); 555 /* reset state */ 556 pubkey_reset(authctxt); 557 } 558 debug("Authentications that can continue: %s", authlist); 559 560 userauth(authctxt, authlist); 561 return 0; 562 } 563 564 /* ARGSUSED */ 565 int 566 input_userauth_pk_ok(int type, u_int32_t seq, void *ctxt) 567 { 568 Authctxt *authctxt = ctxt; 569 Key *key = NULL; 570 Identity *id = NULL; 571 Buffer b; 572 int pktype, sent = 0; 573 u_int alen, blen; 574 char *pkalg, *fp; 575 u_char *pkblob; 576 577 if (authctxt == NULL) 578 fatal("input_userauth_pk_ok: no authentication context"); 579 if (datafellows & SSH_BUG_PKOK) { 580 /* this is similar to SSH_BUG_PKAUTH */ 581 debug2("input_userauth_pk_ok: SSH_BUG_PKOK"); 582 pkblob = packet_get_string(&blen); 583 buffer_init(&b); 584 buffer_append(&b, pkblob, blen); 585 pkalg = buffer_get_string(&b, &alen); 586 buffer_free(&b); 587 } else { 588 pkalg = packet_get_string(&alen); 589 pkblob = packet_get_string(&blen); 590 } 591 packet_check_eom(); 592 593 debug("Server accepts key: pkalg %s blen %u", pkalg, blen); 594 595 if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) { 596 debug("unknown pkalg %s", pkalg); 597 goto done; 598 } 599 if ((key = key_from_blob(pkblob, blen)) == NULL) { 600 debug("no key from blob. pkalg %s", pkalg); 601 goto done; 602 } 603 if (key->type != pktype) { 604 error("input_userauth_pk_ok: type mismatch " 605 "for decoded key (received %d, expected %d)", 606 key->type, pktype); 607 goto done; 608 } 609 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash, 610 SSH_FP_DEFAULT)) == NULL) 611 goto done; 612 debug2("input_userauth_pk_ok: fp %s", fp); 613 free(fp); 614 615 /* 616 * search keys in the reverse order, because last candidate has been 617 * moved to the end of the queue. this also avoids confusion by 618 * duplicate keys 619 */ 620 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) { 621 if (key_equal(key, id->key)) { 622 sent = sign_and_send_pubkey(authctxt, id); 623 break; 624 } 625 } 626 done: 627 if (key != NULL) 628 key_free(key); 629 free(pkalg); 630 free(pkblob); 631 632 /* try another method if we did not send a packet */ 633 if (sent == 0) 634 userauth(authctxt, NULL); 635 return 0; 636 } 637 638 #ifdef GSSAPI 639 int 640 userauth_gssapi(Authctxt *authctxt) 641 { 642 Gssctxt *gssctxt = NULL; 643 static gss_OID_set gss_supported = NULL; 644 static u_int mech = 0; 645 OM_uint32 min; 646 int ok = 0; 647 648 /* Try one GSSAPI method at a time, rather than sending them all at 649 * once. */ 650 651 if (gss_supported == NULL) 652 gss_indicate_mechs(&min, &gss_supported); 653 654 /* Check to see if the mechanism is usable before we offer it */ 655 while (mech < gss_supported->count && !ok) { 656 /* My DER encoding requires length<128 */ 657 if (gss_supported->elements[mech].length < 128 && 658 ssh_gssapi_check_mechanism(&gssctxt, 659 &gss_supported->elements[mech], authctxt->host)) { 660 ok = 1; /* Mechanism works */ 661 } else { 662 mech++; 663 } 664 } 665 666 if (!ok) 667 return 0; 668 669 authctxt->methoddata=(void *)gssctxt; 670 671 packet_start(SSH2_MSG_USERAUTH_REQUEST); 672 packet_put_cstring(authctxt->server_user); 673 packet_put_cstring(authctxt->service); 674 packet_put_cstring(authctxt->method->name); 675 676 packet_put_int(1); 677 678 packet_put_int((gss_supported->elements[mech].length) + 2); 679 packet_put_char(SSH_GSS_OIDTYPE); 680 packet_put_char(gss_supported->elements[mech].length); 681 packet_put_raw(gss_supported->elements[mech].elements, 682 gss_supported->elements[mech].length); 683 684 packet_send(); 685 686 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response); 687 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token); 688 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error); 689 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok); 690 691 mech++; /* Move along to next candidate */ 692 693 return 1; 694 } 695 696 static OM_uint32 697 process_gssapi_token(void *ctxt, gss_buffer_t recv_tok) 698 { 699 Authctxt *authctxt = ctxt; 700 Gssctxt *gssctxt = authctxt->methoddata; 701 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER; 702 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER; 703 gss_buffer_desc gssbuf; 704 OM_uint32 status, ms, flags; 705 Buffer b; 706 707 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds, 708 recv_tok, &send_tok, &flags); 709 710 if (send_tok.length > 0) { 711 if (GSS_ERROR(status)) 712 packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK); 713 else 714 packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN); 715 716 packet_put_string(send_tok.value, send_tok.length); 717 packet_send(); 718 gss_release_buffer(&ms, &send_tok); 719 } 720 721 if (status == GSS_S_COMPLETE) { 722 /* send either complete or MIC, depending on mechanism */ 723 if (!(flags & GSS_C_INTEG_FLAG)) { 724 packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE); 725 packet_send(); 726 } else { 727 ssh_gssapi_buildmic(&b, authctxt->server_user, 728 authctxt->service, "gssapi-with-mic"); 729 730 gssbuf.value = buffer_ptr(&b); 731 gssbuf.length = buffer_len(&b); 732 733 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic); 734 735 if (!GSS_ERROR(status)) { 736 packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC); 737 packet_put_string(mic.value, mic.length); 738 739 packet_send(); 740 } 741 742 buffer_free(&b); 743 gss_release_buffer(&ms, &mic); 744 } 745 } 746 747 return status; 748 } 749 750 /* ARGSUSED */ 751 int 752 input_gssapi_response(int type, u_int32_t plen, void *ctxt) 753 { 754 Authctxt *authctxt = ctxt; 755 Gssctxt *gssctxt; 756 int oidlen; 757 char *oidv; 758 759 if (authctxt == NULL) 760 fatal("input_gssapi_response: no authentication context"); 761 gssctxt = authctxt->methoddata; 762 763 /* Setup our OID */ 764 oidv = packet_get_string(&oidlen); 765 766 if (oidlen <= 2 || 767 oidv[0] != SSH_GSS_OIDTYPE || 768 oidv[1] != oidlen - 2) { 769 free(oidv); 770 debug("Badly encoded mechanism OID received"); 771 userauth(authctxt, NULL); 772 return 0; 773 } 774 775 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2)) 776 fatal("Server returned different OID than expected"); 777 778 packet_check_eom(); 779 780 free(oidv); 781 782 if (GSS_ERROR(process_gssapi_token(ctxt, GSS_C_NO_BUFFER))) { 783 /* Start again with next method on list */ 784 debug("Trying to start again"); 785 userauth(authctxt, NULL); 786 return 0; 787 } 788 return 0; 789 } 790 791 /* ARGSUSED */ 792 int 793 input_gssapi_token(int type, u_int32_t plen, void *ctxt) 794 { 795 Authctxt *authctxt = ctxt; 796 gss_buffer_desc recv_tok; 797 OM_uint32 status; 798 u_int slen; 799 800 if (authctxt == NULL) 801 fatal("input_gssapi_response: no authentication context"); 802 803 recv_tok.value = packet_get_string(&slen); 804 recv_tok.length = slen; /* safe typecast */ 805 806 packet_check_eom(); 807 808 status = process_gssapi_token(ctxt, &recv_tok); 809 810 free(recv_tok.value); 811 812 if (GSS_ERROR(status)) { 813 /* Start again with the next method in the list */ 814 userauth(authctxt, NULL); 815 return 0; 816 } 817 return 0; 818 } 819 820 /* ARGSUSED */ 821 int 822 input_gssapi_errtok(int type, u_int32_t plen, void *ctxt) 823 { 824 Authctxt *authctxt = ctxt; 825 Gssctxt *gssctxt; 826 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER; 827 gss_buffer_desc recv_tok; 828 OM_uint32 ms; 829 u_int len; 830 831 if (authctxt == NULL) 832 fatal("input_gssapi_response: no authentication context"); 833 gssctxt = authctxt->methoddata; 834 835 recv_tok.value = packet_get_string(&len); 836 recv_tok.length = len; 837 838 packet_check_eom(); 839 840 /* Stick it into GSSAPI and see what it says */ 841 (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds, 842 &recv_tok, &send_tok, NULL); 843 844 free(recv_tok.value); 845 gss_release_buffer(&ms, &send_tok); 846 847 /* Server will be returning a failed packet after this one */ 848 return 0; 849 } 850 851 /* ARGSUSED */ 852 int 853 input_gssapi_error(int type, u_int32_t plen, void *ctxt) 854 { 855 char *msg; 856 char *lang; 857 858 /* maj */(void)packet_get_int(); 859 /* min */(void)packet_get_int(); 860 msg=packet_get_string(NULL); 861 lang=packet_get_string(NULL); 862 863 packet_check_eom(); 864 865 debug("Server GSSAPI Error:\n%s", msg); 866 free(msg); 867 free(lang); 868 return 0; 869 } 870 #endif /* GSSAPI */ 871 872 int 873 userauth_none(Authctxt *authctxt) 874 { 875 /* initial userauth request */ 876 packet_start(SSH2_MSG_USERAUTH_REQUEST); 877 packet_put_cstring(authctxt->server_user); 878 packet_put_cstring(authctxt->service); 879 packet_put_cstring(authctxt->method->name); 880 packet_send(); 881 return 1; 882 } 883 884 int 885 userauth_passwd(Authctxt *authctxt) 886 { 887 static int attempt = 0; 888 char prompt[150]; 889 char *password; 890 const char *host = options.host_key_alias ? options.host_key_alias : 891 authctxt->host; 892 893 if (attempt++ >= options.number_of_password_prompts) 894 return 0; 895 896 if (attempt != 1) 897 error("Permission denied, please try again."); 898 899 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ", 900 authctxt->server_user, host); 901 password = read_passphrase(prompt, 0); 902 packet_start(SSH2_MSG_USERAUTH_REQUEST); 903 packet_put_cstring(authctxt->server_user); 904 packet_put_cstring(authctxt->service); 905 packet_put_cstring(authctxt->method->name); 906 packet_put_char(0); 907 packet_put_cstring(password); 908 explicit_bzero(password, strlen(password)); 909 free(password); 910 packet_add_padding(64); 911 packet_send(); 912 913 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, 914 &input_userauth_passwd_changereq); 915 916 return 1; 917 } 918 919 /* 920 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST 921 */ 922 /* ARGSUSED */ 923 int 924 input_userauth_passwd_changereq(int type, u_int32_t seqnr, void *ctxt) 925 { 926 Authctxt *authctxt = ctxt; 927 char *info, *lang, *password = NULL, *retype = NULL; 928 char prompt[150]; 929 const char *host = options.host_key_alias ? options.host_key_alias : 930 authctxt->host; 931 932 debug2("input_userauth_passwd_changereq"); 933 934 if (authctxt == NULL) 935 fatal("input_userauth_passwd_changereq: " 936 "no authentication context"); 937 938 info = packet_get_string(NULL); 939 lang = packet_get_string(NULL); 940 if (strlen(info) > 0) 941 logit("%s", info); 942 free(info); 943 free(lang); 944 packet_start(SSH2_MSG_USERAUTH_REQUEST); 945 packet_put_cstring(authctxt->server_user); 946 packet_put_cstring(authctxt->service); 947 packet_put_cstring(authctxt->method->name); 948 packet_put_char(1); /* additional info */ 949 snprintf(prompt, sizeof(prompt), 950 "Enter %.30s@%.128s's old password: ", 951 authctxt->server_user, host); 952 password = read_passphrase(prompt, 0); 953 packet_put_cstring(password); 954 explicit_bzero(password, strlen(password)); 955 free(password); 956 password = NULL; 957 while (password == NULL) { 958 snprintf(prompt, sizeof(prompt), 959 "Enter %.30s@%.128s's new password: ", 960 authctxt->server_user, host); 961 password = read_passphrase(prompt, RP_ALLOW_EOF); 962 if (password == NULL) { 963 /* bail out */ 964 return 0; 965 } 966 snprintf(prompt, sizeof(prompt), 967 "Retype %.30s@%.128s's new password: ", 968 authctxt->server_user, host); 969 retype = read_passphrase(prompt, 0); 970 if (strcmp(password, retype) != 0) { 971 explicit_bzero(password, strlen(password)); 972 free(password); 973 logit("Mismatch; try again, EOF to quit."); 974 password = NULL; 975 } 976 explicit_bzero(retype, strlen(retype)); 977 free(retype); 978 } 979 packet_put_cstring(password); 980 explicit_bzero(password, strlen(password)); 981 free(password); 982 packet_add_padding(64); 983 packet_send(); 984 985 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, 986 &input_userauth_passwd_changereq); 987 return 0; 988 } 989 990 static const char * 991 identity_sign_encode(struct identity *id) 992 { 993 struct ssh *ssh = active_state; 994 995 if (id->key->type == KEY_RSA) { 996 switch (ssh->kex->rsa_sha2) { 997 case 256: 998 return "rsa-sha2-256"; 999 case 512: 1000 return "rsa-sha2-512"; 1001 } 1002 } 1003 return key_ssh_name(id->key); 1004 } 1005 1006 static int 1007 identity_sign(struct identity *id, u_char **sigp, size_t *lenp, 1008 const u_char *data, size_t datalen, u_int compat) 1009 { 1010 Key *prv; 1011 int ret; 1012 const char *alg; 1013 1014 alg = identity_sign_encode(id); 1015 1016 /* the agent supports this key */ 1017 if (id->agent_fd != -1) 1018 return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp, 1019 data, datalen, alg, compat); 1020 1021 /* 1022 * we have already loaded the private key or 1023 * the private key is stored in external hardware 1024 */ 1025 if (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT)) 1026 return (sshkey_sign(id->key, sigp, lenp, data, datalen, alg, 1027 compat)); 1028 /* load the private key from the file */ 1029 if ((prv = load_identity_file(id)) == NULL) 1030 return SSH_ERR_KEY_NOT_FOUND; 1031 ret = sshkey_sign(prv, sigp, lenp, data, datalen, alg, compat); 1032 sshkey_free(prv); 1033 return (ret); 1034 } 1035 1036 static int 1037 sign_and_send_pubkey(Authctxt *authctxt, Identity *id) 1038 { 1039 Buffer b; 1040 Identity *private_id; 1041 u_char *blob, *signature; 1042 size_t slen; 1043 u_int bloblen, skip = 0; 1044 int matched, ret = -1, have_sig = 1; 1045 char *fp; 1046 1047 if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash, 1048 SSH_FP_DEFAULT)) == NULL) 1049 return 0; 1050 debug3("%s: %s %s", __func__, key_type(id->key), fp); 1051 free(fp); 1052 1053 if (key_to_blob(id->key, &blob, &bloblen) == 0) { 1054 /* we cannot handle this key */ 1055 debug3("sign_and_send_pubkey: cannot handle key"); 1056 return 0; 1057 } 1058 /* data to be signed */ 1059 buffer_init(&b); 1060 if (datafellows & SSH_OLD_SESSIONID) { 1061 buffer_append(&b, session_id2, session_id2_len); 1062 skip = session_id2_len; 1063 } else { 1064 buffer_put_string(&b, session_id2, session_id2_len); 1065 skip = buffer_len(&b); 1066 } 1067 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST); 1068 buffer_put_cstring(&b, authctxt->server_user); 1069 buffer_put_cstring(&b, 1070 datafellows & SSH_BUG_PKSERVICE ? 1071 "ssh-userauth" : 1072 authctxt->service); 1073 if (datafellows & SSH_BUG_PKAUTH) { 1074 buffer_put_char(&b, have_sig); 1075 } else { 1076 buffer_put_cstring(&b, authctxt->method->name); 1077 buffer_put_char(&b, have_sig); 1078 buffer_put_cstring(&b, identity_sign_encode(id)); 1079 } 1080 buffer_put_string(&b, blob, bloblen); 1081 1082 /* 1083 * If the key is an certificate, try to find a matching private key 1084 * and use it to complete the signature. 1085 * If no such private key exists, fall back to trying the certificate 1086 * key itself in case it has a private half already loaded. 1087 */ 1088 if (key_is_cert(id->key)) { 1089 matched = 0; 1090 TAILQ_FOREACH(private_id, &authctxt->keys, next) { 1091 if (sshkey_equal_public(id->key, private_id->key) && 1092 id->key->type != private_id->key->type) { 1093 id = private_id; 1094 matched = 1; 1095 break; 1096 } 1097 } 1098 if (matched) { 1099 debug2("%s: using private key \"%s\"%s for " 1100 "certificate", __func__, id->filename, 1101 id->agent_fd != -1 ? " from agent" : ""); 1102 } else { 1103 debug("%s: no separate private key for certificate " 1104 "\"%s\"", __func__, id->filename); 1105 } 1106 } 1107 1108 /* generate signature */ 1109 ret = identity_sign(id, &signature, &slen, 1110 buffer_ptr(&b), buffer_len(&b), datafellows); 1111 if (ret != 0) { 1112 if (ret != SSH_ERR_KEY_NOT_FOUND) 1113 error("%s: signing failed: %s", __func__, ssh_err(ret)); 1114 free(blob); 1115 buffer_free(&b); 1116 return 0; 1117 } 1118 #ifdef DEBUG_PK 1119 buffer_dump(&b); 1120 #endif 1121 if (datafellows & SSH_BUG_PKSERVICE) { 1122 buffer_clear(&b); 1123 buffer_append(&b, session_id2, session_id2_len); 1124 skip = session_id2_len; 1125 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST); 1126 buffer_put_cstring(&b, authctxt->server_user); 1127 buffer_put_cstring(&b, authctxt->service); 1128 buffer_put_cstring(&b, authctxt->method->name); 1129 buffer_put_char(&b, have_sig); 1130 if (!(datafellows & SSH_BUG_PKAUTH)) 1131 buffer_put_cstring(&b, key_ssh_name(id->key)); 1132 buffer_put_string(&b, blob, bloblen); 1133 } 1134 free(blob); 1135 1136 /* append signature */ 1137 buffer_put_string(&b, signature, slen); 1138 free(signature); 1139 1140 /* skip session id and packet type */ 1141 if (buffer_len(&b) < skip + 1) 1142 fatal("userauth_pubkey: internal error"); 1143 buffer_consume(&b, skip + 1); 1144 1145 /* put remaining data from buffer into packet */ 1146 packet_start(SSH2_MSG_USERAUTH_REQUEST); 1147 packet_put_raw(buffer_ptr(&b), buffer_len(&b)); 1148 buffer_free(&b); 1149 packet_send(); 1150 1151 return 1; 1152 } 1153 1154 static int 1155 send_pubkey_test(Authctxt *authctxt, Identity *id) 1156 { 1157 u_char *blob; 1158 u_int bloblen, have_sig = 0; 1159 1160 debug3("send_pubkey_test"); 1161 1162 if (key_to_blob(id->key, &blob, &bloblen) == 0) { 1163 /* we cannot handle this key */ 1164 debug3("send_pubkey_test: cannot handle key"); 1165 return 0; 1166 } 1167 /* register callback for USERAUTH_PK_OK message */ 1168 dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok); 1169 1170 packet_start(SSH2_MSG_USERAUTH_REQUEST); 1171 packet_put_cstring(authctxt->server_user); 1172 packet_put_cstring(authctxt->service); 1173 packet_put_cstring(authctxt->method->name); 1174 packet_put_char(have_sig); 1175 if (!(datafellows & SSH_BUG_PKAUTH)) 1176 packet_put_cstring(identity_sign_encode(id)); 1177 packet_put_string(blob, bloblen); 1178 free(blob); 1179 packet_send(); 1180 return 1; 1181 } 1182 1183 static Key * 1184 load_identity_file(Identity *id) 1185 { 1186 Key *private = NULL; 1187 char prompt[300], *passphrase, *comment; 1188 int r, perm_ok = 0, quit = 0, i; 1189 struct stat st; 1190 1191 if (stat(id->filename, &st) < 0) { 1192 (id->userprovided ? logit : debug3)("no such identity: %s: %s", 1193 id->filename, strerror(errno)); 1194 return NULL; 1195 } 1196 snprintf(prompt, sizeof prompt, 1197 "Enter passphrase for key '%.100s': ", id->filename); 1198 for (i = 0; i <= options.number_of_password_prompts; i++) { 1199 if (i == 0) 1200 passphrase = ""; 1201 else { 1202 passphrase = read_passphrase(prompt, 0); 1203 if (*passphrase == '\0') { 1204 debug2("no passphrase given, try next key"); 1205 free(passphrase); 1206 break; 1207 } 1208 } 1209 switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename, 1210 passphrase, &private, &comment, &perm_ok))) { 1211 case 0: 1212 break; 1213 case SSH_ERR_KEY_WRONG_PASSPHRASE: 1214 if (options.batch_mode) { 1215 quit = 1; 1216 break; 1217 } 1218 if (i != 0) 1219 debug2("bad passphrase given, try again..."); 1220 break; 1221 case SSH_ERR_SYSTEM_ERROR: 1222 if (errno == ENOENT) { 1223 debug2("Load key \"%s\": %s", 1224 id->filename, ssh_err(r)); 1225 quit = 1; 1226 break; 1227 } 1228 /* FALLTHROUGH */ 1229 default: 1230 error("Load key \"%s\": %s", id->filename, ssh_err(r)); 1231 quit = 1; 1232 break; 1233 } 1234 if (!quit && private != NULL && id->agent_fd == -1 && 1235 !(id->key && id->isprivate)) 1236 maybe_add_key_to_agent(id->filename, private, comment, 1237 passphrase); 1238 if (i > 0) { 1239 explicit_bzero(passphrase, strlen(passphrase)); 1240 free(passphrase); 1241 } 1242 free(comment); 1243 if (private != NULL || quit) 1244 break; 1245 } 1246 return private; 1247 } 1248 1249 /* 1250 * try keys in the following order: 1251 * 1. certificates listed in the config file 1252 * 2. other input certificates 1253 * 3. agent keys that are found in the config file 1254 * 4. other agent keys 1255 * 5. keys that are only listed in the config file 1256 */ 1257 static void 1258 pubkey_prepare(Authctxt *authctxt) 1259 { 1260 struct identity *id, *id2, *tmp; 1261 struct idlist agent, files, *preferred; 1262 struct sshkey *key; 1263 int agent_fd = -1, i, r, found; 1264 size_t j; 1265 struct ssh_identitylist *idlist; 1266 1267 TAILQ_INIT(&agent); /* keys from the agent */ 1268 TAILQ_INIT(&files); /* keys from the config file */ 1269 preferred = &authctxt->keys; 1270 TAILQ_INIT(preferred); /* preferred order of keys */ 1271 1272 /* list of keys stored in the filesystem and PKCS#11 */ 1273 for (i = 0; i < options.num_identity_files; i++) { 1274 key = options.identity_keys[i]; 1275 if (key && key->type == KEY_RSA1) 1276 continue; 1277 if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER) 1278 continue; 1279 options.identity_keys[i] = NULL; 1280 id = xcalloc(1, sizeof(*id)); 1281 id->agent_fd = -1; 1282 id->key = key; 1283 id->filename = xstrdup(options.identity_files[i]); 1284 id->userprovided = options.identity_file_userprovided[i]; 1285 TAILQ_INSERT_TAIL(&files, id, next); 1286 } 1287 /* list of certificates specified by user */ 1288 for (i = 0; i < options.num_certificate_files; i++) { 1289 key = options.certificates[i]; 1290 if (!key_is_cert(key) || key->cert == NULL || 1291 key->cert->type != SSH2_CERT_TYPE_USER) 1292 continue; 1293 id = xcalloc(1, sizeof(*id)); 1294 id->agent_fd = -1; 1295 id->key = key; 1296 id->filename = xstrdup(options.certificate_files[i]); 1297 id->userprovided = options.certificate_file_userprovided[i]; 1298 TAILQ_INSERT_TAIL(preferred, id, next); 1299 } 1300 /* list of keys supported by the agent */ 1301 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) { 1302 if (r != SSH_ERR_AGENT_NOT_PRESENT) 1303 debug("%s: ssh_get_authentication_socket: %s", 1304 __func__, ssh_err(r)); 1305 } else if ((r = ssh_fetch_identitylist(agent_fd, 2, &idlist)) != 0) { 1306 if (r != SSH_ERR_AGENT_NO_IDENTITIES) 1307 debug("%s: ssh_fetch_identitylist: %s", 1308 __func__, ssh_err(r)); 1309 close(agent_fd); 1310 } else { 1311 for (j = 0; j < idlist->nkeys; j++) { 1312 found = 0; 1313 TAILQ_FOREACH(id, &files, next) { 1314 /* 1315 * agent keys from the config file are 1316 * preferred 1317 */ 1318 if (sshkey_equal(idlist->keys[j], id->key)) { 1319 TAILQ_REMOVE(&files, id, next); 1320 TAILQ_INSERT_TAIL(preferred, id, next); 1321 id->agent_fd = agent_fd; 1322 found = 1; 1323 break; 1324 } 1325 } 1326 if (!found && !options.identities_only) { 1327 id = xcalloc(1, sizeof(*id)); 1328 /* XXX "steals" key/comment from idlist */ 1329 id->key = idlist->keys[j]; 1330 id->filename = idlist->comments[j]; 1331 idlist->keys[j] = NULL; 1332 idlist->comments[j] = NULL; 1333 id->agent_fd = agent_fd; 1334 TAILQ_INSERT_TAIL(&agent, id, next); 1335 } 1336 } 1337 ssh_free_identitylist(idlist); 1338 /* append remaining agent keys */ 1339 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) { 1340 TAILQ_REMOVE(&agent, id, next); 1341 TAILQ_INSERT_TAIL(preferred, id, next); 1342 } 1343 authctxt->agent_fd = agent_fd; 1344 } 1345 /* Prefer PKCS11 keys that are explicitly listed */ 1346 TAILQ_FOREACH_SAFE(id, &files, next, tmp) { 1347 if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0) 1348 continue; 1349 found = 0; 1350 TAILQ_FOREACH(id2, &files, next) { 1351 if (id2->key == NULL || 1352 (id2->key->flags & SSHKEY_FLAG_EXT) == 0) 1353 continue; 1354 if (sshkey_equal(id->key, id2->key)) { 1355 TAILQ_REMOVE(&files, id, next); 1356 TAILQ_INSERT_TAIL(preferred, id, next); 1357 found = 1; 1358 break; 1359 } 1360 } 1361 /* If IdentitiesOnly set and key not found then don't use it */ 1362 if (!found && options.identities_only) { 1363 TAILQ_REMOVE(&files, id, next); 1364 explicit_bzero(id, sizeof(*id)); 1365 free(id); 1366 } 1367 } 1368 /* append remaining keys from the config file */ 1369 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) { 1370 TAILQ_REMOVE(&files, id, next); 1371 TAILQ_INSERT_TAIL(preferred, id, next); 1372 } 1373 /* finally, filter by PubkeyAcceptedKeyTypes */ 1374 TAILQ_FOREACH_SAFE(id, preferred, next, id2) { 1375 if (id->key != NULL && 1376 match_pattern_list(sshkey_ssh_name(id->key), 1377 options.pubkey_key_types, 0) != 1) { 1378 debug("Skipping %s key %s - " 1379 "not in PubkeyAcceptedKeyTypes", 1380 sshkey_ssh_name(id->key), id->filename); 1381 TAILQ_REMOVE(preferred, id, next); 1382 sshkey_free(id->key); 1383 free(id->filename); 1384 memset(id, 0, sizeof(*id)); 1385 continue; 1386 } 1387 debug2("key: %s (%p)%s%s", id->filename, id->key, 1388 id->userprovided ? ", explicit" : "", 1389 id->agent_fd != -1 ? ", agent" : ""); 1390 } 1391 } 1392 1393 static void 1394 pubkey_cleanup(Authctxt *authctxt) 1395 { 1396 Identity *id; 1397 1398 if (authctxt->agent_fd != -1) 1399 ssh_close_authentication_socket(authctxt->agent_fd); 1400 for (id = TAILQ_FIRST(&authctxt->keys); id; 1401 id = TAILQ_FIRST(&authctxt->keys)) { 1402 TAILQ_REMOVE(&authctxt->keys, id, next); 1403 sshkey_free(id->key); 1404 free(id->filename); 1405 free(id); 1406 } 1407 } 1408 1409 static void 1410 pubkey_reset(Authctxt *authctxt) 1411 { 1412 Identity *id; 1413 1414 TAILQ_FOREACH(id, &authctxt->keys, next) 1415 id->tried = 0; 1416 } 1417 1418 static int 1419 try_identity(Identity *id) 1420 { 1421 if (!id->key) 1422 return (0); 1423 if (key_type_plain(id->key->type) == KEY_RSA && 1424 (datafellows & SSH_BUG_RSASIGMD5) != 0) { 1425 debug("Skipped %s key %s for RSA/MD5 server", 1426 key_type(id->key), id->filename); 1427 return (0); 1428 } 1429 return (id->key->type != KEY_RSA1); 1430 } 1431 1432 int 1433 userauth_pubkey(Authctxt *authctxt) 1434 { 1435 Identity *id; 1436 int sent = 0; 1437 1438 while ((id = TAILQ_FIRST(&authctxt->keys))) { 1439 if (id->tried++) 1440 return (0); 1441 /* move key to the end of the queue */ 1442 TAILQ_REMOVE(&authctxt->keys, id, next); 1443 TAILQ_INSERT_TAIL(&authctxt->keys, id, next); 1444 /* 1445 * send a test message if we have the public key. for 1446 * encrypted keys we cannot do this and have to load the 1447 * private key instead 1448 */ 1449 if (id->key != NULL) { 1450 if (try_identity(id)) { 1451 debug("Offering %s public key: %s", 1452 key_type(id->key), id->filename); 1453 sent = send_pubkey_test(authctxt, id); 1454 } 1455 } else { 1456 debug("Trying private key: %s", id->filename); 1457 id->key = load_identity_file(id); 1458 if (id->key != NULL) { 1459 if (try_identity(id)) { 1460 id->isprivate = 1; 1461 sent = sign_and_send_pubkey( 1462 authctxt, id); 1463 } 1464 key_free(id->key); 1465 id->key = NULL; 1466 id->isprivate = 0; 1467 } 1468 } 1469 if (sent) 1470 return (sent); 1471 } 1472 return (0); 1473 } 1474 1475 /* 1476 * Send userauth request message specifying keyboard-interactive method. 1477 */ 1478 int 1479 userauth_kbdint(Authctxt *authctxt) 1480 { 1481 static int attempt = 0; 1482 1483 if (attempt++ >= options.number_of_password_prompts) 1484 return 0; 1485 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */ 1486 if (attempt > 1 && !authctxt->info_req_seen) { 1487 debug3("userauth_kbdint: disable: no info_req_seen"); 1488 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL); 1489 return 0; 1490 } 1491 1492 debug2("userauth_kbdint"); 1493 packet_start(SSH2_MSG_USERAUTH_REQUEST); 1494 packet_put_cstring(authctxt->server_user); 1495 packet_put_cstring(authctxt->service); 1496 packet_put_cstring(authctxt->method->name); 1497 packet_put_cstring(""); /* lang */ 1498 packet_put_cstring(options.kbd_interactive_devices ? 1499 options.kbd_interactive_devices : ""); 1500 packet_send(); 1501 1502 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req); 1503 return 1; 1504 } 1505 1506 /* 1507 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE 1508 */ 1509 int 1510 input_userauth_info_req(int type, u_int32_t seq, void *ctxt) 1511 { 1512 Authctxt *authctxt = ctxt; 1513 char *name, *inst, *lang, *prompt, *response; 1514 u_int num_prompts, i; 1515 int echo = 0; 1516 1517 debug2("input_userauth_info_req"); 1518 1519 if (authctxt == NULL) 1520 fatal("input_userauth_info_req: no authentication context"); 1521 1522 authctxt->info_req_seen = 1; 1523 1524 name = packet_get_string(NULL); 1525 inst = packet_get_string(NULL); 1526 lang = packet_get_string(NULL); 1527 if (strlen(name) > 0) 1528 logit("%s", name); 1529 if (strlen(inst) > 0) 1530 logit("%s", inst); 1531 free(name); 1532 free(inst); 1533 free(lang); 1534 1535 num_prompts = packet_get_int(); 1536 /* 1537 * Begin to build info response packet based on prompts requested. 1538 * We commit to providing the correct number of responses, so if 1539 * further on we run into a problem that prevents this, we have to 1540 * be sure and clean this up and send a correct error response. 1541 */ 1542 packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE); 1543 packet_put_int(num_prompts); 1544 1545 debug2("input_userauth_info_req: num_prompts %d", num_prompts); 1546 for (i = 0; i < num_prompts; i++) { 1547 prompt = packet_get_string(NULL); 1548 echo = packet_get_char(); 1549 1550 response = read_passphrase(prompt, echo ? RP_ECHO : 0); 1551 1552 packet_put_cstring(response); 1553 explicit_bzero(response, strlen(response)); 1554 free(response); 1555 free(prompt); 1556 } 1557 packet_check_eom(); /* done with parsing incoming message. */ 1558 1559 packet_add_padding(64); 1560 packet_send(); 1561 return 0; 1562 } 1563 1564 static int 1565 ssh_keysign(struct sshkey *key, u_char **sigp, size_t *lenp, 1566 const u_char *data, size_t datalen) 1567 { 1568 struct sshbuf *b; 1569 struct stat st; 1570 pid_t pid; 1571 int i, r, to[2], from[2], status, sock = packet_get_connection_in(); 1572 u_char rversion = 0, version = 2; 1573 void (*osigchld)(int); 1574 1575 *sigp = NULL; 1576 *lenp = 0; 1577 1578 if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) { 1579 error("%s: not installed: %s", __func__, strerror(errno)); 1580 return -1; 1581 } 1582 if (fflush(stdout) != 0) { 1583 error("%s: fflush: %s", __func__, strerror(errno)); 1584 return -1; 1585 } 1586 if (pipe(to) < 0) { 1587 error("%s: pipe: %s", __func__, strerror(errno)); 1588 return -1; 1589 } 1590 if (pipe(from) < 0) { 1591 error("%s: pipe: %s", __func__, strerror(errno)); 1592 return -1; 1593 } 1594 if ((pid = fork()) < 0) { 1595 error("%s: fork: %s", __func__, strerror(errno)); 1596 return -1; 1597 } 1598 osigchld = signal(SIGCHLD, SIG_DFL); 1599 if (pid == 0) { 1600 /* keep the socket on exec */ 1601 fcntl(sock, F_SETFD, 0); 1602 permanently_drop_suid(getuid()); 1603 close(from[0]); 1604 if (dup2(from[1], STDOUT_FILENO) < 0) 1605 fatal("%s: dup2: %s", __func__, strerror(errno)); 1606 close(to[1]); 1607 if (dup2(to[0], STDIN_FILENO) < 0) 1608 fatal("%s: dup2: %s", __func__, strerror(errno)); 1609 close(from[1]); 1610 close(to[0]); 1611 /* Close everything but stdio and the socket */ 1612 for (i = STDERR_FILENO + 1; i < sock; i++) 1613 close(i); 1614 closefrom(sock + 1); 1615 debug3("%s: [child] pid=%ld, exec %s", 1616 __func__, (long)getpid(), _PATH_SSH_KEY_SIGN); 1617 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL); 1618 fatal("%s: exec(%s): %s", __func__, _PATH_SSH_KEY_SIGN, 1619 strerror(errno)); 1620 } 1621 close(from[1]); 1622 close(to[0]); 1623 1624 if ((b = sshbuf_new()) == NULL) 1625 fatal("%s: sshbuf_new failed", __func__); 1626 /* send # of sock, data to be signed */ 1627 if ((r = sshbuf_put_u32(b, sock) != 0) || 1628 (r = sshbuf_put_string(b, data, datalen)) != 0) 1629 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 1630 if (ssh_msg_send(to[1], version, b) == -1) 1631 fatal("%s: couldn't send request", __func__); 1632 sshbuf_reset(b); 1633 r = ssh_msg_recv(from[0], b); 1634 close(from[0]); 1635 close(to[1]); 1636 if (r < 0) { 1637 error("%s: no reply", __func__); 1638 goto fail; 1639 } 1640 1641 errno = 0; 1642 while (waitpid(pid, &status, 0) < 0) { 1643 if (errno != EINTR) { 1644 error("%s: waitpid %ld: %s", 1645 __func__, (long)pid, strerror(errno)); 1646 goto fail; 1647 } 1648 } 1649 if (!WIFEXITED(status)) { 1650 error("%s: exited abnormally", __func__); 1651 goto fail; 1652 } 1653 if (WEXITSTATUS(status) != 0) { 1654 error("%s: exited with status %d", 1655 __func__, WEXITSTATUS(status)); 1656 goto fail; 1657 } 1658 if ((r = sshbuf_get_u8(b, &rversion)) != 0) { 1659 error("%s: buffer error: %s", __func__, ssh_err(r)); 1660 goto fail; 1661 } 1662 if (rversion != version) { 1663 error("%s: bad version", __func__); 1664 goto fail; 1665 } 1666 if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) { 1667 error("%s: buffer error: %s", __func__, ssh_err(r)); 1668 fail: 1669 signal(SIGCHLD, osigchld); 1670 sshbuf_free(b); 1671 return -1; 1672 } 1673 signal(SIGCHLD, osigchld); 1674 sshbuf_free(b); 1675 1676 return 0; 1677 } 1678 1679 int 1680 userauth_hostbased(Authctxt *authctxt) 1681 { 1682 struct ssh *ssh = active_state; 1683 struct sshkey *private = NULL; 1684 struct sshbuf *b = NULL; 1685 const char *service; 1686 u_char *sig = NULL, *keyblob = NULL; 1687 char *fp = NULL, *chost = NULL, *lname = NULL; 1688 size_t siglen = 0, keylen = 0; 1689 int i, r, success = 0; 1690 1691 if (authctxt->ktypes == NULL) { 1692 authctxt->oktypes = xstrdup(options.hostbased_key_types); 1693 authctxt->ktypes = authctxt->oktypes; 1694 } 1695 1696 /* 1697 * Work through each listed type pattern in HostbasedKeyTypes, 1698 * trying each hostkey that matches the type in turn. 1699 */ 1700 for (;;) { 1701 if (authctxt->active_ktype == NULL) 1702 authctxt->active_ktype = strsep(&authctxt->ktypes, ","); 1703 if (authctxt->active_ktype == NULL || 1704 *authctxt->active_ktype == '\0') 1705 break; 1706 debug3("%s: trying key type %s", __func__, 1707 authctxt->active_ktype); 1708 1709 /* check for a useful key */ 1710 private = NULL; 1711 for (i = 0; i < authctxt->sensitive->nkeys; i++) { 1712 if (authctxt->sensitive->keys[i] == NULL || 1713 authctxt->sensitive->keys[i]->type == KEY_RSA1 || 1714 authctxt->sensitive->keys[i]->type == KEY_UNSPEC) 1715 continue; 1716 if (match_pattern_list( 1717 sshkey_ssh_name(authctxt->sensitive->keys[i]), 1718 authctxt->active_ktype, 0) != 1) 1719 continue; 1720 /* we take and free the key */ 1721 private = authctxt->sensitive->keys[i]; 1722 authctxt->sensitive->keys[i] = NULL; 1723 break; 1724 } 1725 /* Found one */ 1726 if (private != NULL) 1727 break; 1728 /* No more keys of this type; advance */ 1729 authctxt->active_ktype = NULL; 1730 } 1731 if (private == NULL) { 1732 free(authctxt->oktypes); 1733 authctxt->oktypes = authctxt->ktypes = NULL; 1734 authctxt->active_ktype = NULL; 1735 debug("No more client hostkeys for hostbased authentication."); 1736 goto out; 1737 } 1738 1739 if ((fp = sshkey_fingerprint(private, options.fingerprint_hash, 1740 SSH_FP_DEFAULT)) == NULL) { 1741 error("%s: sshkey_fingerprint failed", __func__); 1742 goto out; 1743 } 1744 debug("%s: trying hostkey %s %s", 1745 __func__, sshkey_ssh_name(private), fp); 1746 1747 /* figure out a name for the client host */ 1748 if ((lname = get_local_name(packet_get_connection_in())) == NULL) { 1749 error("%s: cannot get local ipaddr/name", __func__); 1750 goto out; 1751 } 1752 1753 /* XXX sshbuf_put_stringf? */ 1754 xasprintf(&chost, "%s.", lname); 1755 debug2("%s: chost %s", __func__, chost); 1756 1757 service = datafellows & SSH_BUG_HBSERVICE ? "ssh-userauth" : 1758 authctxt->service; 1759 1760 /* construct data */ 1761 if ((b = sshbuf_new()) == NULL) { 1762 error("%s: sshbuf_new failed", __func__); 1763 goto out; 1764 } 1765 if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) { 1766 error("%s: sshkey_to_blob: %s", __func__, ssh_err(r)); 1767 goto out; 1768 } 1769 if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 || 1770 (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1771 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 || 1772 (r = sshbuf_put_cstring(b, service)) != 0 || 1773 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 || 1774 (r = sshbuf_put_cstring(b, key_ssh_name(private))) != 0 || 1775 (r = sshbuf_put_string(b, keyblob, keylen)) != 0 || 1776 (r = sshbuf_put_cstring(b, chost)) != 0 || 1777 (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) { 1778 error("%s: buffer error: %s", __func__, ssh_err(r)); 1779 goto out; 1780 } 1781 1782 #ifdef DEBUG_PK 1783 sshbuf_dump(b, stderr); 1784 #endif 1785 if (authctxt->sensitive->external_keysign) 1786 r = ssh_keysign(private, &sig, &siglen, 1787 sshbuf_ptr(b), sshbuf_len(b)); 1788 else if ((r = sshkey_sign(private, &sig, &siglen, 1789 sshbuf_ptr(b), sshbuf_len(b), NULL, datafellows)) != 0) 1790 debug("%s: sshkey_sign: %s", __func__, ssh_err(r)); 1791 if (r != 0) { 1792 error("sign using hostkey %s %s failed", 1793 sshkey_ssh_name(private), fp); 1794 goto out; 1795 } 1796 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1797 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 || 1798 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 || 1799 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 || 1800 (r = sshpkt_put_cstring(ssh, key_ssh_name(private))) != 0 || 1801 (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 || 1802 (r = sshpkt_put_cstring(ssh, chost)) != 0 || 1803 (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 || 1804 (r = sshpkt_put_string(ssh, sig, siglen)) != 0 || 1805 (r = sshpkt_send(ssh)) != 0) { 1806 error("%s: packet error: %s", __func__, ssh_err(r)); 1807 goto out; 1808 } 1809 success = 1; 1810 1811 out: 1812 if (sig != NULL) { 1813 explicit_bzero(sig, siglen); 1814 free(sig); 1815 } 1816 free(keyblob); 1817 free(lname); 1818 free(fp); 1819 free(chost); 1820 sshkey_free(private); 1821 sshbuf_free(b); 1822 1823 return success; 1824 } 1825 1826 /* find auth method */ 1827 1828 /* 1829 * given auth method name, if configurable options permit this method fill 1830 * in auth_ident field and return true, otherwise return false. 1831 */ 1832 static int 1833 authmethod_is_enabled(Authmethod *method) 1834 { 1835 if (method == NULL) 1836 return 0; 1837 /* return false if options indicate this method is disabled */ 1838 if (method->enabled == NULL || *method->enabled == 0) 1839 return 0; 1840 /* return false if batch mode is enabled but method needs interactive mode */ 1841 if (method->batch_flag != NULL && *method->batch_flag != 0) 1842 return 0; 1843 return 1; 1844 } 1845 1846 static Authmethod * 1847 authmethod_lookup(const char *name) 1848 { 1849 Authmethod *method = NULL; 1850 if (name != NULL) 1851 for (method = authmethods; method->name != NULL; method++) 1852 if (strcmp(name, method->name) == 0) 1853 return method; 1854 debug2("Unrecognized authentication method name: %s", name ? name : "NULL"); 1855 return NULL; 1856 } 1857 1858 /* XXX internal state */ 1859 static Authmethod *current = NULL; 1860 static char *supported = NULL; 1861 static char *preferred = NULL; 1862 1863 /* 1864 * Given the authentication method list sent by the server, return the 1865 * next method we should try. If the server initially sends a nil list, 1866 * use a built-in default list. 1867 */ 1868 static Authmethod * 1869 authmethod_get(char *authlist) 1870 { 1871 char *name = NULL; 1872 u_int next; 1873 1874 /* Use a suitable default if we're passed a nil list. */ 1875 if (authlist == NULL || strlen(authlist) == 0) 1876 authlist = options.preferred_authentications; 1877 1878 if (supported == NULL || strcmp(authlist, supported) != 0) { 1879 debug3("start over, passed a different list %s", authlist); 1880 free(supported); 1881 supported = xstrdup(authlist); 1882 preferred = options.preferred_authentications; 1883 debug3("preferred %s", preferred); 1884 current = NULL; 1885 } else if (current != NULL && authmethod_is_enabled(current)) 1886 return current; 1887 1888 for (;;) { 1889 if ((name = match_list(preferred, supported, &next)) == NULL) { 1890 debug("No more authentication methods to try."); 1891 current = NULL; 1892 return NULL; 1893 } 1894 preferred += next; 1895 debug3("authmethod_lookup %s", name); 1896 debug3("remaining preferred: %s", preferred); 1897 if ((current = authmethod_lookup(name)) != NULL && 1898 authmethod_is_enabled(current)) { 1899 debug3("authmethod_is_enabled %s", name); 1900 debug("Next authentication method: %s", name); 1901 free(name); 1902 return current; 1903 } 1904 free(name); 1905 } 1906 } 1907 1908 static char * 1909 authmethods_get(void) 1910 { 1911 Authmethod *method = NULL; 1912 Buffer b; 1913 char *list; 1914 1915 buffer_init(&b); 1916 for (method = authmethods; method->name != NULL; method++) { 1917 if (authmethod_is_enabled(method)) { 1918 if (buffer_len(&b) > 0) 1919 buffer_append(&b, ",", 1); 1920 buffer_append(&b, method->name, strlen(method->name)); 1921 } 1922 } 1923 if ((list = sshbuf_dup_string(&b)) == NULL) 1924 fatal("%s: sshbuf_dup_string failed", __func__); 1925 buffer_free(&b); 1926 return list; 1927 } 1928 1929