1 /* $OpenBSD: sshconnect2.c,v 1.267 2018/01/23 05:27:21 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(struct sshkey *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(options.rekey_limit, 191 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 ssh_dispatch_run_fatal(active_state, DISPATCH_BLOCK, &kex->done); 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, struct ssh *); 283 int input_userauth_ext_info(int, u_int32_t, struct ssh *); 284 int input_userauth_success(int, u_int32_t, struct ssh *); 285 int input_userauth_success_unexpected(int, u_int32_t, struct ssh *); 286 int input_userauth_failure(int, u_int32_t, struct ssh *); 287 int input_userauth_banner(int, u_int32_t, struct ssh *); 288 int input_userauth_error(int, u_int32_t, struct ssh *); 289 int input_userauth_info_req(int, u_int32_t, struct ssh *); 290 int input_userauth_pk_ok(int, u_int32_t, struct ssh *); 291 int input_userauth_passwd_changereq(int, u_int32_t, struct ssh *); 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, struct ssh *); 302 int input_gssapi_token(int type, u_int32_t, struct ssh *); 303 int input_gssapi_hash(int type, u_int32_t, struct ssh *); 304 int input_gssapi_error(int, u_int32_t, struct ssh *); 305 int input_gssapi_errtok(int, u_int32_t, struct ssh *); 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 struct sshkey *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->authctxt = &authctxt; 393 ssh_dispatch_init(ssh, &input_userauth_error); 394 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_ext_info); 395 ssh_dispatch_set(ssh, SSH2_MSG_SERVICE_ACCEPT, &input_userauth_service_accept); 396 ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &authctxt.success); /* loop until success */ 397 ssh->authctxt = NULL; 398 399 pubkey_cleanup(&authctxt); 400 ssh_dispatch_range(ssh, SSH2_MSG_USERAUTH_MIN, SSH2_MSG_USERAUTH_MAX, NULL); 401 402 if (!authctxt.success) 403 fatal("Authentication failed."); 404 debug("Authentication succeeded (%s).", authctxt.method->name); 405 } 406 407 /* ARGSUSED */ 408 int 409 input_userauth_service_accept(int type, u_int32_t seq, struct ssh *ssh) 410 { 411 Authctxt *authctxt = ssh->authctxt; 412 int r; 413 414 if (ssh_packet_remaining(ssh) > 0) { 415 char *reply; 416 417 if ((r = sshpkt_get_cstring(ssh, &reply, NULL)) != 0) 418 goto out; 419 debug2("service_accept: %s", reply); 420 free(reply); 421 } else { 422 debug2("buggy server: service_accept w/o service"); 423 } 424 if ((r = sshpkt_get_end(ssh)) != 0) 425 goto out; 426 debug("SSH2_MSG_SERVICE_ACCEPT received"); 427 428 /* initial userauth request */ 429 userauth_none(authctxt); 430 431 ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &input_userauth_error); 432 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_SUCCESS, &input_userauth_success); 433 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_FAILURE, &input_userauth_failure); 434 ssh_dispatch_set(ssh, SSH2_MSG_USERAUTH_BANNER, &input_userauth_banner); 435 r = 0; 436 out: 437 return r; 438 } 439 440 /* ARGSUSED */ 441 int 442 input_userauth_ext_info(int type, u_int32_t seqnr, struct ssh *ssh) 443 { 444 return kex_input_ext_info(type, seqnr, ssh); 445 } 446 447 void 448 userauth(Authctxt *authctxt, char *authlist) 449 { 450 if (authctxt->method != NULL && authctxt->method->cleanup != NULL) 451 authctxt->method->cleanup(authctxt); 452 453 free(authctxt->methoddata); 454 authctxt->methoddata = NULL; 455 if (authlist == NULL) { 456 authlist = authctxt->authlist; 457 } else { 458 free(authctxt->authlist); 459 authctxt->authlist = authlist; 460 } 461 for (;;) { 462 Authmethod *method = authmethod_get(authlist); 463 if (method == NULL) 464 fatal("%s@%s: Permission denied (%s).", 465 authctxt->server_user, authctxt->host, authlist); 466 authctxt->method = method; 467 468 /* reset the per method handler */ 469 dispatch_range(SSH2_MSG_USERAUTH_PER_METHOD_MIN, 470 SSH2_MSG_USERAUTH_PER_METHOD_MAX, NULL); 471 472 /* and try new method */ 473 if (method->userauth(authctxt) != 0) { 474 debug2("we sent a %s packet, wait for reply", method->name); 475 break; 476 } else { 477 debug2("we did not send a packet, disable method"); 478 method->enabled = NULL; 479 } 480 } 481 } 482 483 /* ARGSUSED */ 484 int 485 input_userauth_error(int type, u_int32_t seq, struct ssh *ssh) 486 { 487 fatal("input_userauth_error: bad message during authentication: " 488 "type %d", type); 489 return 0; 490 } 491 492 /* ARGSUSED */ 493 int 494 input_userauth_banner(int type, u_int32_t seq, struct ssh *ssh) 495 { 496 char *msg, *lang; 497 u_int len; 498 499 debug3("%s", __func__); 500 msg = packet_get_string(&len); 501 lang = packet_get_string(NULL); 502 if (len > 0 && options.log_level >= SYSLOG_LEVEL_INFO) 503 fmprintf(stderr, "%s", msg); 504 free(msg); 505 free(lang); 506 return 0; 507 } 508 509 /* ARGSUSED */ 510 int 511 input_userauth_success(int type, u_int32_t seq, struct ssh *ssh) 512 { 513 Authctxt *authctxt = ssh->authctxt; 514 515 if (authctxt == NULL) 516 fatal("input_userauth_success: no authentication context"); 517 free(authctxt->authlist); 518 authctxt->authlist = NULL; 519 if (authctxt->method != NULL && authctxt->method->cleanup != NULL) 520 authctxt->method->cleanup(authctxt); 521 free(authctxt->methoddata); 522 authctxt->methoddata = NULL; 523 authctxt->success = 1; /* break out */ 524 return 0; 525 } 526 527 int 528 input_userauth_success_unexpected(int type, u_int32_t seq, struct ssh *ssh) 529 { 530 Authctxt *authctxt = ssh->authctxt; 531 532 if (authctxt == NULL) 533 fatal("%s: no authentication context", __func__); 534 535 fatal("Unexpected authentication success during %s.", 536 authctxt->method->name); 537 return 0; 538 } 539 540 /* ARGSUSED */ 541 int 542 input_userauth_failure(int type, u_int32_t seq, struct ssh *ssh) 543 { 544 Authctxt *authctxt = ssh->authctxt; 545 char *authlist = NULL; 546 int partial; 547 548 if (authctxt == NULL) 549 fatal("input_userauth_failure: no authentication context"); 550 551 authlist = packet_get_string(NULL); 552 partial = packet_get_char(); 553 packet_check_eom(); 554 555 if (partial != 0) { 556 verbose("Authenticated with partial success."); 557 /* reset state */ 558 pubkey_reset(authctxt); 559 } 560 debug("Authentications that can continue: %s", authlist); 561 562 userauth(authctxt, authlist); 563 return 0; 564 } 565 566 /* ARGSUSED */ 567 int 568 input_userauth_pk_ok(int type, u_int32_t seq, struct ssh *ssh) 569 { 570 Authctxt *authctxt = ssh->authctxt; 571 struct sshkey *key = NULL; 572 Identity *id = NULL; 573 int pktype, sent = 0; 574 u_int alen, blen; 575 char *pkalg, *fp; 576 u_char *pkblob; 577 578 if (authctxt == NULL) 579 fatal("input_userauth_pk_ok: no authentication context"); 580 581 pkalg = packet_get_string(&alen); 582 pkblob = packet_get_string(&blen); 583 packet_check_eom(); 584 585 debug("Server accepts key: pkalg %s blen %u", pkalg, blen); 586 587 if ((pktype = key_type_from_name(pkalg)) == KEY_UNSPEC) { 588 debug("unknown pkalg %s", pkalg); 589 goto done; 590 } 591 if ((key = key_from_blob(pkblob, blen)) == NULL) { 592 debug("no key from blob. pkalg %s", pkalg); 593 goto done; 594 } 595 if (key->type != pktype) { 596 error("input_userauth_pk_ok: type mismatch " 597 "for decoded key (received %d, expected %d)", 598 key->type, pktype); 599 goto done; 600 } 601 if ((fp = sshkey_fingerprint(key, options.fingerprint_hash, 602 SSH_FP_DEFAULT)) == NULL) 603 goto done; 604 debug2("input_userauth_pk_ok: fp %s", fp); 605 free(fp); 606 607 /* 608 * search keys in the reverse order, because last candidate has been 609 * moved to the end of the queue. this also avoids confusion by 610 * duplicate keys 611 */ 612 TAILQ_FOREACH_REVERSE(id, &authctxt->keys, idlist, next) { 613 if (key_equal(key, id->key)) { 614 sent = sign_and_send_pubkey(authctxt, id); 615 break; 616 } 617 } 618 done: 619 if (key != NULL) 620 key_free(key); 621 free(pkalg); 622 free(pkblob); 623 624 /* try another method if we did not send a packet */ 625 if (sent == 0) 626 userauth(authctxt, NULL); 627 return 0; 628 } 629 630 #ifdef GSSAPI 631 int 632 userauth_gssapi(Authctxt *authctxt) 633 { 634 Gssctxt *gssctxt = NULL; 635 static gss_OID_set gss_supported = NULL; 636 static u_int mech = 0; 637 OM_uint32 min; 638 int ok = 0; 639 640 /* Try one GSSAPI method at a time, rather than sending them all at 641 * once. */ 642 643 if (gss_supported == NULL) 644 gss_indicate_mechs(&min, &gss_supported); 645 646 /* Check to see if the mechanism is usable before we offer it */ 647 while (mech < gss_supported->count && !ok) { 648 /* My DER encoding requires length<128 */ 649 if (gss_supported->elements[mech].length < 128 && 650 ssh_gssapi_check_mechanism(&gssctxt, 651 &gss_supported->elements[mech], authctxt->host)) { 652 ok = 1; /* Mechanism works */ 653 } else { 654 mech++; 655 } 656 } 657 658 if (!ok) 659 return 0; 660 661 authctxt->methoddata=(void *)gssctxt; 662 663 packet_start(SSH2_MSG_USERAUTH_REQUEST); 664 packet_put_cstring(authctxt->server_user); 665 packet_put_cstring(authctxt->service); 666 packet_put_cstring(authctxt->method->name); 667 668 packet_put_int(1); 669 670 packet_put_int((gss_supported->elements[mech].length) + 2); 671 packet_put_char(SSH_GSS_OIDTYPE); 672 packet_put_char(gss_supported->elements[mech].length); 673 packet_put_raw(gss_supported->elements[mech].elements, 674 gss_supported->elements[mech].length); 675 676 packet_send(); 677 678 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_RESPONSE, &input_gssapi_response); 679 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_TOKEN, &input_gssapi_token); 680 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERROR, &input_gssapi_error); 681 dispatch_set(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK, &input_gssapi_errtok); 682 683 mech++; /* Move along to next candidate */ 684 685 return 1; 686 } 687 688 static OM_uint32 689 process_gssapi_token(struct ssh *ssh, gss_buffer_t recv_tok) 690 { 691 Authctxt *authctxt = ssh->authctxt; 692 Gssctxt *gssctxt = authctxt->methoddata; 693 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER; 694 gss_buffer_desc mic = GSS_C_EMPTY_BUFFER; 695 gss_buffer_desc gssbuf; 696 OM_uint32 status, ms, flags; 697 Buffer b; 698 699 status = ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds, 700 recv_tok, &send_tok, &flags); 701 702 if (send_tok.length > 0) { 703 if (GSS_ERROR(status)) 704 packet_start(SSH2_MSG_USERAUTH_GSSAPI_ERRTOK); 705 else 706 packet_start(SSH2_MSG_USERAUTH_GSSAPI_TOKEN); 707 708 packet_put_string(send_tok.value, send_tok.length); 709 packet_send(); 710 gss_release_buffer(&ms, &send_tok); 711 } 712 713 if (status == GSS_S_COMPLETE) { 714 /* send either complete or MIC, depending on mechanism */ 715 if (!(flags & GSS_C_INTEG_FLAG)) { 716 packet_start(SSH2_MSG_USERAUTH_GSSAPI_EXCHANGE_COMPLETE); 717 packet_send(); 718 } else { 719 ssh_gssapi_buildmic(&b, authctxt->server_user, 720 authctxt->service, "gssapi-with-mic"); 721 722 gssbuf.value = buffer_ptr(&b); 723 gssbuf.length = buffer_len(&b); 724 725 status = ssh_gssapi_sign(gssctxt, &gssbuf, &mic); 726 727 if (!GSS_ERROR(status)) { 728 packet_start(SSH2_MSG_USERAUTH_GSSAPI_MIC); 729 packet_put_string(mic.value, mic.length); 730 731 packet_send(); 732 } 733 734 buffer_free(&b); 735 gss_release_buffer(&ms, &mic); 736 } 737 } 738 739 return status; 740 } 741 742 /* ARGSUSED */ 743 int 744 input_gssapi_response(int type, u_int32_t plen, struct ssh *ssh) 745 { 746 Authctxt *authctxt = ssh->authctxt; 747 Gssctxt *gssctxt; 748 int oidlen; 749 char *oidv; 750 751 if (authctxt == NULL) 752 fatal("input_gssapi_response: no authentication context"); 753 gssctxt = authctxt->methoddata; 754 755 /* Setup our OID */ 756 oidv = packet_get_string(&oidlen); 757 758 if (oidlen <= 2 || 759 oidv[0] != SSH_GSS_OIDTYPE || 760 oidv[1] != oidlen - 2) { 761 free(oidv); 762 debug("Badly encoded mechanism OID received"); 763 userauth(authctxt, NULL); 764 return 0; 765 } 766 767 if (!ssh_gssapi_check_oid(gssctxt, oidv + 2, oidlen - 2)) 768 fatal("Server returned different OID than expected"); 769 770 packet_check_eom(); 771 772 free(oidv); 773 774 if (GSS_ERROR(process_gssapi_token(ssh, GSS_C_NO_BUFFER))) { 775 /* Start again with next method on list */ 776 debug("Trying to start again"); 777 userauth(authctxt, NULL); 778 return 0; 779 } 780 return 0; 781 } 782 783 /* ARGSUSED */ 784 int 785 input_gssapi_token(int type, u_int32_t plen, struct ssh *ssh) 786 { 787 Authctxt *authctxt = ssh->authctxt; 788 gss_buffer_desc recv_tok; 789 OM_uint32 status; 790 u_int slen; 791 792 if (authctxt == NULL) 793 fatal("input_gssapi_response: no authentication context"); 794 795 recv_tok.value = packet_get_string(&slen); 796 recv_tok.length = slen; /* safe typecast */ 797 798 packet_check_eom(); 799 800 status = process_gssapi_token(ssh, &recv_tok); 801 802 free(recv_tok.value); 803 804 if (GSS_ERROR(status)) { 805 /* Start again with the next method in the list */ 806 userauth(authctxt, NULL); 807 return 0; 808 } 809 return 0; 810 } 811 812 /* ARGSUSED */ 813 int 814 input_gssapi_errtok(int type, u_int32_t plen, struct ssh *ssh) 815 { 816 Authctxt *authctxt = ssh->authctxt; 817 Gssctxt *gssctxt; 818 gss_buffer_desc send_tok = GSS_C_EMPTY_BUFFER; 819 gss_buffer_desc recv_tok; 820 OM_uint32 ms; 821 u_int len; 822 823 if (authctxt == NULL) 824 fatal("input_gssapi_response: no authentication context"); 825 gssctxt = authctxt->methoddata; 826 827 recv_tok.value = packet_get_string(&len); 828 recv_tok.length = len; 829 830 packet_check_eom(); 831 832 /* Stick it into GSSAPI and see what it says */ 833 (void)ssh_gssapi_init_ctx(gssctxt, options.gss_deleg_creds, 834 &recv_tok, &send_tok, NULL); 835 836 free(recv_tok.value); 837 gss_release_buffer(&ms, &send_tok); 838 839 /* Server will be returning a failed packet after this one */ 840 return 0; 841 } 842 843 /* ARGSUSED */ 844 int 845 input_gssapi_error(int type, u_int32_t plen, struct ssh *ssh) 846 { 847 char *msg; 848 char *lang; 849 850 /* maj */(void)packet_get_int(); 851 /* min */(void)packet_get_int(); 852 msg=packet_get_string(NULL); 853 lang=packet_get_string(NULL); 854 855 packet_check_eom(); 856 857 debug("Server GSSAPI Error:\n%s", msg); 858 free(msg); 859 free(lang); 860 return 0; 861 } 862 #endif /* GSSAPI */ 863 864 int 865 userauth_none(Authctxt *authctxt) 866 { 867 /* initial userauth request */ 868 packet_start(SSH2_MSG_USERAUTH_REQUEST); 869 packet_put_cstring(authctxt->server_user); 870 packet_put_cstring(authctxt->service); 871 packet_put_cstring(authctxt->method->name); 872 packet_send(); 873 return 1; 874 } 875 876 int 877 userauth_passwd(Authctxt *authctxt) 878 { 879 static int attempt = 0; 880 char prompt[256]; 881 char *password; 882 const char *host = options.host_key_alias ? options.host_key_alias : 883 authctxt->host; 884 885 if (attempt++ >= options.number_of_password_prompts) 886 return 0; 887 888 if (attempt != 1) 889 error("Permission denied, please try again."); 890 891 snprintf(prompt, sizeof(prompt), "%.30s@%.128s's password: ", 892 authctxt->server_user, host); 893 password = read_passphrase(prompt, 0); 894 packet_start(SSH2_MSG_USERAUTH_REQUEST); 895 packet_put_cstring(authctxt->server_user); 896 packet_put_cstring(authctxt->service); 897 packet_put_cstring(authctxt->method->name); 898 packet_put_char(0); 899 packet_put_cstring(password); 900 explicit_bzero(password, strlen(password)); 901 free(password); 902 packet_add_padding(64); 903 packet_send(); 904 905 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, 906 &input_userauth_passwd_changereq); 907 908 return 1; 909 } 910 911 /* 912 * parse PASSWD_CHANGEREQ, prompt user and send SSH2_MSG_USERAUTH_REQUEST 913 */ 914 /* ARGSUSED */ 915 int 916 input_userauth_passwd_changereq(int type, u_int32_t seqnr, struct ssh *ssh) 917 { 918 Authctxt *authctxt = ssh->authctxt; 919 char *info, *lang, *password = NULL, *retype = NULL; 920 char prompt[256]; 921 const char *host; 922 923 debug2("input_userauth_passwd_changereq"); 924 925 if (authctxt == NULL) 926 fatal("input_userauth_passwd_changereq: " 927 "no authentication context"); 928 host = options.host_key_alias ? options.host_key_alias : authctxt->host; 929 930 info = packet_get_string(NULL); 931 lang = packet_get_string(NULL); 932 if (strlen(info) > 0) 933 logit("%s", info); 934 free(info); 935 free(lang); 936 packet_start(SSH2_MSG_USERAUTH_REQUEST); 937 packet_put_cstring(authctxt->server_user); 938 packet_put_cstring(authctxt->service); 939 packet_put_cstring(authctxt->method->name); 940 packet_put_char(1); /* additional info */ 941 snprintf(prompt, sizeof(prompt), 942 "Enter %.30s@%.128s's old password: ", 943 authctxt->server_user, host); 944 password = read_passphrase(prompt, 0); 945 packet_put_cstring(password); 946 explicit_bzero(password, strlen(password)); 947 free(password); 948 password = NULL; 949 while (password == NULL) { 950 snprintf(prompt, sizeof(prompt), 951 "Enter %.30s@%.128s's new password: ", 952 authctxt->server_user, host); 953 password = read_passphrase(prompt, RP_ALLOW_EOF); 954 if (password == NULL) { 955 /* bail out */ 956 return 0; 957 } 958 snprintf(prompt, sizeof(prompt), 959 "Retype %.30s@%.128s's new password: ", 960 authctxt->server_user, host); 961 retype = read_passphrase(prompt, 0); 962 if (strcmp(password, retype) != 0) { 963 explicit_bzero(password, strlen(password)); 964 free(password); 965 logit("Mismatch; try again, EOF to quit."); 966 password = NULL; 967 } 968 explicit_bzero(retype, strlen(retype)); 969 free(retype); 970 } 971 packet_put_cstring(password); 972 explicit_bzero(password, strlen(password)); 973 free(password); 974 packet_add_padding(64); 975 packet_send(); 976 977 dispatch_set(SSH2_MSG_USERAUTH_PASSWD_CHANGEREQ, 978 &input_userauth_passwd_changereq); 979 return 0; 980 } 981 982 static const char * 983 key_sign_encode(const struct sshkey *key) 984 { 985 struct ssh *ssh = active_state; 986 987 if (key->type == KEY_RSA) { 988 switch (ssh->kex->rsa_sha2) { 989 case 256: 990 return "rsa-sha2-256"; 991 case 512: 992 return "rsa-sha2-512"; 993 } 994 } 995 return key_ssh_name(key); 996 } 997 998 static int 999 identity_sign(struct identity *id, u_char **sigp, size_t *lenp, 1000 const u_char *data, size_t datalen, u_int compat) 1001 { 1002 struct sshkey *prv; 1003 int ret; 1004 1005 /* the agent supports this key */ 1006 if (id->key != NULL && id->agent_fd != -1) 1007 return ssh_agent_sign(id->agent_fd, id->key, sigp, lenp, 1008 data, datalen, key_sign_encode(id->key), compat); 1009 1010 /* 1011 * we have already loaded the private key or 1012 * the private key is stored in external hardware 1013 */ 1014 if (id->key != NULL && 1015 (id->isprivate || (id->key->flags & SSHKEY_FLAG_EXT))) 1016 return (sshkey_sign(id->key, sigp, lenp, data, datalen, 1017 key_sign_encode(id->key), compat)); 1018 1019 /* load the private key from the file */ 1020 if ((prv = load_identity_file(id)) == NULL) 1021 return SSH_ERR_KEY_NOT_FOUND; 1022 if (id->key != NULL && !sshkey_equal_public(prv, id->key)) { 1023 error("%s: private key %s contents do not match public", 1024 __func__, id->filename); 1025 return SSH_ERR_KEY_NOT_FOUND; 1026 } 1027 ret = sshkey_sign(prv, sigp, lenp, data, datalen, 1028 key_sign_encode(prv), compat); 1029 sshkey_free(prv); 1030 return (ret); 1031 } 1032 1033 static int 1034 id_filename_matches(Identity *id, Identity *private_id) 1035 { 1036 const char *suffixes[] = { ".pub", "-cert.pub", NULL }; 1037 size_t len = strlen(id->filename), plen = strlen(private_id->filename); 1038 size_t i, slen; 1039 1040 if (strcmp(id->filename, private_id->filename) == 0) 1041 return 1; 1042 for (i = 0; suffixes[i]; i++) { 1043 slen = strlen(suffixes[i]); 1044 if (len > slen && plen == len - slen && 1045 strcmp(id->filename + (len - slen), suffixes[i]) == 0 && 1046 memcmp(id->filename, private_id->filename, plen) == 0) 1047 return 1; 1048 } 1049 return 0; 1050 } 1051 1052 static int 1053 sign_and_send_pubkey(Authctxt *authctxt, Identity *id) 1054 { 1055 Buffer b; 1056 Identity *private_id; 1057 u_char *blob, *signature; 1058 size_t slen; 1059 u_int bloblen, skip = 0; 1060 int matched, ret = -1, have_sig = 1; 1061 char *fp; 1062 1063 if ((fp = sshkey_fingerprint(id->key, options.fingerprint_hash, 1064 SSH_FP_DEFAULT)) == NULL) 1065 return 0; 1066 debug3("%s: %s %s", __func__, key_type(id->key), fp); 1067 free(fp); 1068 1069 if (key_to_blob(id->key, &blob, &bloblen) == 0) { 1070 /* we cannot handle this key */ 1071 debug3("sign_and_send_pubkey: cannot handle key"); 1072 return 0; 1073 } 1074 /* data to be signed */ 1075 buffer_init(&b); 1076 if (datafellows & SSH_OLD_SESSIONID) { 1077 buffer_append(&b, session_id2, session_id2_len); 1078 skip = session_id2_len; 1079 } else { 1080 buffer_put_string(&b, session_id2, session_id2_len); 1081 skip = buffer_len(&b); 1082 } 1083 buffer_put_char(&b, SSH2_MSG_USERAUTH_REQUEST); 1084 buffer_put_cstring(&b, authctxt->server_user); 1085 buffer_put_cstring(&b, authctxt->service); 1086 buffer_put_cstring(&b, authctxt->method->name); 1087 buffer_put_char(&b, have_sig); 1088 buffer_put_cstring(&b, key_sign_encode(id->key)); 1089 buffer_put_string(&b, blob, bloblen); 1090 1091 /* 1092 * If the key is an certificate, try to find a matching private key 1093 * and use it to complete the signature. 1094 * If no such private key exists, fall back to trying the certificate 1095 * key itself in case it has a private half already loaded. 1096 */ 1097 if (key_is_cert(id->key)) { 1098 matched = 0; 1099 TAILQ_FOREACH(private_id, &authctxt->keys, next) { 1100 if (sshkey_equal_public(id->key, private_id->key) && 1101 id->key->type != private_id->key->type) { 1102 id = private_id; 1103 matched = 1; 1104 break; 1105 } 1106 } 1107 /* 1108 * Exact key matches are preferred, but also allow 1109 * filename matches for non-PKCS#11/agent keys that 1110 * didn't load public keys. This supports the case 1111 * of keeping just a private key file and public 1112 * certificate on disk. 1113 */ 1114 if (!matched && !id->isprivate && id->agent_fd == -1 && 1115 (id->key->flags & SSHKEY_FLAG_EXT) == 0) { 1116 TAILQ_FOREACH(private_id, &authctxt->keys, next) { 1117 if (private_id->key == NULL && 1118 id_filename_matches(id, private_id)) { 1119 id = private_id; 1120 matched = 1; 1121 break; 1122 } 1123 } 1124 } 1125 if (matched) { 1126 debug2("%s: using private key \"%s\"%s for " 1127 "certificate", __func__, id->filename, 1128 id->agent_fd != -1 ? " from agent" : ""); 1129 } else { 1130 debug("%s: no separate private key for certificate " 1131 "\"%s\"", __func__, id->filename); 1132 } 1133 } 1134 1135 /* generate signature */ 1136 ret = identity_sign(id, &signature, &slen, 1137 buffer_ptr(&b), buffer_len(&b), datafellows); 1138 if (ret != 0) { 1139 if (ret != SSH_ERR_KEY_NOT_FOUND) 1140 error("%s: signing failed: %s", __func__, ssh_err(ret)); 1141 free(blob); 1142 buffer_free(&b); 1143 return 0; 1144 } 1145 #ifdef DEBUG_PK 1146 buffer_dump(&b); 1147 #endif 1148 free(blob); 1149 1150 /* append signature */ 1151 buffer_put_string(&b, signature, slen); 1152 free(signature); 1153 1154 /* skip session id and packet type */ 1155 if (buffer_len(&b) < skip + 1) 1156 fatal("userauth_pubkey: internal error"); 1157 buffer_consume(&b, skip + 1); 1158 1159 /* put remaining data from buffer into packet */ 1160 packet_start(SSH2_MSG_USERAUTH_REQUEST); 1161 packet_put_raw(buffer_ptr(&b), buffer_len(&b)); 1162 buffer_free(&b); 1163 packet_send(); 1164 1165 return 1; 1166 } 1167 1168 static int 1169 send_pubkey_test(Authctxt *authctxt, Identity *id) 1170 { 1171 u_char *blob; 1172 u_int bloblen, have_sig = 0; 1173 1174 debug3("send_pubkey_test"); 1175 1176 if (key_to_blob(id->key, &blob, &bloblen) == 0) { 1177 /* we cannot handle this key */ 1178 debug3("send_pubkey_test: cannot handle key"); 1179 return 0; 1180 } 1181 /* register callback for USERAUTH_PK_OK message */ 1182 dispatch_set(SSH2_MSG_USERAUTH_PK_OK, &input_userauth_pk_ok); 1183 1184 packet_start(SSH2_MSG_USERAUTH_REQUEST); 1185 packet_put_cstring(authctxt->server_user); 1186 packet_put_cstring(authctxt->service); 1187 packet_put_cstring(authctxt->method->name); 1188 packet_put_char(have_sig); 1189 packet_put_cstring(key_sign_encode(id->key)); 1190 packet_put_string(blob, bloblen); 1191 free(blob); 1192 packet_send(); 1193 return 1; 1194 } 1195 1196 static struct sshkey * 1197 load_identity_file(Identity *id) 1198 { 1199 struct sshkey *private = NULL; 1200 char prompt[300], *passphrase, *comment; 1201 int r, perm_ok = 0, quit = 0, i; 1202 struct stat st; 1203 1204 if (stat(id->filename, &st) < 0) { 1205 (id->userprovided ? logit : debug3)("no such identity: %s: %s", 1206 id->filename, strerror(errno)); 1207 return NULL; 1208 } 1209 snprintf(prompt, sizeof prompt, 1210 "Enter passphrase for key '%.100s': ", id->filename); 1211 for (i = 0; i <= options.number_of_password_prompts; i++) { 1212 if (i == 0) 1213 passphrase = ""; 1214 else { 1215 passphrase = read_passphrase(prompt, 0); 1216 if (*passphrase == '\0') { 1217 debug2("no passphrase given, try next key"); 1218 free(passphrase); 1219 break; 1220 } 1221 } 1222 switch ((r = sshkey_load_private_type(KEY_UNSPEC, id->filename, 1223 passphrase, &private, &comment, &perm_ok))) { 1224 case 0: 1225 break; 1226 case SSH_ERR_KEY_WRONG_PASSPHRASE: 1227 if (options.batch_mode) { 1228 quit = 1; 1229 break; 1230 } 1231 if (i != 0) 1232 debug2("bad passphrase given, try again..."); 1233 break; 1234 case SSH_ERR_SYSTEM_ERROR: 1235 if (errno == ENOENT) { 1236 debug2("Load key \"%s\": %s", 1237 id->filename, ssh_err(r)); 1238 quit = 1; 1239 break; 1240 } 1241 /* FALLTHROUGH */ 1242 default: 1243 error("Load key \"%s\": %s", id->filename, ssh_err(r)); 1244 quit = 1; 1245 break; 1246 } 1247 if (!quit && private != NULL && id->agent_fd == -1 && 1248 !(id->key && id->isprivate)) 1249 maybe_add_key_to_agent(id->filename, private, comment, 1250 passphrase); 1251 if (i > 0) { 1252 explicit_bzero(passphrase, strlen(passphrase)); 1253 free(passphrase); 1254 } 1255 free(comment); 1256 if (private != NULL || quit) 1257 break; 1258 } 1259 return private; 1260 } 1261 1262 /* 1263 * try keys in the following order: 1264 * 1. certificates listed in the config file 1265 * 2. other input certificates 1266 * 3. agent keys that are found in the config file 1267 * 4. other agent keys 1268 * 5. keys that are only listed in the config file 1269 */ 1270 static void 1271 pubkey_prepare(Authctxt *authctxt) 1272 { 1273 struct identity *id, *id2, *tmp; 1274 struct idlist agent, files, *preferred; 1275 struct sshkey *key; 1276 int agent_fd = -1, i, r, found; 1277 size_t j; 1278 struct ssh_identitylist *idlist; 1279 1280 TAILQ_INIT(&agent); /* keys from the agent */ 1281 TAILQ_INIT(&files); /* keys from the config file */ 1282 preferred = &authctxt->keys; 1283 TAILQ_INIT(preferred); /* preferred order of keys */ 1284 1285 /* list of keys stored in the filesystem and PKCS#11 */ 1286 for (i = 0; i < options.num_identity_files; i++) { 1287 key = options.identity_keys[i]; 1288 if (key && key->cert && key->cert->type != SSH2_CERT_TYPE_USER) 1289 continue; 1290 options.identity_keys[i] = NULL; 1291 id = xcalloc(1, sizeof(*id)); 1292 id->agent_fd = -1; 1293 id->key = key; 1294 id->filename = xstrdup(options.identity_files[i]); 1295 id->userprovided = options.identity_file_userprovided[i]; 1296 TAILQ_INSERT_TAIL(&files, id, next); 1297 } 1298 /* list of certificates specified by user */ 1299 for (i = 0; i < options.num_certificate_files; i++) { 1300 key = options.certificates[i]; 1301 if (!key_is_cert(key) || key->cert == NULL || 1302 key->cert->type != SSH2_CERT_TYPE_USER) 1303 continue; 1304 id = xcalloc(1, sizeof(*id)); 1305 id->agent_fd = -1; 1306 id->key = key; 1307 id->filename = xstrdup(options.certificate_files[i]); 1308 id->userprovided = options.certificate_file_userprovided[i]; 1309 TAILQ_INSERT_TAIL(preferred, id, next); 1310 } 1311 /* list of keys supported by the agent */ 1312 if ((r = ssh_get_authentication_socket(&agent_fd)) != 0) { 1313 if (r != SSH_ERR_AGENT_NOT_PRESENT) 1314 debug("%s: ssh_get_authentication_socket: %s", 1315 __func__, ssh_err(r)); 1316 } else if ((r = ssh_fetch_identitylist(agent_fd, &idlist)) != 0) { 1317 if (r != SSH_ERR_AGENT_NO_IDENTITIES) 1318 debug("%s: ssh_fetch_identitylist: %s", 1319 __func__, ssh_err(r)); 1320 close(agent_fd); 1321 } else { 1322 for (j = 0; j < idlist->nkeys; j++) { 1323 found = 0; 1324 TAILQ_FOREACH(id, &files, next) { 1325 /* 1326 * agent keys from the config file are 1327 * preferred 1328 */ 1329 if (sshkey_equal(idlist->keys[j], id->key)) { 1330 TAILQ_REMOVE(&files, id, next); 1331 TAILQ_INSERT_TAIL(preferred, id, next); 1332 id->agent_fd = agent_fd; 1333 found = 1; 1334 break; 1335 } 1336 } 1337 if (!found && !options.identities_only) { 1338 id = xcalloc(1, sizeof(*id)); 1339 /* XXX "steals" key/comment from idlist */ 1340 id->key = idlist->keys[j]; 1341 id->filename = idlist->comments[j]; 1342 idlist->keys[j] = NULL; 1343 idlist->comments[j] = NULL; 1344 id->agent_fd = agent_fd; 1345 TAILQ_INSERT_TAIL(&agent, id, next); 1346 } 1347 } 1348 ssh_free_identitylist(idlist); 1349 /* append remaining agent keys */ 1350 for (id = TAILQ_FIRST(&agent); id; id = TAILQ_FIRST(&agent)) { 1351 TAILQ_REMOVE(&agent, id, next); 1352 TAILQ_INSERT_TAIL(preferred, id, next); 1353 } 1354 authctxt->agent_fd = agent_fd; 1355 } 1356 /* Prefer PKCS11 keys that are explicitly listed */ 1357 TAILQ_FOREACH_SAFE(id, &files, next, tmp) { 1358 if (id->key == NULL || (id->key->flags & SSHKEY_FLAG_EXT) == 0) 1359 continue; 1360 found = 0; 1361 TAILQ_FOREACH(id2, &files, next) { 1362 if (id2->key == NULL || 1363 (id2->key->flags & SSHKEY_FLAG_EXT) == 0) 1364 continue; 1365 if (sshkey_equal(id->key, id2->key)) { 1366 TAILQ_REMOVE(&files, id, next); 1367 TAILQ_INSERT_TAIL(preferred, id, next); 1368 found = 1; 1369 break; 1370 } 1371 } 1372 /* If IdentitiesOnly set and key not found then don't use it */ 1373 if (!found && options.identities_only) { 1374 TAILQ_REMOVE(&files, id, next); 1375 explicit_bzero(id, sizeof(*id)); 1376 free(id); 1377 } 1378 } 1379 /* append remaining keys from the config file */ 1380 for (id = TAILQ_FIRST(&files); id; id = TAILQ_FIRST(&files)) { 1381 TAILQ_REMOVE(&files, id, next); 1382 TAILQ_INSERT_TAIL(preferred, id, next); 1383 } 1384 /* finally, filter by PubkeyAcceptedKeyTypes */ 1385 TAILQ_FOREACH_SAFE(id, preferred, next, id2) { 1386 if (id->key != NULL && 1387 match_pattern_list(sshkey_ssh_name(id->key), 1388 options.pubkey_key_types, 0) != 1) { 1389 debug("Skipping %s key %s - " 1390 "not in PubkeyAcceptedKeyTypes", 1391 sshkey_ssh_name(id->key), id->filename); 1392 TAILQ_REMOVE(preferred, id, next); 1393 sshkey_free(id->key); 1394 free(id->filename); 1395 memset(id, 0, sizeof(*id)); 1396 continue; 1397 } 1398 debug2("key: %s (%p)%s%s", id->filename, id->key, 1399 id->userprovided ? ", explicit" : "", 1400 id->agent_fd != -1 ? ", agent" : ""); 1401 } 1402 } 1403 1404 static void 1405 pubkey_cleanup(Authctxt *authctxt) 1406 { 1407 Identity *id; 1408 1409 if (authctxt->agent_fd != -1) 1410 ssh_close_authentication_socket(authctxt->agent_fd); 1411 for (id = TAILQ_FIRST(&authctxt->keys); id; 1412 id = TAILQ_FIRST(&authctxt->keys)) { 1413 TAILQ_REMOVE(&authctxt->keys, id, next); 1414 sshkey_free(id->key); 1415 free(id->filename); 1416 free(id); 1417 } 1418 } 1419 1420 static void 1421 pubkey_reset(Authctxt *authctxt) 1422 { 1423 Identity *id; 1424 1425 TAILQ_FOREACH(id, &authctxt->keys, next) 1426 id->tried = 0; 1427 } 1428 1429 static int 1430 try_identity(Identity *id) 1431 { 1432 if (!id->key) 1433 return (0); 1434 if (key_type_plain(id->key->type) == KEY_RSA && 1435 (datafellows & SSH_BUG_RSASIGMD5) != 0) { 1436 debug("Skipped %s key %s for RSA/MD5 server", 1437 key_type(id->key), id->filename); 1438 return (0); 1439 } 1440 return 1; 1441 } 1442 1443 int 1444 userauth_pubkey(Authctxt *authctxt) 1445 { 1446 Identity *id; 1447 int sent = 0; 1448 char *fp; 1449 1450 while ((id = TAILQ_FIRST(&authctxt->keys))) { 1451 if (id->tried++) 1452 return (0); 1453 /* move key to the end of the queue */ 1454 TAILQ_REMOVE(&authctxt->keys, id, next); 1455 TAILQ_INSERT_TAIL(&authctxt->keys, id, next); 1456 /* 1457 * send a test message if we have the public key. for 1458 * encrypted keys we cannot do this and have to load the 1459 * private key instead 1460 */ 1461 if (id->key != NULL) { 1462 if (try_identity(id)) { 1463 if ((fp = sshkey_fingerprint(id->key, 1464 options.fingerprint_hash, 1465 SSH_FP_DEFAULT)) == NULL) { 1466 error("%s: sshkey_fingerprint failed", 1467 __func__); 1468 return 0; 1469 } 1470 debug("Offering public key: %s %s %s", 1471 sshkey_type(id->key), fp, id->filename); 1472 free(fp); 1473 sent = send_pubkey_test(authctxt, id); 1474 } 1475 } else { 1476 debug("Trying private key: %s", id->filename); 1477 id->key = load_identity_file(id); 1478 if (id->key != NULL) { 1479 if (try_identity(id)) { 1480 id->isprivate = 1; 1481 sent = sign_and_send_pubkey( 1482 authctxt, id); 1483 } 1484 key_free(id->key); 1485 id->key = NULL; 1486 id->isprivate = 0; 1487 } 1488 } 1489 if (sent) 1490 return (sent); 1491 } 1492 return (0); 1493 } 1494 1495 /* 1496 * Send userauth request message specifying keyboard-interactive method. 1497 */ 1498 int 1499 userauth_kbdint(Authctxt *authctxt) 1500 { 1501 static int attempt = 0; 1502 1503 if (attempt++ >= options.number_of_password_prompts) 1504 return 0; 1505 /* disable if no SSH2_MSG_USERAUTH_INFO_REQUEST has been seen */ 1506 if (attempt > 1 && !authctxt->info_req_seen) { 1507 debug3("userauth_kbdint: disable: no info_req_seen"); 1508 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, NULL); 1509 return 0; 1510 } 1511 1512 debug2("userauth_kbdint"); 1513 packet_start(SSH2_MSG_USERAUTH_REQUEST); 1514 packet_put_cstring(authctxt->server_user); 1515 packet_put_cstring(authctxt->service); 1516 packet_put_cstring(authctxt->method->name); 1517 packet_put_cstring(""); /* lang */ 1518 packet_put_cstring(options.kbd_interactive_devices ? 1519 options.kbd_interactive_devices : ""); 1520 packet_send(); 1521 1522 dispatch_set(SSH2_MSG_USERAUTH_INFO_REQUEST, &input_userauth_info_req); 1523 return 1; 1524 } 1525 1526 /* 1527 * parse INFO_REQUEST, prompt user and send INFO_RESPONSE 1528 */ 1529 int 1530 input_userauth_info_req(int type, u_int32_t seq, struct ssh *ssh) 1531 { 1532 Authctxt *authctxt = ssh->authctxt; 1533 char *name, *inst, *lang, *prompt, *response; 1534 u_int num_prompts, i; 1535 int echo = 0; 1536 1537 debug2("input_userauth_info_req"); 1538 1539 if (authctxt == NULL) 1540 fatal("input_userauth_info_req: no authentication context"); 1541 1542 authctxt->info_req_seen = 1; 1543 1544 name = packet_get_string(NULL); 1545 inst = packet_get_string(NULL); 1546 lang = packet_get_string(NULL); 1547 if (strlen(name) > 0) 1548 logit("%s", name); 1549 if (strlen(inst) > 0) 1550 logit("%s", inst); 1551 free(name); 1552 free(inst); 1553 free(lang); 1554 1555 num_prompts = packet_get_int(); 1556 /* 1557 * Begin to build info response packet based on prompts requested. 1558 * We commit to providing the correct number of responses, so if 1559 * further on we run into a problem that prevents this, we have to 1560 * be sure and clean this up and send a correct error response. 1561 */ 1562 packet_start(SSH2_MSG_USERAUTH_INFO_RESPONSE); 1563 packet_put_int(num_prompts); 1564 1565 debug2("input_userauth_info_req: num_prompts %d", num_prompts); 1566 for (i = 0; i < num_prompts; i++) { 1567 prompt = packet_get_string(NULL); 1568 echo = packet_get_char(); 1569 1570 response = read_passphrase(prompt, echo ? RP_ECHO : 0); 1571 1572 packet_put_cstring(response); 1573 explicit_bzero(response, strlen(response)); 1574 free(response); 1575 free(prompt); 1576 } 1577 packet_check_eom(); /* done with parsing incoming message. */ 1578 1579 packet_add_padding(64); 1580 packet_send(); 1581 return 0; 1582 } 1583 1584 static int 1585 ssh_keysign(struct sshkey *key, u_char **sigp, size_t *lenp, 1586 const u_char *data, size_t datalen) 1587 { 1588 struct sshbuf *b; 1589 struct stat st; 1590 pid_t pid; 1591 int i, r, to[2], from[2], status, sock = packet_get_connection_in(); 1592 u_char rversion = 0, version = 2; 1593 void (*osigchld)(int); 1594 1595 *sigp = NULL; 1596 *lenp = 0; 1597 1598 if (stat(_PATH_SSH_KEY_SIGN, &st) < 0) { 1599 error("%s: not installed: %s", __func__, strerror(errno)); 1600 return -1; 1601 } 1602 if (fflush(stdout) != 0) { 1603 error("%s: fflush: %s", __func__, strerror(errno)); 1604 return -1; 1605 } 1606 if (pipe(to) < 0) { 1607 error("%s: pipe: %s", __func__, strerror(errno)); 1608 return -1; 1609 } 1610 if (pipe(from) < 0) { 1611 error("%s: pipe: %s", __func__, strerror(errno)); 1612 return -1; 1613 } 1614 if ((pid = fork()) < 0) { 1615 error("%s: fork: %s", __func__, strerror(errno)); 1616 return -1; 1617 } 1618 osigchld = signal(SIGCHLD, SIG_DFL); 1619 if (pid == 0) { 1620 /* keep the socket on exec */ 1621 fcntl(sock, F_SETFD, 0); 1622 permanently_drop_suid(getuid()); 1623 close(from[0]); 1624 if (dup2(from[1], STDOUT_FILENO) < 0) 1625 fatal("%s: dup2: %s", __func__, strerror(errno)); 1626 close(to[1]); 1627 if (dup2(to[0], STDIN_FILENO) < 0) 1628 fatal("%s: dup2: %s", __func__, strerror(errno)); 1629 close(from[1]); 1630 close(to[0]); 1631 /* Close everything but stdio and the socket */ 1632 for (i = STDERR_FILENO + 1; i < sock; i++) 1633 close(i); 1634 closefrom(sock + 1); 1635 debug3("%s: [child] pid=%ld, exec %s", 1636 __func__, (long)getpid(), _PATH_SSH_KEY_SIGN); 1637 execl(_PATH_SSH_KEY_SIGN, _PATH_SSH_KEY_SIGN, (char *)NULL); 1638 fatal("%s: exec(%s): %s", __func__, _PATH_SSH_KEY_SIGN, 1639 strerror(errno)); 1640 } 1641 close(from[1]); 1642 close(to[0]); 1643 1644 if ((b = sshbuf_new()) == NULL) 1645 fatal("%s: sshbuf_new failed", __func__); 1646 /* send # of sock, data to be signed */ 1647 if ((r = sshbuf_put_u32(b, sock)) != 0 || 1648 (r = sshbuf_put_string(b, data, datalen)) != 0) 1649 fatal("%s: buffer error: %s", __func__, ssh_err(r)); 1650 if (ssh_msg_send(to[1], version, b) == -1) 1651 fatal("%s: couldn't send request", __func__); 1652 sshbuf_reset(b); 1653 r = ssh_msg_recv(from[0], b); 1654 close(from[0]); 1655 close(to[1]); 1656 if (r < 0) { 1657 error("%s: no reply", __func__); 1658 goto fail; 1659 } 1660 1661 errno = 0; 1662 while (waitpid(pid, &status, 0) < 0) { 1663 if (errno != EINTR) { 1664 error("%s: waitpid %ld: %s", 1665 __func__, (long)pid, strerror(errno)); 1666 goto fail; 1667 } 1668 } 1669 if (!WIFEXITED(status)) { 1670 error("%s: exited abnormally", __func__); 1671 goto fail; 1672 } 1673 if (WEXITSTATUS(status) != 0) { 1674 error("%s: exited with status %d", 1675 __func__, WEXITSTATUS(status)); 1676 goto fail; 1677 } 1678 if ((r = sshbuf_get_u8(b, &rversion)) != 0) { 1679 error("%s: buffer error: %s", __func__, ssh_err(r)); 1680 goto fail; 1681 } 1682 if (rversion != version) { 1683 error("%s: bad version", __func__); 1684 goto fail; 1685 } 1686 if ((r = sshbuf_get_string(b, sigp, lenp)) != 0) { 1687 error("%s: buffer error: %s", __func__, ssh_err(r)); 1688 fail: 1689 signal(SIGCHLD, osigchld); 1690 sshbuf_free(b); 1691 return -1; 1692 } 1693 signal(SIGCHLD, osigchld); 1694 sshbuf_free(b); 1695 1696 return 0; 1697 } 1698 1699 int 1700 userauth_hostbased(Authctxt *authctxt) 1701 { 1702 struct ssh *ssh = active_state; 1703 struct sshkey *private = NULL; 1704 struct sshbuf *b = NULL; 1705 u_char *sig = NULL, *keyblob = NULL; 1706 char *fp = NULL, *chost = NULL, *lname = NULL; 1707 size_t siglen = 0, keylen = 0; 1708 int i, r, success = 0; 1709 1710 if (authctxt->ktypes == NULL) { 1711 authctxt->oktypes = xstrdup(options.hostbased_key_types); 1712 authctxt->ktypes = authctxt->oktypes; 1713 } 1714 1715 /* 1716 * Work through each listed type pattern in HostbasedKeyTypes, 1717 * trying each hostkey that matches the type in turn. 1718 */ 1719 for (;;) { 1720 if (authctxt->active_ktype == NULL) 1721 authctxt->active_ktype = strsep(&authctxt->ktypes, ","); 1722 if (authctxt->active_ktype == NULL || 1723 *authctxt->active_ktype == '\0') 1724 break; 1725 debug3("%s: trying key type %s", __func__, 1726 authctxt->active_ktype); 1727 1728 /* check for a useful key */ 1729 private = NULL; 1730 for (i = 0; i < authctxt->sensitive->nkeys; i++) { 1731 if (authctxt->sensitive->keys[i] == NULL || 1732 authctxt->sensitive->keys[i]->type == KEY_UNSPEC) 1733 continue; 1734 if (match_pattern_list( 1735 sshkey_ssh_name(authctxt->sensitive->keys[i]), 1736 authctxt->active_ktype, 0) != 1) 1737 continue; 1738 /* we take and free the key */ 1739 private = authctxt->sensitive->keys[i]; 1740 authctxt->sensitive->keys[i] = NULL; 1741 break; 1742 } 1743 /* Found one */ 1744 if (private != NULL) 1745 break; 1746 /* No more keys of this type; advance */ 1747 authctxt->active_ktype = NULL; 1748 } 1749 if (private == NULL) { 1750 free(authctxt->oktypes); 1751 authctxt->oktypes = authctxt->ktypes = NULL; 1752 authctxt->active_ktype = NULL; 1753 debug("No more client hostkeys for hostbased authentication."); 1754 goto out; 1755 } 1756 1757 if ((fp = sshkey_fingerprint(private, options.fingerprint_hash, 1758 SSH_FP_DEFAULT)) == NULL) { 1759 error("%s: sshkey_fingerprint failed", __func__); 1760 goto out; 1761 } 1762 debug("%s: trying hostkey %s %s", 1763 __func__, sshkey_ssh_name(private), fp); 1764 1765 /* figure out a name for the client host */ 1766 if ((lname = get_local_name(packet_get_connection_in())) == NULL) { 1767 error("%s: cannot get local ipaddr/name", __func__); 1768 goto out; 1769 } 1770 1771 /* XXX sshbuf_put_stringf? */ 1772 xasprintf(&chost, "%s.", lname); 1773 debug2("%s: chost %s", __func__, chost); 1774 1775 /* construct data */ 1776 if ((b = sshbuf_new()) == NULL) { 1777 error("%s: sshbuf_new failed", __func__); 1778 goto out; 1779 } 1780 if ((r = sshkey_to_blob(private, &keyblob, &keylen)) != 0) { 1781 error("%s: sshkey_to_blob: %s", __func__, ssh_err(r)); 1782 goto out; 1783 } 1784 if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 || 1785 (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1786 (r = sshbuf_put_cstring(b, authctxt->server_user)) != 0 || 1787 (r = sshbuf_put_cstring(b, authctxt->service)) != 0 || 1788 (r = sshbuf_put_cstring(b, authctxt->method->name)) != 0 || 1789 (r = sshbuf_put_cstring(b, key_ssh_name(private))) != 0 || 1790 (r = sshbuf_put_string(b, keyblob, keylen)) != 0 || 1791 (r = sshbuf_put_cstring(b, chost)) != 0 || 1792 (r = sshbuf_put_cstring(b, authctxt->local_user)) != 0) { 1793 error("%s: buffer error: %s", __func__, ssh_err(r)); 1794 goto out; 1795 } 1796 1797 #ifdef DEBUG_PK 1798 sshbuf_dump(b, stderr); 1799 #endif 1800 if (authctxt->sensitive->external_keysign) 1801 r = ssh_keysign(private, &sig, &siglen, 1802 sshbuf_ptr(b), sshbuf_len(b)); 1803 else if ((r = sshkey_sign(private, &sig, &siglen, 1804 sshbuf_ptr(b), sshbuf_len(b), NULL, datafellows)) != 0) 1805 debug("%s: sshkey_sign: %s", __func__, ssh_err(r)); 1806 if (r != 0) { 1807 error("sign using hostkey %s %s failed", 1808 sshkey_ssh_name(private), fp); 1809 goto out; 1810 } 1811 if ((r = sshpkt_start(ssh, SSH2_MSG_USERAUTH_REQUEST)) != 0 || 1812 (r = sshpkt_put_cstring(ssh, authctxt->server_user)) != 0 || 1813 (r = sshpkt_put_cstring(ssh, authctxt->service)) != 0 || 1814 (r = sshpkt_put_cstring(ssh, authctxt->method->name)) != 0 || 1815 (r = sshpkt_put_cstring(ssh, key_ssh_name(private))) != 0 || 1816 (r = sshpkt_put_string(ssh, keyblob, keylen)) != 0 || 1817 (r = sshpkt_put_cstring(ssh, chost)) != 0 || 1818 (r = sshpkt_put_cstring(ssh, authctxt->local_user)) != 0 || 1819 (r = sshpkt_put_string(ssh, sig, siglen)) != 0 || 1820 (r = sshpkt_send(ssh)) != 0) { 1821 error("%s: packet error: %s", __func__, ssh_err(r)); 1822 goto out; 1823 } 1824 success = 1; 1825 1826 out: 1827 if (sig != NULL) { 1828 explicit_bzero(sig, siglen); 1829 free(sig); 1830 } 1831 free(keyblob); 1832 free(lname); 1833 free(fp); 1834 free(chost); 1835 sshkey_free(private); 1836 sshbuf_free(b); 1837 1838 return success; 1839 } 1840 1841 /* find auth method */ 1842 1843 /* 1844 * given auth method name, if configurable options permit this method fill 1845 * in auth_ident field and return true, otherwise return false. 1846 */ 1847 static int 1848 authmethod_is_enabled(Authmethod *method) 1849 { 1850 if (method == NULL) 1851 return 0; 1852 /* return false if options indicate this method is disabled */ 1853 if (method->enabled == NULL || *method->enabled == 0) 1854 return 0; 1855 /* return false if batch mode is enabled but method needs interactive mode */ 1856 if (method->batch_flag != NULL && *method->batch_flag != 0) 1857 return 0; 1858 return 1; 1859 } 1860 1861 static Authmethod * 1862 authmethod_lookup(const char *name) 1863 { 1864 Authmethod *method = NULL; 1865 if (name != NULL) 1866 for (method = authmethods; method->name != NULL; method++) 1867 if (strcmp(name, method->name) == 0) 1868 return method; 1869 debug2("Unrecognized authentication method name: %s", name ? name : "NULL"); 1870 return NULL; 1871 } 1872 1873 /* XXX internal state */ 1874 static Authmethod *current = NULL; 1875 static char *supported = NULL; 1876 static char *preferred = NULL; 1877 1878 /* 1879 * Given the authentication method list sent by the server, return the 1880 * next method we should try. If the server initially sends a nil list, 1881 * use a built-in default list. 1882 */ 1883 static Authmethod * 1884 authmethod_get(char *authlist) 1885 { 1886 char *name = NULL; 1887 u_int next; 1888 1889 /* Use a suitable default if we're passed a nil list. */ 1890 if (authlist == NULL || strlen(authlist) == 0) 1891 authlist = options.preferred_authentications; 1892 1893 if (supported == NULL || strcmp(authlist, supported) != 0) { 1894 debug3("start over, passed a different list %s", authlist); 1895 free(supported); 1896 supported = xstrdup(authlist); 1897 preferred = options.preferred_authentications; 1898 debug3("preferred %s", preferred); 1899 current = NULL; 1900 } else if (current != NULL && authmethod_is_enabled(current)) 1901 return current; 1902 1903 for (;;) { 1904 if ((name = match_list(preferred, supported, &next)) == NULL) { 1905 debug("No more authentication methods to try."); 1906 current = NULL; 1907 return NULL; 1908 } 1909 preferred += next; 1910 debug3("authmethod_lookup %s", name); 1911 debug3("remaining preferred: %s", preferred); 1912 if ((current = authmethod_lookup(name)) != NULL && 1913 authmethod_is_enabled(current)) { 1914 debug3("authmethod_is_enabled %s", name); 1915 debug("Next authentication method: %s", name); 1916 free(name); 1917 return current; 1918 } 1919 free(name); 1920 } 1921 } 1922 1923 static char * 1924 authmethods_get(void) 1925 { 1926 Authmethod *method = NULL; 1927 Buffer b; 1928 char *list; 1929 1930 buffer_init(&b); 1931 for (method = authmethods; method->name != NULL; method++) { 1932 if (authmethod_is_enabled(method)) { 1933 if (buffer_len(&b) > 0) 1934 buffer_append(&b, ",", 1); 1935 buffer_append(&b, method->name, strlen(method->name)); 1936 } 1937 } 1938 if ((list = sshbuf_dup_string(&b)) == NULL) 1939 fatal("%s: sshbuf_dup_string failed", __func__); 1940 buffer_free(&b); 1941 return list; 1942 } 1943 1944