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