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