1 /* $OpenBSD: sshd-session.c,v 1.12 2025/03/12 22:43:44 djm Exp $ */ 2 /* 3 * SSH2 implementation: 4 * Privilege Separation: 5 * 6 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved. 7 * Copyright (c) 2002 Niels Provos. All rights reserved. 8 * 9 * Redistribution and use in source and binary forms, with or without 10 * modification, are permitted provided that the following conditions 11 * are met: 12 * 1. Redistributions of source code must retain the above copyright 13 * notice, this list of conditions and the following disclaimer. 14 * 2. Redistributions in binary form must reproduce the above copyright 15 * notice, this list of conditions and the following disclaimer in the 16 * documentation and/or other materials provided with the distribution. 17 * 18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR 19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF 27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 28 */ 29 30 #include "includes.h" 31 32 #include <sys/types.h> 33 #include <sys/ioctl.h> 34 #include <sys/socket.h> 35 #ifdef HAVE_SYS_STAT_H 36 # include <sys/stat.h> 37 #endif 38 #ifdef HAVE_SYS_TIME_H 39 # include <sys/time.h> 40 #endif 41 #include "openbsd-compat/sys-tree.h" 42 #include "openbsd-compat/sys-queue.h" 43 #include <sys/wait.h> 44 45 #include <errno.h> 46 #include <fcntl.h> 47 #include <netdb.h> 48 #ifdef HAVE_PATHS_H 49 # include <paths.h> 50 #endif 51 #include <pwd.h> 52 #include <grp.h> 53 #include <signal.h> 54 #include <stdio.h> 55 #include <stdlib.h> 56 #include <string.h> 57 #include <stdarg.h> 58 #include <unistd.h> 59 #include <limits.h> 60 61 #ifdef WITH_OPENSSL 62 #include <openssl/bn.h> 63 #include <openssl/evp.h> 64 #include <openssl/rand.h> 65 #include "openbsd-compat/openssl-compat.h" 66 #endif 67 68 #ifdef HAVE_SECUREWARE 69 #include <sys/security.h> 70 #include <prot.h> 71 #endif 72 73 #include "xmalloc.h" 74 #include "ssh.h" 75 #include "ssh2.h" 76 #include "sshpty.h" 77 #include "packet.h" 78 #include "log.h" 79 #include "sshbuf.h" 80 #include "misc.h" 81 #include "match.h" 82 #include "servconf.h" 83 #include "uidswap.h" 84 #include "compat.h" 85 #include "cipher.h" 86 #include "digest.h" 87 #include "sshkey.h" 88 #include "kex.h" 89 #include "authfile.h" 90 #include "pathnames.h" 91 #include "atomicio.h" 92 #include "canohost.h" 93 #include "hostfile.h" 94 #include "auth.h" 95 #include "authfd.h" 96 #include "msg.h" 97 #include "dispatch.h" 98 #include "channels.h" 99 #include "session.h" 100 #include "monitor.h" 101 #ifdef GSSAPI 102 #include "ssh-gss.h" 103 #endif 104 #include "monitor_wrap.h" 105 #include "auth-options.h" 106 #include "version.h" 107 #include "ssherr.h" 108 #include "sk-api.h" 109 #include "srclimit.h" 110 #include "dh.h" 111 #include "blacklist_client.h" 112 113 /* Re-exec fds */ 114 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1) 115 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 2) 116 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 3) 117 118 /* Privsep fds */ 119 #define PRIVSEP_MONITOR_FD (STDERR_FILENO + 1) 120 #define PRIVSEP_LOG_FD (STDERR_FILENO + 2) 121 #define PRIVSEP_MIN_FREE_FD (STDERR_FILENO + 3) 122 123 extern char *__progname; 124 125 /* Server configuration options. */ 126 ServerOptions options; 127 128 /* Name of the server configuration file. */ 129 char *config_file_name = _PATH_SERVER_CONFIG_FILE; 130 131 /* 132 * Debug mode flag. This can be set on the command line. If debug 133 * mode is enabled, extra debugging output will be sent to the system 134 * log, the daemon will not go to background, and will exit after processing 135 * the first connection. 136 */ 137 int debug_flag = 0; 138 139 /* Flag indicating that the daemon is being started from inetd. */ 140 static int inetd_flag = 0; 141 142 /* debug goes to stderr unless inetd_flag is set */ 143 static int log_stderr = 0; 144 145 /* Saved arguments to main(). */ 146 static char **saved_argv; 147 static int saved_argc; 148 149 /* Daemon's agent connection */ 150 int auth_sock = -1; 151 static int have_agent = 0; 152 153 /* 154 * Any really sensitive data in the application is contained in this 155 * structure. The idea is that this structure could be locked into memory so 156 * that the pages do not get written into swap. However, there are some 157 * problems. The private key contains BIGNUMs, and we do not (in principle) 158 * have access to the internals of them, and locking just the structure is 159 * not very useful. Currently, memory locking is not implemented. 160 */ 161 struct { 162 u_int num_hostkeys; 163 struct sshkey **host_keys; /* all private host keys */ 164 struct sshkey **host_pubkeys; /* all public host keys */ 165 struct sshkey **host_certificates; /* all public host certificates */ 166 } sensitive_data; 167 168 /* record remote hostname or ip */ 169 u_int utmp_len = HOST_NAME_MAX+1; 170 171 static int startup_pipe = -1; /* in child */ 172 173 /* variables used for privilege separation */ 174 struct monitor *pmonitor = NULL; 175 int privsep_is_preauth = 1; 176 static int privsep_chroot = 1; 177 178 /* Unprivileged user */ 179 struct passwd *privsep_pw = NULL; 180 181 /* global connection state and authentication contexts */ 182 Authctxt *the_authctxt = NULL; 183 struct ssh *the_active_state; 184 185 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */ 186 struct sshauthopt *auth_opts = NULL; 187 188 /* sshd_config buffer */ 189 struct sshbuf *cfg; 190 191 /* Included files from the configuration file */ 192 struct include_list includes = TAILQ_HEAD_INITIALIZER(includes); 193 194 /* message to be displayed after login */ 195 struct sshbuf *loginmsg; 196 197 /* Prototypes for various functions defined later in this file. */ 198 void destroy_sensitive_data(void); 199 void demote_sensitive_data(void); 200 201 /* XXX reduce to stub once postauth split */ 202 int 203 mm_is_monitor(void) 204 { 205 /* 206 * m_pid is only set in the privileged part, and 207 * points to the unprivileged child. 208 */ 209 return (pmonitor && pmonitor->m_pid > 0); 210 } 211 212 /* 213 * Signal handler for the alarm after the login grace period has expired. 214 * As usual, this may only take signal-safe actions, even though it is 215 * terminal. 216 */ 217 static void 218 grace_alarm_handler(int sig) 219 { 220 BLACKLIST_NOTIFY(the_active_state, BLACKLIST_AUTH_FAIL, 221 "Grace period expired"); 222 /* 223 * Try to kill any processes that we have spawned, E.g. authorized 224 * keys command helpers or privsep children. 225 */ 226 if (getpgid(0) == getpid()) { 227 struct sigaction sa; 228 229 /* mask all other signals while in handler */ 230 memset(&sa, 0, sizeof(sa)); 231 sa.sa_handler = SIG_IGN; 232 sigfillset(&sa.sa_mask); 233 #if defined(SA_RESTART) 234 sa.sa_flags = SA_RESTART; 235 #endif 236 (void)sigaction(SIGTERM, &sa, NULL); 237 kill(0, SIGTERM); 238 } 239 _exit(EXIT_LOGIN_GRACE); 240 } 241 242 /* Destroy the host and server keys. They will no longer be needed. */ 243 void 244 destroy_sensitive_data(void) 245 { 246 u_int i; 247 248 for (i = 0; i < options.num_host_key_files; i++) { 249 if (sensitive_data.host_keys[i]) { 250 sshkey_free(sensitive_data.host_keys[i]); 251 sensitive_data.host_keys[i] = NULL; 252 } 253 if (sensitive_data.host_certificates[i]) { 254 sshkey_free(sensitive_data.host_certificates[i]); 255 sensitive_data.host_certificates[i] = NULL; 256 } 257 } 258 } 259 260 /* Demote private to public keys for network child */ 261 void 262 demote_sensitive_data(void) 263 { 264 struct sshkey *tmp; 265 u_int i; 266 int r; 267 268 for (i = 0; i < options.num_host_key_files; i++) { 269 if (sensitive_data.host_keys[i]) { 270 if ((r = sshkey_from_private( 271 sensitive_data.host_keys[i], &tmp)) != 0) 272 fatal_r(r, "could not demote host %s key", 273 sshkey_type(sensitive_data.host_keys[i])); 274 sshkey_free(sensitive_data.host_keys[i]); 275 sensitive_data.host_keys[i] = tmp; 276 } 277 /* Certs do not need demotion */ 278 } 279 } 280 281 static void 282 reseed_prngs(void) 283 { 284 u_int32_t rnd[256]; 285 286 #ifdef WITH_OPENSSL 287 RAND_poll(); 288 #endif 289 arc4random_stir(); /* noop on recent arc4random() implementations */ 290 arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */ 291 292 #ifdef WITH_OPENSSL 293 RAND_seed(rnd, sizeof(rnd)); 294 /* give libcrypto a chance to notice the PID change */ 295 if ((RAND_bytes((u_char *)rnd, 1)) != 1) 296 fatal("%s: RAND_bytes failed", __func__); 297 #endif 298 299 explicit_bzero(rnd, sizeof(rnd)); 300 } 301 302 struct sshbuf * 303 pack_hostkeys(void) 304 { 305 struct sshbuf *keybuf = NULL, *hostkeys = NULL; 306 int r; 307 u_int i; 308 309 if ((hostkeys = sshbuf_new()) == NULL) 310 fatal_f("sshbuf_new failed"); 311 312 /* pack hostkeys into a string. Empty key slots get empty strings */ 313 for (i = 0; i < options.num_host_key_files; i++) { 314 /* public key */ 315 if (sensitive_data.host_pubkeys[i] != NULL) { 316 if ((r = sshkey_puts(sensitive_data.host_pubkeys[i], 317 hostkeys)) != 0) 318 fatal_fr(r, "compose hostkey public"); 319 } else { 320 if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0) 321 fatal_fr(r, "compose hostkey empty public"); 322 } 323 /* cert */ 324 if (sensitive_data.host_certificates[i] != NULL) { 325 if ((r = sshkey_puts( 326 sensitive_data.host_certificates[i], 327 hostkeys)) != 0) 328 fatal_fr(r, "compose host cert"); 329 } else { 330 if ((r = sshbuf_put_string(hostkeys, NULL, 0)) != 0) 331 fatal_fr(r, "compose host cert empty"); 332 } 333 } 334 335 sshbuf_free(keybuf); 336 return hostkeys; 337 } 338 339 static int 340 privsep_preauth(struct ssh *ssh) 341 { 342 int status, r; 343 pid_t pid; 344 345 /* Set up unprivileged child process to deal with network data */ 346 pmonitor = monitor_init(); 347 /* Store a pointer to the kex for later rekeying */ 348 pmonitor->m_pkex = &ssh->kex; 349 350 if ((pid = fork()) == -1) 351 fatal("fork of unprivileged child failed"); 352 else if (pid != 0) { 353 debug2("Network child is on pid %ld", (long)pid); 354 355 pmonitor->m_pid = pid; 356 if (have_agent) { 357 r = ssh_get_authentication_socket(&auth_sock); 358 if (r != 0) { 359 error_r(r, "Could not get agent socket"); 360 have_agent = 0; 361 } 362 } 363 monitor_child_preauth(ssh, pmonitor); 364 365 /* Wait for the child's exit status */ 366 while (waitpid(pid, &status, 0) == -1) { 367 if (errno == EINTR) 368 continue; 369 pmonitor->m_pid = -1; 370 fatal_f("waitpid: %s", strerror(errno)); 371 } 372 privsep_is_preauth = 0; 373 pmonitor->m_pid = -1; 374 if (WIFEXITED(status)) { 375 if (WEXITSTATUS(status) != 0) 376 fatal_f("preauth child exited with status %d", 377 WEXITSTATUS(status)); 378 } else if (WIFSIGNALED(status)) 379 fatal_f("preauth child terminated by signal %d", 380 WTERMSIG(status)); 381 return 1; 382 } else { 383 /* child */ 384 close(pmonitor->m_sendfd); 385 close(pmonitor->m_log_recvfd); 386 387 /* 388 * Arrange unpriv-preauth child process fds: 389 * 0, 1 network socket 390 * 2 optional stderr 391 * 3 reserved 392 * 4 monitor message socket 393 * 5 monitor logging socket 394 * 395 * We know that the monitor sockets will have fds > 4 because 396 * of the reserved fds in main() 397 */ 398 399 if (ssh_packet_get_connection_in(ssh) != STDIN_FILENO && 400 dup2(ssh_packet_get_connection_in(ssh), STDIN_FILENO) == -1) 401 fatal("dup2 stdin failed: %s", strerror(errno)); 402 if (ssh_packet_get_connection_out(ssh) != STDOUT_FILENO && 403 dup2(ssh_packet_get_connection_out(ssh), 404 STDOUT_FILENO) == -1) 405 fatal("dup2 stdout failed: %s", strerror(errno)); 406 /* leave stderr as-is */ 407 log_redirect_stderr_to(NULL); /* dup can clobber log fd */ 408 if (pmonitor->m_recvfd != PRIVSEP_MONITOR_FD && 409 dup2(pmonitor->m_recvfd, PRIVSEP_MONITOR_FD) == -1) 410 fatal("dup2 monitor fd: %s", strerror(errno)); 411 if (pmonitor->m_log_sendfd != PRIVSEP_LOG_FD && 412 dup2(pmonitor->m_log_sendfd, PRIVSEP_LOG_FD) == -1) 413 fatal("dup2 log fd: %s", strerror(errno)); 414 closefrom(PRIVSEP_MIN_FREE_FD); 415 416 saved_argv[0] = options.sshd_auth_path; 417 execv(options.sshd_auth_path, saved_argv); 418 419 fatal_f("exec of %s failed: %s", 420 options.sshd_auth_path, strerror(errno)); 421 } 422 } 423 424 static void 425 privsep_postauth(struct ssh *ssh, Authctxt *authctxt) 426 { 427 int skip_privdrop = 0; 428 429 /* 430 * Hack for systems that don't support FD passing: retain privileges 431 * in the post-auth privsep process so it can allocate PTYs directly. 432 * This is basically equivalent to what we did <= 9.7, which was to 433 * disable post-auth privsep entriely. 434 * Cygwin doesn't need to drop privs here although it doesn't support 435 * fd passing, as AFAIK PTY allocation on this platform doesn't require 436 * special privileges to begin with. 437 */ 438 #if defined(DISABLE_FD_PASSING) && !defined(HAVE_CYGWIN) 439 skip_privdrop = 1; 440 #endif 441 442 /* New socket pair */ 443 monitor_reinit(pmonitor); 444 445 pmonitor->m_pid = fork(); 446 if (pmonitor->m_pid == -1) 447 fatal("fork of unprivileged child failed"); 448 else if (pmonitor->m_pid != 0) { 449 verbose("User child is on pid %ld", (long)pmonitor->m_pid); 450 sshbuf_reset(loginmsg); 451 monitor_clear_keystate(ssh, pmonitor); 452 monitor_child_postauth(ssh, pmonitor); 453 454 /* NEVERREACHED */ 455 exit(0); 456 } 457 458 /* child */ 459 460 close(pmonitor->m_sendfd); 461 pmonitor->m_sendfd = -1; 462 463 /* Demote the private keys to public keys. */ 464 demote_sensitive_data(); 465 466 reseed_prngs(); 467 468 /* Drop privileges */ 469 if (!skip_privdrop) 470 do_setusercontext(authctxt->pw); 471 472 /* It is safe now to apply the key state */ 473 monitor_apply_keystate(ssh, pmonitor); 474 475 /* 476 * Tell the packet layer that authentication was successful, since 477 * this information is not part of the key state. 478 */ 479 ssh_packet_set_authenticated(ssh); 480 } 481 482 static struct sshkey * 483 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh) 484 { 485 u_int i; 486 struct sshkey *key; 487 488 for (i = 0; i < options.num_host_key_files; i++) { 489 switch (type) { 490 case KEY_RSA_CERT: 491 case KEY_DSA_CERT: 492 case KEY_ECDSA_CERT: 493 case KEY_ED25519_CERT: 494 case KEY_ECDSA_SK_CERT: 495 case KEY_ED25519_SK_CERT: 496 case KEY_XMSS_CERT: 497 key = sensitive_data.host_certificates[i]; 498 break; 499 default: 500 key = sensitive_data.host_keys[i]; 501 if (key == NULL && !need_private) 502 key = sensitive_data.host_pubkeys[i]; 503 break; 504 } 505 if (key == NULL || key->type != type) 506 continue; 507 switch (type) { 508 case KEY_ECDSA: 509 case KEY_ECDSA_SK: 510 case KEY_ECDSA_CERT: 511 case KEY_ECDSA_SK_CERT: 512 if (key->ecdsa_nid != nid) 513 continue; 514 /* FALLTHROUGH */ 515 default: 516 return need_private ? 517 sensitive_data.host_keys[i] : key; 518 } 519 } 520 return NULL; 521 } 522 523 struct sshkey * 524 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh) 525 { 526 return get_hostkey_by_type(type, nid, 0, ssh); 527 } 528 529 struct sshkey * 530 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh) 531 { 532 return get_hostkey_by_type(type, nid, 1, ssh); 533 } 534 535 struct sshkey * 536 get_hostkey_by_index(int ind) 537 { 538 if (ind < 0 || (u_int)ind >= options.num_host_key_files) 539 return (NULL); 540 return (sensitive_data.host_keys[ind]); 541 } 542 543 struct sshkey * 544 get_hostkey_public_by_index(int ind, struct ssh *ssh) 545 { 546 if (ind < 0 || (u_int)ind >= options.num_host_key_files) 547 return (NULL); 548 return (sensitive_data.host_pubkeys[ind]); 549 } 550 551 int 552 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh) 553 { 554 u_int i; 555 556 for (i = 0; i < options.num_host_key_files; i++) { 557 if (sshkey_is_cert(key)) { 558 if (key == sensitive_data.host_certificates[i] || 559 (compare && sensitive_data.host_certificates[i] && 560 sshkey_equal(key, 561 sensitive_data.host_certificates[i]))) 562 return (i); 563 } else { 564 if (key == sensitive_data.host_keys[i] || 565 (compare && sensitive_data.host_keys[i] && 566 sshkey_equal(key, sensitive_data.host_keys[i]))) 567 return (i); 568 if (key == sensitive_data.host_pubkeys[i] || 569 (compare && sensitive_data.host_pubkeys[i] && 570 sshkey_equal(key, sensitive_data.host_pubkeys[i]))) 571 return (i); 572 } 573 } 574 return (-1); 575 } 576 577 /* Inform the client of all hostkeys */ 578 static void 579 notify_hostkeys(struct ssh *ssh) 580 { 581 struct sshbuf *buf; 582 struct sshkey *key; 583 u_int i, nkeys; 584 int r; 585 char *fp; 586 587 /* Some clients cannot cope with the hostkeys message, skip those. */ 588 if (ssh->compat & SSH_BUG_HOSTKEYS) 589 return; 590 591 if ((buf = sshbuf_new()) == NULL) 592 fatal_f("sshbuf_new"); 593 for (i = nkeys = 0; i < options.num_host_key_files; i++) { 594 key = get_hostkey_public_by_index(i, ssh); 595 if (key == NULL || key->type == KEY_UNSPEC || 596 sshkey_is_cert(key)) 597 continue; 598 fp = sshkey_fingerprint(key, options.fingerprint_hash, 599 SSH_FP_DEFAULT); 600 debug3_f("key %d: %s %s", i, sshkey_ssh_name(key), fp); 601 free(fp); 602 if (nkeys == 0) { 603 /* 604 * Start building the request when we find the 605 * first usable key. 606 */ 607 if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 || 608 (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 || 609 (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */ 610 sshpkt_fatal(ssh, r, "%s: start request", __func__); 611 } 612 /* Append the key to the request */ 613 sshbuf_reset(buf); 614 if ((r = sshkey_putb(key, buf)) != 0) 615 fatal_fr(r, "couldn't put hostkey %d", i); 616 if ((r = sshpkt_put_stringb(ssh, buf)) != 0) 617 sshpkt_fatal(ssh, r, "%s: append key", __func__); 618 nkeys++; 619 } 620 debug3_f("sent %u hostkeys", nkeys); 621 if (nkeys == 0) 622 fatal_f("no hostkeys"); 623 if ((r = sshpkt_send(ssh)) != 0) 624 sshpkt_fatal(ssh, r, "%s: send", __func__); 625 sshbuf_free(buf); 626 } 627 628 static void 629 usage(void) 630 { 631 fprintf(stderr, "%s, %s\n", SSH_RELEASE, SSH_OPENSSL_VERSION); 632 fprintf(stderr, 633 "usage: sshd [-46DdeGiqTtV] [-C connection_spec] [-c host_cert_file]\n" 634 " [-E log_file] [-f config_file] [-g login_grace_time]\n" 635 " [-h host_key_file] [-o option] [-p port] [-u len]\n" 636 ); 637 exit(1); 638 } 639 640 static void 641 parse_hostkeys(struct sshbuf *hostkeys) 642 { 643 int r; 644 u_int num_keys = 0; 645 struct sshkey *k; 646 struct sshbuf *kbuf; 647 const u_char *cp; 648 size_t len; 649 650 while (sshbuf_len(hostkeys) != 0) { 651 if (num_keys > 2048) 652 fatal_f("too many hostkeys"); 653 sensitive_data.host_keys = xrecallocarray( 654 sensitive_data.host_keys, num_keys, num_keys + 1, 655 sizeof(*sensitive_data.host_pubkeys)); 656 sensitive_data.host_pubkeys = xrecallocarray( 657 sensitive_data.host_pubkeys, num_keys, num_keys + 1, 658 sizeof(*sensitive_data.host_pubkeys)); 659 sensitive_data.host_certificates = xrecallocarray( 660 sensitive_data.host_certificates, num_keys, num_keys + 1, 661 sizeof(*sensitive_data.host_certificates)); 662 /* private key */ 663 k = NULL; 664 if ((r = sshbuf_froms(hostkeys, &kbuf)) != 0) 665 fatal_fr(r, "extract privkey"); 666 if (sshbuf_len(kbuf) != 0 && 667 (r = sshkey_private_deserialize(kbuf, &k)) != 0) 668 fatal_fr(r, "parse pubkey"); 669 sensitive_data.host_keys[num_keys] = k; 670 sshbuf_free(kbuf); 671 if (k) 672 debug2_f("privkey %u: %s", num_keys, sshkey_ssh_name(k)); 673 /* public key */ 674 k = NULL; 675 if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0) 676 fatal_fr(r, "extract pubkey"); 677 if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0) 678 fatal_fr(r, "parse pubkey"); 679 sensitive_data.host_pubkeys[num_keys] = k; 680 if (k) 681 debug2_f("pubkey %u: %s", num_keys, sshkey_ssh_name(k)); 682 /* certificate */ 683 k = NULL; 684 if ((r = sshbuf_get_string_direct(hostkeys, &cp, &len)) != 0) 685 fatal_fr(r, "extract pubkey"); 686 if (len != 0 && (r = sshkey_from_blob(cp, len, &k)) != 0) 687 fatal_fr(r, "parse pubkey"); 688 sensitive_data.host_certificates[num_keys] = k; 689 if (k) 690 debug2_f("cert %u: %s", num_keys, sshkey_ssh_name(k)); 691 num_keys++; 692 } 693 sensitive_data.num_hostkeys = num_keys; 694 } 695 696 static void 697 recv_rexec_state(int fd, struct sshbuf *conf, uint64_t *timing_secretp) 698 { 699 struct sshbuf *m, *inc, *hostkeys; 700 u_char *cp, ver; 701 size_t len; 702 int r; 703 struct include_item *item; 704 705 debug3_f("entering fd = %d", fd); 706 707 if ((m = sshbuf_new()) == NULL || (inc = sshbuf_new()) == NULL) 708 fatal_f("sshbuf_new failed"); 709 710 /* receive config */ 711 if (ssh_msg_recv(fd, m) == -1) 712 fatal_f("ssh_msg_recv failed"); 713 if ((r = sshbuf_get_u8(m, &ver)) != 0) 714 fatal_fr(r, "parse version"); 715 if (ver != 0) 716 fatal_f("rexec version mismatch"); 717 if ((r = sshbuf_get_string(m, &cp, &len)) != 0 || /* XXX _direct */ 718 (r = sshbuf_get_u64(m, timing_secretp)) != 0 || 719 (r = sshbuf_get_stringb(m, inc)) != 0) 720 fatal_fr(r, "parse config"); 721 722 if (conf != NULL && (r = sshbuf_put(conf, cp, len))) 723 fatal_fr(r, "sshbuf_put"); 724 725 while (sshbuf_len(inc) != 0) { 726 item = xcalloc(1, sizeof(*item)); 727 if ((item->contents = sshbuf_new()) == NULL) 728 fatal_f("sshbuf_new failed"); 729 if ((r = sshbuf_get_cstring(inc, &item->selector, NULL)) != 0 || 730 (r = sshbuf_get_cstring(inc, &item->filename, NULL)) != 0 || 731 (r = sshbuf_get_stringb(inc, item->contents)) != 0) 732 fatal_fr(r, "parse includes"); 733 TAILQ_INSERT_TAIL(&includes, item, entry); 734 } 735 736 /* receive hostkeys */ 737 sshbuf_reset(m); 738 if (ssh_msg_recv(fd, m) == -1) 739 fatal_f("ssh_msg_recv failed"); 740 if ((r = sshbuf_get_u8(m, NULL)) != 0 || 741 (r = sshbuf_froms(m, &hostkeys)) != 0) 742 fatal_fr(r, "parse config"); 743 parse_hostkeys(hostkeys); 744 745 free(cp); 746 sshbuf_free(m); 747 sshbuf_free(hostkeys); 748 sshbuf_free(inc); 749 750 debug3_f("done"); 751 } 752 753 /* 754 * If IP options are supported, make sure there are none (log and 755 * return an error if any are found). Basically we are worried about 756 * source routing; it can be used to pretend you are somebody 757 * (ip-address) you are not. That itself may be "almost acceptable" 758 * under certain circumstances, but rhosts authentication is useless 759 * if source routing is accepted. Notice also that if we just dropped 760 * source routing here, the other side could use IP spoofing to do 761 * rest of the interaction and could still bypass security. So we 762 * exit here if we detect any IP options. 763 */ 764 static void 765 check_ip_options(struct ssh *ssh) 766 { 767 #ifdef IP_OPTIONS 768 int sock_in = ssh_packet_get_connection_in(ssh); 769 struct sockaddr_storage from; 770 u_char opts[200]; 771 socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from); 772 char text[sizeof(opts) * 3 + 1]; 773 774 memset(&from, 0, sizeof(from)); 775 if (getpeername(sock_in, (struct sockaddr *)&from, 776 &fromlen) == -1) 777 return; 778 if (from.ss_family != AF_INET) 779 return; 780 /* XXX IPv6 options? */ 781 782 if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts, 783 &option_size) >= 0 && option_size != 0) { 784 text[0] = '\0'; 785 for (i = 0; i < option_size; i++) 786 snprintf(text + i*3, sizeof(text) - i*3, 787 " %2.2x", opts[i]); 788 fatal("Connection from %.100s port %d with IP opts: %.800s", 789 ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text); 790 } 791 #endif /* IP_OPTIONS */ 792 } 793 794 /* Set the routing domain for this process */ 795 static void 796 set_process_rdomain(struct ssh *ssh, const char *name) 797 { 798 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN) 799 if (name == NULL) 800 return; /* default */ 801 802 if (strcmp(name, "%D") == 0) { 803 /* "expands" to routing domain of connection */ 804 if ((name = ssh_packet_rdomain_in(ssh)) == NULL) 805 return; 806 } 807 /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */ 808 return sys_set_process_rdomain(name); 809 #elif defined(__OpenBSD__) 810 int rtable, ortable = getrtable(); 811 const char *errstr; 812 813 if (name == NULL) 814 return; /* default */ 815 816 if (strcmp(name, "%D") == 0) { 817 /* "expands" to routing domain of connection */ 818 if ((name = ssh_packet_rdomain_in(ssh)) == NULL) 819 return; 820 } 821 822 rtable = (int)strtonum(name, 0, 255, &errstr); 823 if (errstr != NULL) /* Shouldn't happen */ 824 fatal("Invalid routing domain \"%s\": %s", name, errstr); 825 if (rtable != ortable && setrtable(rtable) != 0) 826 fatal("Unable to set routing domain %d: %s", 827 rtable, strerror(errno)); 828 debug_f("set routing domain %d (was %d)", rtable, ortable); 829 #else /* defined(__OpenBSD__) */ 830 fatal("Unable to set routing domain: not supported in this platform"); 831 #endif 832 } 833 834 /* 835 * Main program for the daemon. 836 */ 837 int 838 main(int ac, char **av) 839 { 840 struct ssh *ssh = NULL; 841 extern char *optarg; 842 extern int optind; 843 int devnull, r, opt, on = 1, remote_port; 844 int sock_in = -1, sock_out = -1, rexeced_flag = 0, have_key = 0; 845 const char *remote_ip, *rdomain; 846 char *line, *laddr, *logfile = NULL; 847 u_int i; 848 u_int64_t ibytes, obytes; 849 mode_t new_umask; 850 Authctxt *authctxt; 851 struct connection_info *connection_info = NULL; 852 sigset_t sigmask; 853 uint64_t timing_secret = 0; 854 struct itimerval itv; 855 856 sigemptyset(&sigmask); 857 sigprocmask(SIG_SETMASK, &sigmask, NULL); 858 859 #ifdef HAVE_SECUREWARE 860 (void)set_auth_parameters(ac, av); 861 #endif 862 __progname = ssh_get_progname(av[0]); 863 864 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */ 865 saved_argc = ac; 866 saved_argv = xcalloc(ac + 1, sizeof(*saved_argv)); 867 for (i = 0; (int)i < ac; i++) 868 saved_argv[i] = xstrdup(av[i]); 869 saved_argv[i] = NULL; 870 871 #ifndef HAVE_SETPROCTITLE 872 /* Prepare for later setproctitle emulation */ 873 compat_init_setproctitle(ac, av); 874 av = saved_argv; 875 #endif 876 877 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 878 sanitise_stdfd(); 879 880 /* Initialize configuration options to their default values. */ 881 initialize_server_options(&options); 882 883 /* Parse command-line arguments. */ 884 while ((opt = getopt(ac, av, 885 "C:E:b:c:f:g:h:k:o:p:u:46DGQRTdeiqrtV")) != -1) { 886 switch (opt) { 887 case '4': 888 options.address_family = AF_INET; 889 break; 890 case '6': 891 options.address_family = AF_INET6; 892 break; 893 case 'f': 894 config_file_name = optarg; 895 break; 896 case 'c': 897 servconf_add_hostcert("[command-line]", 0, 898 &options, optarg); 899 break; 900 case 'd': 901 if (debug_flag == 0) { 902 debug_flag = 1; 903 options.log_level = SYSLOG_LEVEL_DEBUG1; 904 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) 905 options.log_level++; 906 break; 907 case 'D': 908 /* ignore */ 909 break; 910 case 'E': 911 logfile = optarg; 912 /* FALLTHROUGH */ 913 case 'e': 914 log_stderr = 1; 915 break; 916 case 'i': 917 inetd_flag = 1; 918 break; 919 case 'r': 920 /* ignore */ 921 break; 922 case 'R': 923 rexeced_flag = 1; 924 break; 925 case 'Q': 926 /* ignored */ 927 break; 928 case 'q': 929 options.log_level = SYSLOG_LEVEL_QUIET; 930 break; 931 case 'b': 932 /* protocol 1, ignored */ 933 break; 934 case 'p': 935 options.ports_from_cmdline = 1; 936 if (options.num_ports >= MAX_PORTS) { 937 fprintf(stderr, "too many ports.\n"); 938 exit(1); 939 } 940 options.ports[options.num_ports++] = a2port(optarg); 941 if (options.ports[options.num_ports-1] <= 0) { 942 fprintf(stderr, "Bad port number.\n"); 943 exit(1); 944 } 945 break; 946 case 'g': 947 if ((options.login_grace_time = convtime(optarg)) == -1) { 948 fprintf(stderr, "Invalid login grace time.\n"); 949 exit(1); 950 } 951 break; 952 case 'k': 953 /* protocol 1, ignored */ 954 break; 955 case 'h': 956 servconf_add_hostkey("[command-line]", 0, 957 &options, optarg, 1); 958 break; 959 case 't': 960 case 'T': 961 case 'G': 962 fatal("test/dump modes not supported"); 963 break; 964 case 'C': 965 connection_info = server_get_connection_info(ssh, 0, 0); 966 if (parse_server_match_testspec(connection_info, 967 optarg) == -1) 968 exit(1); 969 break; 970 case 'u': 971 utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL); 972 if (utmp_len > HOST_NAME_MAX+1) { 973 fprintf(stderr, "Invalid utmp length.\n"); 974 exit(1); 975 } 976 break; 977 case 'o': 978 line = xstrdup(optarg); 979 if (process_server_config_line(&options, line, 980 "command-line", 0, NULL, NULL, &includes) != 0) 981 exit(1); 982 free(line); 983 break; 984 case 'V': 985 fprintf(stderr, "%s, %s\n", 986 SSH_RELEASE, SSH_OPENSSL_VERSION); 987 exit(0); 988 default: 989 usage(); 990 break; 991 } 992 } 993 994 /* Check that there are no remaining arguments. */ 995 if (optind < ac) { 996 fprintf(stderr, "Extra argument %s.\n", av[optind]); 997 exit(1); 998 } 999 1000 if (!rexeced_flag) 1001 fatal("sshd-session should not be executed directly"); 1002 1003 closefrom(REEXEC_MIN_FREE_FD); 1004 1005 platform_pre_session_start(); 1006 1007 /* Reserve fds we'll need later for reexec things */ 1008 if ((devnull = open(_PATH_DEVNULL, O_RDWR)) == -1) 1009 fatal("open %s: %s", _PATH_DEVNULL, strerror(errno)); 1010 while (devnull < PRIVSEP_MIN_FREE_FD) { 1011 if ((devnull = dup(devnull)) == -1) 1012 fatal("dup %s: %s", _PATH_DEVNULL, strerror(errno)); 1013 } 1014 1015 seed_rng(); 1016 1017 /* If requested, redirect the logs to the specified logfile. */ 1018 if (logfile != NULL) { 1019 char *cp, pid_s[32]; 1020 1021 snprintf(pid_s, sizeof(pid_s), "%ld", (unsigned long)getpid()); 1022 cp = percent_expand(logfile, 1023 "p", pid_s, 1024 "P", "sshd-session", 1025 (char *)NULL); 1026 log_redirect_stderr_to(cp); 1027 free(cp); 1028 } 1029 1030 /* 1031 * Force logging to stderr until we have loaded the private host 1032 * key (unless started from inetd) 1033 */ 1034 log_init(__progname, 1035 options.log_level == SYSLOG_LEVEL_NOT_SET ? 1036 SYSLOG_LEVEL_INFO : options.log_level, 1037 options.log_facility == SYSLOG_FACILITY_NOT_SET ? 1038 SYSLOG_FACILITY_AUTH : options.log_facility, 1039 log_stderr || !inetd_flag || debug_flag); 1040 1041 /* Fetch our configuration */ 1042 if ((cfg = sshbuf_new()) == NULL) 1043 fatal("sshbuf_new config buf failed"); 1044 setproctitle("%s", "[rexeced]"); 1045 recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg, &timing_secret); 1046 parse_server_config(&options, "rexec", cfg, &includes, NULL, 1); 1047 /* Fill in default values for those options not explicitly set. */ 1048 fill_default_server_options(&options); 1049 options.timing_secret = timing_secret; 1050 1051 /* Reinit logging in case config set Level, Facility or Verbose. */ 1052 log_init(__progname, options.log_level, options.log_facility, 1053 log_stderr || !inetd_flag || debug_flag); 1054 1055 debug("sshd-session version %s, %s", SSH_VERSION, SSH_OPENSSL_VERSION); 1056 1057 /* Store privilege separation user for later use if required. */ 1058 privsep_chroot = (getuid() == 0 || geteuid() == 0); 1059 if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) { 1060 if (privsep_chroot || options.kerberos_authentication) 1061 fatal("Privilege separation user %s does not exist", 1062 SSH_PRIVSEP_USER); 1063 } else { 1064 privsep_pw = pwcopy(privsep_pw); 1065 freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd)); 1066 privsep_pw->pw_passwd = xstrdup("*"); 1067 } 1068 endpwent(); 1069 1070 if (!debug_flag && !inetd_flag) { 1071 if ((startup_pipe = dup(REEXEC_CONFIG_PASS_FD)) == -1) 1072 fatal("internal error: no startup pipe"); 1073 1074 /* 1075 * Signal parent that this child is at a point where 1076 * they can go away if they have a SIGHUP pending. 1077 */ 1078 (void)atomicio(vwrite, startup_pipe, "\0", 1); 1079 } 1080 /* close the fd, but keep the slot reserved */ 1081 if (dup2(devnull, REEXEC_CONFIG_PASS_FD) == -1) 1082 fatal("dup2 devnull->config fd: %s", strerror(errno)); 1083 1084 /* Check that options are sensible */ 1085 if (options.authorized_keys_command_user == NULL && 1086 (options.authorized_keys_command != NULL && 1087 strcasecmp(options.authorized_keys_command, "none") != 0)) 1088 fatal("AuthorizedKeysCommand set without " 1089 "AuthorizedKeysCommandUser"); 1090 if (options.authorized_principals_command_user == NULL && 1091 (options.authorized_principals_command != NULL && 1092 strcasecmp(options.authorized_principals_command, "none") != 0)) 1093 fatal("AuthorizedPrincipalsCommand set without " 1094 "AuthorizedPrincipalsCommandUser"); 1095 1096 /* 1097 * Check whether there is any path through configured auth methods. 1098 * Unfortunately it is not possible to verify this generally before 1099 * daemonisation in the presence of Match block, but this catches 1100 * and warns for trivial misconfigurations that could break login. 1101 */ 1102 if (options.num_auth_methods != 0) { 1103 for (i = 0; i < options.num_auth_methods; i++) { 1104 if (auth2_methods_valid(options.auth_methods[i], 1105 1) == 0) 1106 break; 1107 } 1108 if (i >= options.num_auth_methods) 1109 fatal("AuthenticationMethods cannot be satisfied by " 1110 "enabled authentication methods"); 1111 } 1112 1113 #ifdef WITH_OPENSSL 1114 if (options.moduli_file != NULL) 1115 dh_set_moduli_file(options.moduli_file); 1116 #endif 1117 1118 if (options.host_key_agent) { 1119 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME)) 1120 setenv(SSH_AUTHSOCKET_ENV_NAME, 1121 options.host_key_agent, 1); 1122 if ((r = ssh_get_authentication_socket(NULL)) == 0) 1123 have_agent = 1; 1124 else 1125 error_r(r, "Could not connect to agent \"%s\"", 1126 options.host_key_agent); 1127 } 1128 1129 if (options.num_host_key_files != sensitive_data.num_hostkeys) { 1130 fatal("internal error: hostkeys confused (config %u recvd %u)", 1131 options.num_host_key_files, sensitive_data.num_hostkeys); 1132 } 1133 1134 for (i = 0; i < options.num_host_key_files; i++) { 1135 if (sensitive_data.host_keys[i] != NULL || 1136 (have_agent && sensitive_data.host_pubkeys[i] != NULL)) { 1137 have_key = 1; 1138 break; 1139 } 1140 } 1141 if (!have_key) 1142 fatal("internal error: monitor received no hostkeys"); 1143 1144 /* Ensure that umask disallows at least group and world write */ 1145 new_umask = umask(0077) | 0022; 1146 (void) umask(new_umask); 1147 1148 /* Initialize the log (it is reinitialized below in case we forked). */ 1149 if (debug_flag) 1150 log_stderr = 1; 1151 log_init(__progname, options.log_level, 1152 options.log_facility, log_stderr); 1153 for (i = 0; i < options.num_log_verbose; i++) 1154 log_verbose_add(options.log_verbose[i]); 1155 1156 /* Reinitialize the log (because of the fork above). */ 1157 log_init(__progname, options.log_level, options.log_facility, log_stderr); 1158 1159 /* 1160 * Chdir to the root directory so that the current disk can be 1161 * unmounted if desired. 1162 */ 1163 if (chdir("/") == -1) 1164 error("chdir(\"/\"): %s", strerror(errno)); 1165 1166 /* ignore SIGPIPE */ 1167 ssh_signal(SIGPIPE, SIG_IGN); 1168 1169 /* Get a connection, either from inetd or rexec */ 1170 if (inetd_flag) { 1171 /* 1172 * NB. must be different fd numbers for the !socket case, 1173 * as packet_connection_is_on_socket() depends on this. 1174 */ 1175 sock_in = dup(STDIN_FILENO); 1176 sock_out = dup(STDOUT_FILENO); 1177 } else { 1178 /* rexec case; accept()ed socket in ancestor listener */ 1179 sock_in = sock_out = dup(STDIN_FILENO); 1180 } 1181 1182 /* 1183 * We intentionally do not close the descriptors 0, 1, and 2 1184 * as our code for setting the descriptors won't work if 1185 * ttyfd happens to be one of those. 1186 */ 1187 if (stdfd_devnull(1, 1, !log_stderr) == -1) 1188 error("stdfd_devnull failed"); 1189 debug("network sockets: %d, %d", sock_in, sock_out); 1190 1191 /* This is the child processing a new connection. */ 1192 setproctitle("%s", "[accepted]"); 1193 1194 /* Executed child processes don't need these. */ 1195 fcntl(sock_out, F_SETFD, FD_CLOEXEC); 1196 fcntl(sock_in, F_SETFD, FD_CLOEXEC); 1197 1198 /* We will not restart on SIGHUP since it no longer makes sense. */ 1199 ssh_signal(SIGALRM, SIG_DFL); 1200 ssh_signal(SIGHUP, SIG_DFL); 1201 ssh_signal(SIGTERM, SIG_DFL); 1202 ssh_signal(SIGQUIT, SIG_DFL); 1203 ssh_signal(SIGCHLD, SIG_DFL); 1204 ssh_signal(SIGINT, SIG_DFL); 1205 1206 BLACKLIST_INIT(); 1207 1208 /* 1209 * Register our connection. This turns encryption off because we do 1210 * not have a key. 1211 */ 1212 if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL) 1213 fatal("Unable to create connection"); 1214 the_active_state = ssh; 1215 ssh_packet_set_server(ssh); 1216 1217 check_ip_options(ssh); 1218 1219 /* Prepare the channels layer */ 1220 channel_init_channels(ssh); 1221 channel_set_af(ssh, options.address_family); 1222 server_process_channel_timeouts(ssh); 1223 server_process_permitopen(ssh); 1224 1225 /* Set SO_KEEPALIVE if requested. */ 1226 if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) && 1227 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) == -1) 1228 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno)); 1229 1230 if ((remote_port = ssh_remote_port(ssh)) < 0) { 1231 debug("ssh_remote_port failed"); 1232 cleanup_exit(255); 1233 } 1234 1235 #ifdef HAVE_LOGIN_CAP 1236 /* Also caches remote hostname for sandboxed child. */ 1237 auth_get_canonical_hostname(ssh, options.use_dns); 1238 #endif 1239 1240 /* 1241 * The rest of the code depends on the fact that 1242 * ssh_remote_ipaddr() caches the remote ip, even if 1243 * the socket goes away. 1244 */ 1245 remote_ip = ssh_remote_ipaddr(ssh); 1246 1247 #ifdef SSH_AUDIT_EVENTS 1248 audit_connection_from(remote_ip, remote_port); 1249 #endif 1250 1251 rdomain = ssh_packet_rdomain_in(ssh); 1252 1253 /* Log the connection. */ 1254 laddr = get_local_ipaddr(sock_in); 1255 verbose("Connection from %s port %d on %s port %d%s%s%s", 1256 remote_ip, remote_port, laddr, ssh_local_port(ssh), 1257 rdomain == NULL ? "" : " rdomain \"", 1258 rdomain == NULL ? "" : rdomain, 1259 rdomain == NULL ? "" : "\""); 1260 free(laddr); 1261 1262 /* 1263 * We don't want to listen forever unless the other side 1264 * successfully authenticates itself. So we set up an alarm which is 1265 * cleared after successful authentication. A limit of zero 1266 * indicates no limit. Note that we don't set the alarm in debugging 1267 * mode; it is just annoying to have the server exit just when you 1268 * are about to discover the bug. 1269 */ 1270 ssh_signal(SIGALRM, grace_alarm_handler); 1271 if (!debug_flag && options.login_grace_time > 0) { 1272 int ujitter = arc4random_uniform(4 * 1000000); 1273 1274 timerclear(&itv.it_interval); 1275 itv.it_value.tv_sec = options.login_grace_time; 1276 itv.it_value.tv_sec += ujitter / 1000000; 1277 itv.it_value.tv_usec = ujitter % 1000000; 1278 1279 if (setitimer(ITIMER_REAL, &itv, NULL) == -1) 1280 fatal("login grace time setitimer failed"); 1281 } 1282 1283 if ((r = kex_exchange_identification(ssh, -1, 1284 options.version_addendum)) != 0) { 1285 BLACKLIST_NOTIFY(ssh, BLACKLIST_AUTH_FAIL, "Banner exchange"); 1286 sshpkt_fatal(ssh, r, "banner exchange"); 1287 } 1288 1289 ssh_packet_set_nonblocking(ssh); 1290 1291 /* allocate authentication context */ 1292 authctxt = xcalloc(1, sizeof(*authctxt)); 1293 ssh->authctxt = authctxt; 1294 1295 /* XXX global for cleanup, access from other modules */ 1296 the_authctxt = authctxt; 1297 1298 /* Set default key authentication options */ 1299 if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL) 1300 fatal("allocation failed"); 1301 1302 /* prepare buffer to collect messages to display to user after login */ 1303 if ((loginmsg = sshbuf_new()) == NULL) 1304 fatal("sshbuf_new loginmsg failed"); 1305 auth_debug_reset(); 1306 1307 if (privsep_preauth(ssh) != 1) 1308 fatal("privsep_preauth failed"); 1309 1310 /* Now user is authenticated */ 1311 1312 /* 1313 * Cancel the alarm we set to limit the time taken for 1314 * authentication. 1315 */ 1316 timerclear(&itv.it_interval); 1317 timerclear(&itv.it_value); 1318 if (setitimer(ITIMER_REAL, &itv, NULL) == -1) 1319 fatal("login grace time clear failed"); 1320 ssh_signal(SIGALRM, SIG_DFL); 1321 authctxt->authenticated = 1; 1322 if (startup_pipe != -1) { 1323 /* signal listener that authentication completed successfully */ 1324 (void)atomicio(vwrite, startup_pipe, "\001", 1); 1325 close(startup_pipe); 1326 startup_pipe = -1; 1327 } 1328 1329 if (options.routing_domain != NULL) 1330 set_process_rdomain(ssh, options.routing_domain); 1331 1332 #ifdef SSH_AUDIT_EVENTS 1333 audit_event(ssh, SSH_AUTH_SUCCESS); 1334 #endif 1335 1336 #ifdef GSSAPI 1337 if (options.gss_authentication) { 1338 temporarily_use_uid(authctxt->pw); 1339 ssh_gssapi_storecreds(); 1340 restore_uid(); 1341 } 1342 #endif 1343 #ifdef USE_PAM 1344 if (options.use_pam) { 1345 do_pam_setcred(); 1346 do_pam_session(ssh); 1347 } 1348 #endif 1349 1350 /* 1351 * In privilege separation, we fork another child and prepare 1352 * file descriptor passing. 1353 */ 1354 privsep_postauth(ssh, authctxt); 1355 /* the monitor process [priv] will not return */ 1356 1357 ssh_packet_set_timeout(ssh, options.client_alive_interval, 1358 options.client_alive_count_max); 1359 1360 /* Try to send all our hostkeys to the client */ 1361 notify_hostkeys(ssh); 1362 1363 /* Start session. */ 1364 do_authenticated(ssh, authctxt); 1365 1366 /* The connection has been terminated. */ 1367 ssh_packet_get_bytes(ssh, &ibytes, &obytes); 1368 verbose("Transferred: sent %llu, received %llu bytes", 1369 (unsigned long long)obytes, (unsigned long long)ibytes); 1370 1371 verbose("Closing connection to %.500s port %d", remote_ip, remote_port); 1372 1373 #ifdef USE_PAM 1374 if (options.use_pam) 1375 finish_pam(); 1376 #endif /* USE_PAM */ 1377 1378 #ifdef SSH_AUDIT_EVENTS 1379 mm_audit_event(ssh, SSH_CONNECTION_CLOSE); 1380 #endif 1381 1382 ssh_packet_close(ssh); 1383 1384 mm_terminate(); 1385 1386 exit(0); 1387 } 1388 1389 int 1390 sshd_hostkey_sign(struct ssh *ssh, struct sshkey *privkey, 1391 struct sshkey *pubkey, u_char **signature, size_t *slenp, 1392 const u_char *data, size_t dlen, const char *alg) 1393 { 1394 if (privkey) { 1395 if (mm_sshkey_sign(ssh, privkey, signature, slenp, 1396 data, dlen, alg, options.sk_provider, NULL, 1397 ssh->compat) < 0) 1398 fatal_f("privkey sign failed"); 1399 } else { 1400 if (mm_sshkey_sign(ssh, pubkey, signature, slenp, 1401 data, dlen, alg, options.sk_provider, NULL, 1402 ssh->compat) < 0) 1403 fatal_f("pubkey sign failed"); 1404 } 1405 return 0; 1406 } 1407 1408 /* server specific fatal cleanup */ 1409 void 1410 cleanup_exit(int i) 1411 { 1412 extern int auth_attempted; /* monitor.c */ 1413 1414 if (the_active_state != NULL && the_authctxt != NULL) { 1415 do_cleanup(the_active_state, the_authctxt); 1416 if (privsep_is_preauth && 1417 pmonitor != NULL && pmonitor->m_pid > 1) { 1418 debug("Killing privsep child %d", pmonitor->m_pid); 1419 if (kill(pmonitor->m_pid, SIGKILL) != 0 && 1420 errno != ESRCH) { 1421 error_f("kill(%d): %s", pmonitor->m_pid, 1422 strerror(errno)); 1423 } 1424 } 1425 } 1426 #ifdef SSH_AUDIT_EVENTS 1427 /* done after do_cleanup so it can cancel the PAM auth 'thread' */ 1428 if (the_active_state != NULL && mm_is_monitor()) 1429 audit_event(the_active_state, SSH_CONNECTION_ABANDON); 1430 #endif 1431 /* Override default fatal exit value when auth was attempted */ 1432 if (i == 255 && auth_attempted) { 1433 BLACKLIST_NOTIFY(the_active_state, BLACKLIST_AUTH_FAIL, 1434 "Fatal exit"); 1435 _exit(EXIT_AUTH_ATTEMPTED); 1436 } 1437 _exit(i); 1438 } 1439