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