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