Annotation of src/usr.bin/ssh/sshd.c, Revision 1.525
1.525 ! djm 1: /* $OpenBSD: sshd.c,v 1.524 2019/01/19 21:38:24 djm Exp $ */
1.86 markus 2: /*
1.65 deraadt 3: * Author: Tatu Ylonen <ylo@cs.hut.fi>
4: * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5: * All rights reserved
1.126 deraadt 6: * This program is the ssh daemon. It listens for connections from clients,
7: * and performs authentication, executes use commands or shell, and forwards
1.65 deraadt 8: * information to/from the application to the user client over an encrypted
1.126 deraadt 9: * connection. This can also handle forwarding of X11, TCP/IP, and
10: * authentication agent connections.
1.98 markus 11: *
1.126 deraadt 12: * As far as I am concerned, the code I have written for this software
13: * can be used freely for any purpose. Any derived versions of this
14: * software must be clearly marked as such, and if the derived work is
15: * incompatible with the protocol description in the RFC file, it must be
16: * called by a name other than "ssh" or "Secure Shell".
17: *
18: * SSH2 implementation:
1.231 provos 19: * Privilege Separation:
1.126 deraadt 20: *
1.231 provos 21: * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22: * Copyright (c) 2002 Niels Provos. All rights reserved.
1.126 deraadt 23: *
24: * Redistribution and use in source and binary forms, with or without
25: * modification, are permitted provided that the following conditions
26: * are met:
27: * 1. Redistributions of source code must retain the above copyright
28: * notice, this list of conditions and the following disclaimer.
29: * 2. Redistributions in binary form must reproduce the above copyright
30: * notice, this list of conditions and the following disclaimer in the
31: * documentation and/or other materials provided with the distribution.
32: *
33: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.65 deraadt 43: */
1.1 deraadt 44:
1.343 deraadt 45: #include <sys/types.h>
1.320 stevesk 46: #include <sys/ioctl.h>
1.321 stevesk 47: #include <sys/wait.h>
1.343 deraadt 48: #include <sys/tree.h>
1.323 stevesk 49: #include <sys/stat.h>
1.334 stevesk 50: #include <sys/socket.h>
1.340 stevesk 51: #include <sys/time.h>
1.357 djm 52: #include <sys/queue.h>
1.319 stevesk 53:
1.336 stevesk 54: #include <errno.h>
1.335 stevesk 55: #include <fcntl.h>
1.338 stevesk 56: #include <netdb.h>
1.319 stevesk 57: #include <paths.h>
1.333 stevesk 58: #include <pwd.h>
1.322 stevesk 59: #include <signal.h>
1.342 stevesk 60: #include <stdio.h>
1.341 stevesk 61: #include <stdlib.h>
1.339 stevesk 62: #include <string.h>
1.344 dtucker 63: #include <unistd.h>
1.438 deraadt 64: #include <limits.h>
1.1 deraadt 65:
1.426 markus 66: #ifdef WITH_OPENSSL
1.155 markus 67: #include <openssl/bn.h>
1.426 markus 68: #endif
1.155 markus 69:
1.343 deraadt 70: #include "xmalloc.h"
1.155 markus 71: #include "ssh.h"
72: #include "ssh2.h"
1.171 djm 73: #include "sshpty.h"
1.1 deraadt 74: #include "packet.h"
1.155 markus 75: #include "log.h"
1.511 markus 76: #include "sshbuf.h"
1.428 millert 77: #include "misc.h"
1.454 markus 78: #include "match.h"
1.1 deraadt 79: #include "servconf.h"
80: #include "uidswap.h"
1.33 markus 81: #include "compat.h"
1.155 markus 82: #include "cipher.h"
1.415 markus 83: #include "digest.h"
1.512 markus 84: #include "sshkey.h"
1.98 markus 85: #include "kex.h"
86: #include "myproposal.h"
1.108 markus 87: #include "authfile.h"
1.154 markus 88: #include "pathnames.h"
1.155 markus 89: #include "atomicio.h"
90: #include "canohost.h"
1.343 deraadt 91: #include "hostfile.h"
1.155 markus 92: #include "auth.h"
1.404 markus 93: #include "authfd.h"
1.294 djm 94: #include "msg.h"
1.186 markus 95: #include "dispatch.h"
1.206 stevesk 96: #include "channels.h"
1.230 provos 97: #include "session.h"
1.231 provos 98: #include "monitor.h"
1.343 deraadt 99: #ifdef GSSAPI
100: #include "ssh-gss.h"
101: #endif
1.231 provos 102: #include "monitor_wrap.h"
1.385 djm 103: #include "ssh-sandbox.h"
1.506 djm 104: #include "auth-options.h"
1.332 stevesk 105: #include "version.h"
1.432 djm 106: #include "ssherr.h"
1.522 djm 107:
108: extern struct ssh *active_state; /* XXX move decl to this file */
1.1 deraadt 109:
1.296 djm 110: /* Re-exec fds */
111: #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
112: #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
113: #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
114: #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
115:
1.138 markus 116: extern char *__progname;
117:
1.1 deraadt 118: /* Server configuration options. */
119: ServerOptions options;
120:
121: /* Name of the server configuration file. */
1.154 markus 122: char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1.1 deraadt 123:
1.105 markus 124: /*
1.65 deraadt 125: * Debug mode flag. This can be set on the command line. If debug
126: * mode is enabled, extra debugging output will be sent to the system
127: * log, the daemon will not go to background, and will exit after processing
128: * the first connection.
129: */
1.1 deraadt 130: int debug_flag = 0;
131:
1.499 djm 132: /*
133: * Indicating that the daemon should only test the configuration and keys.
134: * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
135: * configuration, optionally using connection information provided by the
136: * "-C" flag.
137: */
1.521 djm 138: static int test_flag = 0;
1.203 stevesk 139:
1.1 deraadt 140: /* Flag indicating that the daemon is being started from inetd. */
1.521 djm 141: static int inetd_flag = 0;
1.1 deraadt 142:
1.135 markus 143: /* Flag indicating that sshd should not detach and become a daemon. */
1.521 djm 144: static int no_daemon_flag = 0;
1.135 markus 145:
1.47 markus 146: /* debug goes to stderr unless inetd_flag is set */
1.521 djm 147: static int log_stderr = 0;
1.47 markus 148:
1.1 deraadt 149: /* Saved arguments to main(). */
1.521 djm 150: static char **saved_argv;
1.1 deraadt 151:
1.294 djm 152: /* re-exec */
1.521 djm 153: static int rexeced_flag = 0;
154: static int rexec_flag = 1;
155: static int rexec_argc = 0;
156: static char **rexec_argv;
1.294 djm 157:
1.66 markus 158: /*
1.75 markus 159: * The sockets that the server is listening; this is used in the SIGHUP
160: * signal handler.
1.66 markus 161: */
1.75 markus 162: #define MAX_LISTEN_SOCKS 16
1.521 djm 163: static int listen_socks[MAX_LISTEN_SOCKS];
164: static int num_listen_socks = 0;
1.1 deraadt 165:
1.404 markus 166: /* Daemon's agent connection */
1.432 djm 167: int auth_sock = -1;
1.521 djm 168: static int have_agent = 0;
1.404 markus 169:
1.66 markus 170: /*
171: * Any really sensitive data in the application is contained in this
172: * structure. The idea is that this structure could be locked into memory so
173: * that the pages do not get written into swap. However, there are some
174: * problems. The private key contains BIGNUMs, and we do not (in principle)
175: * have access to the internals of them, and locking just the structure is
176: * not very useful. Currently, memory locking is not implemented.
177: */
1.64 markus 178: struct {
1.488 markus 179: struct sshkey **host_keys; /* all private host keys */
180: struct sshkey **host_pubkeys; /* all public host keys */
181: struct sshkey **host_certificates; /* all public host certificates */
182: int have_ssh2_key;
1.1 deraadt 183: } sensitive_data;
184:
1.199 markus 185: /* This is set to true when a signal is received. */
1.212 markus 186: static volatile sig_atomic_t received_sighup = 0;
187: static volatile sig_atomic_t received_sigterm = 0;
1.1 deraadt 188:
1.96 markus 189: /* session identifier, used by RSA-auth */
1.140 markus 190: u_char session_id[16];
1.96 markus 191:
1.108 markus 192: /* same for ssh2 */
1.140 markus 193: u_char *session_id2 = NULL;
1.269 markus 194: u_int session_id2_len = 0;
1.108 markus 195:
1.125 markus 196: /* record remote hostname or ip */
1.438 deraadt 197: u_int utmp_len = HOST_NAME_MAX+1;
1.125 markus 198:
1.211 markus 199: /* options.max_startup sized array of fd ints */
1.521 djm 200: static int *startup_pipes = NULL;
201: static int startup_pipe; /* in child */
1.211 markus 202:
1.231 provos 203: /* variables used for privilege separation */
1.337 dtucker 204: int use_privsep = -1;
1.285 dtucker 205: struct monitor *pmonitor = NULL;
1.386 djm 206: int privsep_is_preauth = 1;
1.231 provos 207:
1.278 markus 208: /* global authentication context */
209: Authctxt *the_authctxt = NULL;
210:
1.506 djm 211: /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
212: struct sshauthopt *auth_opts = NULL;
213:
1.337 dtucker 214: /* sshd_config buffer */
1.511 markus 215: struct sshbuf *cfg;
1.337 dtucker 216:
1.299 dtucker 217: /* message to be displayed after login */
1.510 markus 218: struct sshbuf *loginmsg;
1.299 dtucker 219:
1.1 deraadt 220: /* Prototypes for various functions defined later in this file. */
1.200 itojun 221: void destroy_sensitive_data(void);
1.231 provos 222: void demote_sensitive_data(void);
1.525 ! djm 223: static void do_ssh2_kex(struct ssh *);
1.129 provos 224:
1.87 markus 225: /*
1.75 markus 226: * Close all listening sockets
227: */
1.200 itojun 228: static void
1.75 markus 229: close_listen_socks(void)
230: {
231: int i;
1.250 deraadt 232:
1.75 markus 233: for (i = 0; i < num_listen_socks; i++)
234: close(listen_socks[i]);
235: num_listen_socks = -1;
236: }
237:
1.211 markus 238: static void
239: close_startup_pipes(void)
240: {
241: int i;
1.250 deraadt 242:
1.211 markus 243: if (startup_pipes)
244: for (i = 0; i < options.max_startups; i++)
245: if (startup_pipes[i] != -1)
246: close(startup_pipes[i]);
247: }
248:
1.75 markus 249: /*
1.65 deraadt 250: * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
251: * the effect is to reread the configuration file (and to regenerate
252: * the server key).
253: */
1.327 deraadt 254:
255: /*ARGSUSED*/
1.200 itojun 256: static void
1.64 markus 257: sighup_handler(int sig)
1.1 deraadt 258: {
1.210 deraadt 259: int save_errno = errno;
260:
1.64 markus 261: received_sighup = 1;
1.210 deraadt 262: errno = save_errno;
1.1 deraadt 263: }
264:
1.65 deraadt 265: /*
266: * Called from the main program after receiving SIGHUP.
267: * Restarts the server.
268: */
1.200 itojun 269: static void
1.165 itojun 270: sighup_restart(void)
1.1 deraadt 271: {
1.264 itojun 272: logit("Received SIGHUP; restarting.");
1.479 dtucker 273: if (options.pid_file != NULL)
274: unlink(options.pid_file);
1.75 markus 275: close_listen_socks();
1.211 markus 276: close_startup_pipes();
1.349 dtucker 277: alarm(0); /* alarm timer persists across exec */
1.369 dtucker 278: signal(SIGHUP, SIG_IGN); /* will be restored after exec */
1.64 markus 279: execv(saved_argv[0], saved_argv);
1.264 itojun 280: logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
1.250 deraadt 281: strerror(errno));
1.64 markus 282: exit(1);
1.1 deraadt 283: }
284:
1.65 deraadt 285: /*
286: * Generic signal handler for terminating signals in the master daemon.
287: */
1.327 deraadt 288: /*ARGSUSED*/
1.200 itojun 289: static void
1.64 markus 290: sigterm_handler(int sig)
1.1 deraadt 291: {
1.199 markus 292: received_sigterm = sig;
1.1 deraadt 293: }
294:
1.65 deraadt 295: /*
296: * SIGCHLD handler. This is called whenever a child dies. This will then
1.199 markus 297: * reap any zombies left by exited children.
1.65 deraadt 298: */
1.327 deraadt 299: /*ARGSUSED*/
1.200 itojun 300: static void
1.64 markus 301: main_sigchld_handler(int sig)
1.1 deraadt 302: {
1.250 deraadt 303: int save_errno = errno;
1.239 markus 304: pid_t pid;
1.64 markus 305: int status;
1.60 deraadt 306:
1.239 markus 307: while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
308: (pid < 0 && errno == EINTR))
1.64 markus 309: ;
310: errno = save_errno;
1.1 deraadt 311: }
312:
1.65 deraadt 313: /*
314: * Signal handler for the alarm after the login grace period has expired.
315: */
1.327 deraadt 316: /*ARGSUSED*/
1.200 itojun 317: static void
1.64 markus 318: grace_alarm_handler(int sig)
1.1 deraadt 319: {
1.285 dtucker 320: if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
321: kill(pmonitor->m_pid, SIGALRM);
1.394 djm 322:
323: /*
324: * Try to kill any processes that we have spawned, E.g. authorized
325: * keys command helpers.
326: */
327: if (getpgid(0) == getpid()) {
328: signal(SIGTERM, SIG_IGN);
1.416 djm 329: kill(0, SIGTERM);
1.394 djm 330: }
1.285 dtucker 331:
1.64 markus 332: /* Log error and exit. */
1.466 djm 333: sigdie("Timeout before authentication for %s port %d",
334: ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
1.62 markus 335: }
336:
1.134 markus 337: /* Destroy the host and server keys. They will no longer be needed. */
1.108 markus 338: void
339: destroy_sensitive_data(void)
340: {
1.493 djm 341: u_int i;
1.134 markus 342:
1.217 deraadt 343: for (i = 0; i < options.num_host_key_files; i++) {
1.134 markus 344: if (sensitive_data.host_keys[i]) {
1.512 markus 345: sshkey_free(sensitive_data.host_keys[i]);
1.134 markus 346: sensitive_data.host_keys[i] = NULL;
347: }
1.373 djm 348: if (sensitive_data.host_certificates[i]) {
1.512 markus 349: sshkey_free(sensitive_data.host_certificates[i]);
1.373 djm 350: sensitive_data.host_certificates[i] = NULL;
351: }
1.134 markus 352: }
353: }
354:
1.231 provos 355: /* Demote private to public keys for network child */
356: void
357: demote_sensitive_data(void)
358: {
1.488 markus 359: struct sshkey *tmp;
1.493 djm 360: u_int i;
1.512 markus 361: int r;
1.231 provos 362:
363: for (i = 0; i < options.num_host_key_files; i++) {
364: if (sensitive_data.host_keys[i]) {
1.515 djm 365: if ((r = sshkey_from_private(
366: sensitive_data.host_keys[i], &tmp)) != 0)
1.512 markus 367: fatal("could not demote host %s key: %s",
368: sshkey_type(sensitive_data.host_keys[i]),
369: ssh_err(r));
370: sshkey_free(sensitive_data.host_keys[i]);
1.231 provos 371: sensitive_data.host_keys[i] = tmp;
372: }
1.373 djm 373: /* Certs do not need demotion */
1.231 provos 374: }
375: }
376:
1.233 markus 377: static void
1.231 provos 378: privsep_preauth_child(void)
379: {
1.253 deraadt 380: gid_t gidset[1];
1.250 deraadt 381: struct passwd *pw;
1.231 provos 382:
383: /* Enable challenge-response authentication for privilege separation */
384: privsep_challenge_enable();
1.419 djm 385:
1.420 markus 386: #ifdef GSSAPI
1.419 djm 387: /* Cache supported mechanism OIDs for later use */
1.516 djm 388: ssh_gssapi_prepare_supported_oids();
1.420 markus 389: #endif
1.231 provos 390:
391: /* Demote the private keys to public keys. */
392: demote_sensitive_data();
393:
1.460 djm 394: /* Demote the child */
395: if (getuid() == 0 || geteuid() == 0) {
396: if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
397: fatal("Privilege separation user %s does not exist",
398: SSH_PRIVSEP_USER);
1.500 djm 399: pw = pwcopy(pw); /* Ensure mutable */
1.460 djm 400: endpwent();
1.500 djm 401: freezero(pw->pw_passwd, strlen(pw->pw_passwd));
1.460 djm 402:
403: /* Change our root directory */
404: if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
405: fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
406: strerror(errno));
407: if (chdir("/") == -1)
408: fatal("chdir(\"/\"): %s", strerror(errno));
409:
410: /*
411: * Drop our privileges
412: * NB. Can't use setusercontext() after chroot.
413: */
414: debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
415: (u_int)pw->pw_gid);
416: gidset[0] = pw->pw_gid;
417: if (setgroups(1, gidset) < 0)
418: fatal("setgroups: %.100s", strerror(errno));
419: permanently_set_uid(pw);
420: }
1.231 provos 421: }
422:
1.278 markus 423: static int
1.525 ! djm 424: privsep_preauth(struct ssh *ssh)
1.237 markus 425: {
1.525 ! djm 426: Authctxt *authctxt = (Authctxt *)ssh->authctxt;
1.432 djm 427: int status, r;
1.237 markus 428: pid_t pid;
1.384 djm 429: struct ssh_sandbox *box = NULL;
1.237 markus 430:
431: /* Set up unprivileged child process to deal with network data */
1.242 mouring 432: pmonitor = monitor_init();
1.237 markus 433: /* Store a pointer to the kex for later rekeying */
1.525 ! djm 434: pmonitor->m_pkex = &ssh->kex;
1.237 markus 435:
1.393 djm 436: if (use_privsep == PRIVSEP_ON)
1.384 djm 437: box = ssh_sandbox_init();
1.237 markus 438: pid = fork();
439: if (pid == -1) {
440: fatal("fork of unprivileged child failed");
441: } else if (pid != 0) {
1.245 mpech 442: debug2("Network child is on pid %ld", (long)pid);
1.237 markus 443:
1.392 markus 444: pmonitor->m_pid = pid;
1.432 djm 445: if (have_agent) {
446: r = ssh_get_authentication_socket(&auth_sock);
447: if (r != 0) {
448: error("Could not get agent socket: %s",
449: ssh_err(r));
450: have_agent = 0;
451: }
452: }
1.384 djm 453: if (box != NULL)
454: ssh_sandbox_parent_preauth(box, pid);
1.278 markus 455: monitor_child_preauth(authctxt, pmonitor);
1.237 markus 456:
457: /* Wait for the child's exit status */
1.384 djm 458: while (waitpid(pid, &status, 0) < 0) {
1.386 djm 459: if (errno == EINTR)
460: continue;
461: pmonitor->m_pid = -1;
462: fatal("%s: waitpid: %s", __func__, strerror(errno));
1.384 djm 463: }
1.386 djm 464: privsep_is_preauth = 0;
465: pmonitor->m_pid = -1;
1.384 djm 466: if (WIFEXITED(status)) {
467: if (WEXITSTATUS(status) != 0)
468: fatal("%s: preauth child exited with status %d",
469: __func__, WEXITSTATUS(status));
470: } else if (WIFSIGNALED(status))
471: fatal("%s: preauth child terminated by signal %d",
472: __func__, WTERMSIG(status));
473: if (box != NULL)
474: ssh_sandbox_parent_finish(box);
475: return 1;
1.237 markus 476: } else {
477: /* child */
1.383 djm 478: close(pmonitor->m_sendfd);
479: close(pmonitor->m_log_recvfd);
1.237 markus 480:
1.383 djm 481: /* Arrange for logging to be sent to the monitor */
482: set_log_handler(mm_log_handler, pmonitor);
1.237 markus 483:
1.460 djm 484: privsep_preauth_child();
1.238 stevesk 485: setproctitle("%s", "[net]");
1.384 djm 486: if (box != NULL)
487: ssh_sandbox_child(box);
488:
489: return 0;
1.237 markus 490: }
491: }
492:
1.233 markus 493: static void
1.525 ! djm 494: privsep_postauth(struct ssh *ssh, Authctxt *authctxt)
1.231 provos 495: {
1.474 djm 496: if (authctxt->pw->pw_uid == 0) {
1.231 provos 497: /* File descriptor passing is broken or root login */
498: use_privsep = 0;
1.315 djm 499: goto skip;
1.231 provos 500: }
1.234 markus 501:
1.231 provos 502: /* New socket pair */
1.242 mouring 503: monitor_reinit(pmonitor);
1.231 provos 504:
1.242 mouring 505: pmonitor->m_pid = fork();
506: if (pmonitor->m_pid == -1)
1.231 provos 507: fatal("fork of unprivileged child failed");
1.242 mouring 508: else if (pmonitor->m_pid != 0) {
1.364 markus 509: verbose("User child is on pid %ld", (long)pmonitor->m_pid);
1.510 markus 510: sshbuf_reset(loginmsg);
1.490 markus 511: monitor_clear_keystate(pmonitor);
1.242 mouring 512: monitor_child_postauth(pmonitor);
1.231 provos 513:
514: /* NEVERREACHED */
515: exit(0);
516: }
517:
1.383 djm 518: /* child */
519:
1.242 mouring 520: close(pmonitor->m_sendfd);
1.383 djm 521: pmonitor->m_sendfd = -1;
1.231 provos 522:
523: /* Demote the private keys to public keys. */
524: demote_sensitive_data();
1.354 djm 525:
1.231 provos 526: /* Drop privileges */
527: do_setusercontext(authctxt->pw);
528:
1.315 djm 529: skip:
1.231 provos 530: /* It is safe now to apply the key state */
1.242 mouring 531: monitor_apply_keystate(pmonitor);
1.312 markus 532:
533: /*
534: * Tell the packet layer that authentication was successful, since
535: * this information is not part of the key state.
536: */
1.525 ! djm 537: ssh_packet_set_authenticated(ssh);
1.231 provos 538: }
539:
1.509 djm 540: static void
541: append_hostkey_type(struct sshbuf *b, const char *s)
542: {
543: int r;
544:
545: if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
546: debug3("%s: %s key not permitted by HostkeyAlgorithms",
547: __func__, s);
548: return;
549: }
550: if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
551: fatal("%s: sshbuf_putf: %s", __func__, ssh_err(r));
552: }
553:
1.200 itojun 554: static char *
1.134 markus 555: list_hostkey_types(void)
556: {
1.509 djm 557: struct sshbuf *b;
558: struct sshkey *key;
1.281 jakob 559: char *ret;
1.493 djm 560: u_int i;
1.223 markus 561:
1.509 djm 562: if ((b = sshbuf_new()) == NULL)
563: fatal("%s: sshbuf_new failed", __func__);
1.217 deraadt 564: for (i = 0; i < options.num_host_key_files; i++) {
1.373 djm 565: key = sensitive_data.host_keys[i];
1.443 djm 566: if (key == NULL)
1.404 markus 567: key = sensitive_data.host_pubkeys[i];
1.472 markus 568: if (key == NULL)
1.134 markus 569: continue;
1.214 deraadt 570: switch (key->type) {
1.134 markus 571: case KEY_RSA:
1.509 djm 572: /* for RSA we also support SHA2 signatures */
573: append_hostkey_type(b, "rsa-sha2-512");
574: append_hostkey_type(b, "rsa-sha2-256");
575: /* FALLTHROUGH */
1.134 markus 576: case KEY_DSA:
1.378 djm 577: case KEY_ECDSA:
1.412 markus 578: case KEY_ED25519:
1.505 markus 579: case KEY_XMSS:
1.509 djm 580: append_hostkey_type(b, sshkey_ssh_name(key));
1.134 markus 581: break;
582: }
1.373 djm 583: /* If the private key has a cert peer, then list that too */
584: key = sensitive_data.host_certificates[i];
585: if (key == NULL)
586: continue;
587: switch (key->type) {
588: case KEY_RSA_CERT:
1.509 djm 589: /* for RSA we also support SHA2 signatures */
590: append_hostkey_type(b,
591: "rsa-sha2-512-cert-v01@openssh.com");
592: append_hostkey_type(b,
593: "rsa-sha2-256-cert-v01@openssh.com");
594: /* FALLTHROUGH */
1.373 djm 595: case KEY_DSA_CERT:
1.378 djm 596: case KEY_ECDSA_CERT:
1.412 markus 597: case KEY_ED25519_CERT:
1.505 markus 598: case KEY_XMSS_CERT:
1.509 djm 599: append_hostkey_type(b, sshkey_ssh_name(key));
1.373 djm 600: break;
601: }
1.134 markus 602: }
1.509 djm 603: if ((ret = sshbuf_dup_string(b)) == NULL)
1.467 djm 604: fatal("%s: sshbuf_dup_string failed", __func__);
1.509 djm 605: sshbuf_free(b);
606: debug("%s: %s", __func__, ret);
1.281 jakob 607: return ret;
1.134 markus 608: }
609:
1.488 markus 610: static struct sshkey *
1.440 djm 611: get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
1.134 markus 612: {
1.493 djm 613: u_int i;
1.488 markus 614: struct sshkey *key;
1.250 deraadt 615:
1.217 deraadt 616: for (i = 0; i < options.num_host_key_files; i++) {
1.375 djm 617: switch (type) {
618: case KEY_RSA_CERT:
619: case KEY_DSA_CERT:
1.378 djm 620: case KEY_ECDSA_CERT:
1.412 markus 621: case KEY_ED25519_CERT:
1.505 markus 622: case KEY_XMSS_CERT:
1.373 djm 623: key = sensitive_data.host_certificates[i];
1.375 djm 624: break;
625: default:
1.373 djm 626: key = sensitive_data.host_keys[i];
1.404 markus 627: if (key == NULL && !need_private)
628: key = sensitive_data.host_pubkeys[i];
1.375 djm 629: break;
630: }
1.440 djm 631: if (key != NULL && key->type == type &&
632: (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
1.373 djm 633: return need_private ?
634: sensitive_data.host_keys[i] : key;
1.134 markus 635: }
636: return NULL;
1.96 markus 637: }
638:
1.488 markus 639: struct sshkey *
1.440 djm 640: get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
1.373 djm 641: {
1.440 djm 642: return get_hostkey_by_type(type, nid, 0, ssh);
1.373 djm 643: }
644:
1.488 markus 645: struct sshkey *
1.440 djm 646: get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
1.373 djm 647: {
1.440 djm 648: return get_hostkey_by_type(type, nid, 1, ssh);
1.373 djm 649: }
650:
1.488 markus 651: struct sshkey *
1.231 provos 652: get_hostkey_by_index(int ind)
653: {
1.493 djm 654: if (ind < 0 || (u_int)ind >= options.num_host_key_files)
1.231 provos 655: return (NULL);
656: return (sensitive_data.host_keys[ind]);
657: }
658:
1.488 markus 659: struct sshkey *
1.435 markus 660: get_hostkey_public_by_index(int ind, struct ssh *ssh)
1.404 markus 661: {
1.493 djm 662: if (ind < 0 || (u_int)ind >= options.num_host_key_files)
1.404 markus 663: return (NULL);
664: return (sensitive_data.host_pubkeys[ind]);
665: }
666:
1.231 provos 667: int
1.488 markus 668: get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
1.231 provos 669: {
1.493 djm 670: u_int i;
1.250 deraadt 671:
1.231 provos 672: for (i = 0; i < options.num_host_key_files; i++) {
1.512 markus 673: if (sshkey_is_cert(key)) {
1.442 djm 674: if (key == sensitive_data.host_certificates[i] ||
675: (compare && sensitive_data.host_certificates[i] &&
676: sshkey_equal(key,
677: sensitive_data.host_certificates[i])))
1.373 djm 678: return (i);
679: } else {
1.442 djm 680: if (key == sensitive_data.host_keys[i] ||
681: (compare && sensitive_data.host_keys[i] &&
682: sshkey_equal(key, sensitive_data.host_keys[i])))
1.373 djm 683: return (i);
1.442 djm 684: if (key == sensitive_data.host_pubkeys[i] ||
685: (compare && sensitive_data.host_pubkeys[i] &&
686: sshkey_equal(key, sensitive_data.host_pubkeys[i])))
1.404 markus 687: return (i);
1.373 djm 688: }
1.231 provos 689: }
690: return (-1);
691: }
692:
1.439 djm 693: /* Inform the client of all hostkeys */
694: static void
695: notify_hostkeys(struct ssh *ssh)
696: {
697: struct sshbuf *buf;
698: struct sshkey *key;
1.493 djm 699: u_int i, nkeys;
700: int r;
1.439 djm 701: char *fp;
1.446 dtucker 702:
703: /* Some clients cannot cope with the hostkeys message, skip those. */
704: if (datafellows & SSH_BUG_HOSTKEYS)
705: return;
1.439 djm 706:
707: if ((buf = sshbuf_new()) == NULL)
708: fatal("%s: sshbuf_new", __func__);
709: for (i = nkeys = 0; i < options.num_host_key_files; i++) {
710: key = get_hostkey_public_by_index(i, ssh);
711: if (key == NULL || key->type == KEY_UNSPEC ||
1.472 markus 712: sshkey_is_cert(key))
1.439 djm 713: continue;
714: fp = sshkey_fingerprint(key, options.fingerprint_hash,
715: SSH_FP_DEFAULT);
716: debug3("%s: key %d: %s %s", __func__, i,
717: sshkey_ssh_name(key), fp);
718: free(fp);
1.442 djm 719: if (nkeys == 0) {
1.525 ! djm 720: /*
! 721: * Start building the request when we find the
! 722: * first usable key.
! 723: */
! 724: if ((r = sshpkt_start(ssh, SSH2_MSG_GLOBAL_REQUEST)) != 0 ||
! 725: (r = sshpkt_put_cstring(ssh, "hostkeys-00@openssh.com")) != 0 ||
! 726: (r = sshpkt_put_u8(ssh, 0)) != 0) /* want reply */
! 727: sshpkt_fatal(ssh, r, "%s: start request", __func__);
1.442 djm 728: }
1.525 ! djm 729: /* Append the key to the request */
1.442 djm 730: sshbuf_reset(buf);
731: if ((r = sshkey_putb(key, buf)) != 0)
1.439 djm 732: fatal("%s: couldn't put hostkey %d: %s",
733: __func__, i, ssh_err(r));
1.525 ! djm 734: if ((r = sshpkt_put_stringb(ssh, buf)) != 0)
! 735: sshpkt_fatal(ssh, r, "%s: append key", __func__);
1.439 djm 736: nkeys++;
737: }
1.493 djm 738: debug3("%s: sent %u hostkeys", __func__, nkeys);
1.439 djm 739: if (nkeys == 0)
740: fatal("%s: no hostkeys", __func__);
1.525 ! djm 741: if ((r = sshpkt_send(ssh)) != 0)
! 742: sshpkt_fatal(ssh, r, "%s: send", __func__);
1.442 djm 743: sshbuf_free(buf);
1.439 djm 744: }
745:
1.124 markus 746: /*
747: * returns 1 if connection should be dropped, 0 otherwise.
748: * dropping starts at connection #max_startups_begin with a probability
749: * of (max_startups_rate/100). the probability increases linearly until
750: * all connections are dropped for startups > max_startups
751: */
1.200 itojun 752: static int
1.124 markus 753: drop_connection(int startups)
754: {
1.303 mickey 755: int p, r;
1.124 markus 756:
757: if (startups < options.max_startups_begin)
758: return 0;
759: if (startups >= options.max_startups)
760: return 1;
761: if (options.max_startups_rate == 100)
762: return 1;
763:
764: p = 100 - options.max_startups_rate;
765: p *= startups - options.max_startups_begin;
1.303 mickey 766: p /= options.max_startups - options.max_startups_begin;
1.124 markus 767: p += options.max_startups_rate;
1.356 djm 768: r = arc4random_uniform(100);
1.124 markus 769:
1.304 djm 770: debug("drop_connection: p %d, r %d", p, r);
1.124 markus 771: return (r < p) ? 1 : 0;
772: }
773:
1.215 markus 774: static void
775: usage(void)
776: {
1.290 markus 777: fprintf(stderr, "%s, %s\n",
1.426 markus 778: SSH_VERSION,
779: #ifdef WITH_OPENSSL
1.517 djm 780: OpenSSL_version(OPENSSL_VERSION)
1.426 markus 781: #else
782: "without OpenSSL"
783: #endif
784: );
1.289 markus 785: fprintf(stderr,
1.473 naddy 786: "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
1.399 dtucker 787: " [-E log_file] [-f config_file] [-g login_grace_time]\n"
1.473 naddy 788: " [-h host_key_file] [-o option] [-p port] [-u len]\n"
1.289 markus 789: );
1.215 markus 790: exit(1);
791: }
792:
1.294 djm 793: static void
1.467 djm 794: send_rexec_state(int fd, struct sshbuf *conf)
1.294 djm 795: {
1.467 djm 796: struct sshbuf *m;
797: int r;
1.294 djm 798:
1.467 djm 799: debug3("%s: entering fd = %d config len %zu", __func__, fd,
800: sshbuf_len(conf));
1.294 djm 801:
802: /*
803: * Protocol from reexec master to child:
804: * string configuration
805: */
1.467 djm 806: if ((m = sshbuf_new()) == NULL)
807: fatal("%s: sshbuf_new failed", __func__);
808: if ((r = sshbuf_put_stringb(m, conf)) != 0)
809: fatal("%s: buffer error: %s", __func__, ssh_err(r));
810: if (ssh_msg_send(fd, 0, m) == -1)
1.294 djm 811: fatal("%s: ssh_msg_send failed", __func__);
812:
1.467 djm 813: sshbuf_free(m);
1.294 djm 814:
815: debug3("%s: done", __func__);
816: }
817:
818: static void
1.511 markus 819: recv_rexec_state(int fd, struct sshbuf *conf)
1.294 djm 820: {
1.511 markus 821: struct sshbuf *m;
822: u_char *cp, ver;
823: size_t len;
824: int r;
1.294 djm 825:
826: debug3("%s: entering fd = %d", __func__, fd);
827:
1.511 markus 828: if ((m = sshbuf_new()) == NULL)
829: fatal("%s: sshbuf_new failed", __func__);
830: if (ssh_msg_recv(fd, m) == -1)
1.294 djm 831: fatal("%s: ssh_msg_recv failed", __func__);
1.511 markus 832: if ((r = sshbuf_get_u8(m, &ver)) != 0)
833: fatal("%s: buffer error: %s", __func__, ssh_err(r));
834: if (ver != 0)
1.294 djm 835: fatal("%s: rexec version mismatch", __func__);
1.511 markus 836: if ((r = sshbuf_get_string(m, &cp, &len)) != 0)
837: fatal("%s: buffer error: %s", __func__, ssh_err(r));
838: if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
839: fatal("%s: buffer error: %s", __func__, ssh_err(r));
1.294 djm 840:
1.402 djm 841: free(cp);
1.511 markus 842: sshbuf_free(m);
1.294 djm 843:
844: debug3("%s: done", __func__);
845: }
846:
1.345 djm 847: /* Accept a connection from inetd */
848: static void
849: server_accept_inetd(int *sock_in, int *sock_out)
850: {
851: int fd;
852:
853: startup_pipe = -1;
854: if (rexeced_flag) {
855: close(REEXEC_CONFIG_PASS_FD);
856: *sock_in = *sock_out = dup(STDIN_FILENO);
857: if (!debug_flag) {
858: startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
859: close(REEXEC_STARTUP_PIPE_FD);
860: }
861: } else {
862: *sock_in = dup(STDIN_FILENO);
863: *sock_out = dup(STDOUT_FILENO);
864: }
865: /*
866: * We intentionally do not close the descriptors 0, 1, and 2
867: * as our code for setting the descriptors won't work if
868: * ttyfd happens to be one of those.
869: */
870: if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
871: dup2(fd, STDIN_FILENO);
872: dup2(fd, STDOUT_FILENO);
1.403 dtucker 873: if (!log_stderr)
874: dup2(fd, STDERR_FILENO);
875: if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1.345 djm 876: close(fd);
877: }
878: debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
879: }
880:
881: /*
882: * Listen for TCP connections
883: */
884: static void
1.494 djm 885: listen_on_addrs(struct listenaddr *la)
1.345 djm 886: {
1.494 djm 887: int ret, listen_sock;
1.345 djm 888: struct addrinfo *ai;
889: char ntop[NI_MAXHOST], strport[NI_MAXSERV];
890:
1.494 djm 891: for (ai = la->addrs; ai; ai = ai->ai_next) {
1.345 djm 892: if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
893: continue;
894: if (num_listen_socks >= MAX_LISTEN_SOCKS)
895: fatal("Too many listen sockets. "
896: "Enlarge MAX_LISTEN_SOCKS");
897: if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
898: ntop, sizeof(ntop), strport, sizeof(strport),
899: NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
900: error("getnameinfo failed: %.100s",
1.352 dtucker 901: ssh_gai_strerror(ret));
1.345 djm 902: continue;
903: }
904: /* Create socket for listening. */
1.370 dtucker 905: listen_sock = socket(ai->ai_family, ai->ai_socktype,
906: ai->ai_protocol);
1.345 djm 907: if (listen_sock < 0) {
908: /* kernel may not support ipv6 */
909: verbose("socket: %.100s", strerror(errno));
910: continue;
911: }
912: if (set_nonblock(listen_sock) == -1) {
1.483 djm 913: close(listen_sock);
914: continue;
915: }
916: if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
917: verbose("socket: CLOEXEC: %s", strerror(errno));
1.345 djm 918: close(listen_sock);
919: continue;
920: }
1.494 djm 921: /* Socket options */
922: set_reuseaddr(listen_sock);
923: if (la->rdomain != NULL &&
924: set_rdomain(listen_sock, la->rdomain) == -1) {
925: close(listen_sock);
926: continue;
927: }
1.345 djm 928:
929: debug("Bind to port %s on %s.", strport, ntop);
930:
931: /* Bind the socket to the desired port. */
932: if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
933: error("Bind to port %s on %s failed: %.200s.",
934: strport, ntop, strerror(errno));
935: close(listen_sock);
936: continue;
937: }
938: listen_socks[num_listen_socks] = listen_sock;
939: num_listen_socks++;
940:
941: /* Start listening on the port. */
942: if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
943: fatal("listen on [%s]:%s: %.100s",
944: ntop, strport, strerror(errno));
1.494 djm 945: logit("Server listening on %s port %s%s%s.",
946: ntop, strport,
947: la->rdomain == NULL ? "" : " rdomain ",
948: la->rdomain == NULL ? "" : la->rdomain);
1.345 djm 949: }
1.494 djm 950: }
951:
952: static void
953: server_listen(void)
954: {
955: u_int i;
956:
957: for (i = 0; i < options.num_listen_addrs; i++) {
958: listen_on_addrs(&options.listen_addrs[i]);
959: freeaddrinfo(options.listen_addrs[i].addrs);
960: free(options.listen_addrs[i].rdomain);
961: memset(&options.listen_addrs[i], 0,
962: sizeof(options.listen_addrs[i]));
963: }
964: free(options.listen_addrs);
965: options.listen_addrs = NULL;
966: options.num_listen_addrs = 0;
1.345 djm 967:
968: if (!num_listen_socks)
969: fatal("Cannot bind any address.");
970: }
971:
972: /*
973: * The main TCP accept loop. Note that, for the non-debug case, returns
974: * from this function are in a forked subprocess.
975: */
976: static void
977: server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
978: {
979: fd_set *fdset;
980: int i, j, ret, maxfd;
1.472 markus 981: int startups = 0;
1.345 djm 982: int startup_p[2] = { -1 , -1 };
983: struct sockaddr_storage from;
984: socklen_t fromlen;
985: pid_t pid;
986:
987: /* setup fd set for accept */
988: fdset = NULL;
989: maxfd = 0;
990: for (i = 0; i < num_listen_socks; i++)
991: if (listen_socks[i] > maxfd)
992: maxfd = listen_socks[i];
993: /* pipes connected to unauthenticated childs */
994: startup_pipes = xcalloc(options.max_startups, sizeof(int));
995: for (i = 0; i < options.max_startups; i++)
996: startup_pipes[i] = -1;
997:
998: /*
999: * Stay listening for connections until the system crashes or
1000: * the daemon is killed with a signal.
1001: */
1002: for (;;) {
1003: if (received_sighup)
1004: sighup_restart();
1.462 mmcc 1005: free(fdset);
1.458 deraadt 1006: fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1.345 djm 1007: sizeof(fd_mask));
1008:
1009: for (i = 0; i < num_listen_socks; i++)
1010: FD_SET(listen_socks[i], fdset);
1011: for (i = 0; i < options.max_startups; i++)
1012: if (startup_pipes[i] != -1)
1013: FD_SET(startup_pipes[i], fdset);
1014:
1015: /* Wait in select until there is a connection. */
1016: ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1017: if (ret < 0 && errno != EINTR)
1018: error("select: %.100s", strerror(errno));
1019: if (received_sigterm) {
1020: logit("Received signal %d; terminating.",
1021: (int) received_sigterm);
1022: close_listen_socks();
1.430 djm 1023: if (options.pid_file != NULL)
1024: unlink(options.pid_file);
1.382 djm 1025: exit(received_sigterm == SIGTERM ? 0 : 255);
1.345 djm 1026: }
1027: if (ret < 0)
1028: continue;
1029:
1030: for (i = 0; i < options.max_startups; i++)
1031: if (startup_pipes[i] != -1 &&
1032: FD_ISSET(startup_pipes[i], fdset)) {
1033: /*
1034: * the read end of the pipe is ready
1035: * if the child has closed the pipe
1036: * after successful authentication
1037: * or if the child has died
1038: */
1039: close(startup_pipes[i]);
1040: startup_pipes[i] = -1;
1041: startups--;
1042: }
1043: for (i = 0; i < num_listen_socks; i++) {
1044: if (!FD_ISSET(listen_socks[i], fdset))
1045: continue;
1046: fromlen = sizeof(from);
1047: *newsock = accept(listen_socks[i],
1048: (struct sockaddr *)&from, &fromlen);
1049: if (*newsock < 0) {
1.398 markus 1050: if (errno != EINTR && errno != EWOULDBLOCK &&
1051: errno != ECONNABORTED)
1.389 djm 1052: error("accept: %.100s",
1053: strerror(errno));
1054: if (errno == EMFILE || errno == ENFILE)
1055: usleep(100 * 1000);
1.345 djm 1056: continue;
1057: }
1058: if (unset_nonblock(*newsock) == -1) {
1059: close(*newsock);
1060: continue;
1061: }
1062: if (drop_connection(startups) == 1) {
1.480 djm 1063: char *laddr = get_local_ipaddr(*newsock);
1064: char *raddr = get_peer_ipaddr(*newsock);
1065:
1066: verbose("drop connection #%d from [%s]:%d "
1067: "on [%s]:%d past MaxStartups", startups,
1068: raddr, get_peer_port(*newsock),
1069: laddr, get_local_port(*newsock));
1070: free(laddr);
1071: free(raddr);
1.345 djm 1072: close(*newsock);
1073: continue;
1074: }
1075: if (pipe(startup_p) == -1) {
1076: close(*newsock);
1077: continue;
1078: }
1079:
1080: if (rexec_flag && socketpair(AF_UNIX,
1081: SOCK_STREAM, 0, config_s) == -1) {
1082: error("reexec socketpair: %s",
1083: strerror(errno));
1084: close(*newsock);
1085: close(startup_p[0]);
1086: close(startup_p[1]);
1087: continue;
1088: }
1089:
1090: for (j = 0; j < options.max_startups; j++)
1091: if (startup_pipes[j] == -1) {
1092: startup_pipes[j] = startup_p[0];
1093: if (maxfd < startup_p[0])
1094: maxfd = startup_p[0];
1095: startups++;
1096: break;
1097: }
1098:
1099: /*
1100: * Got connection. Fork a child to handle it, unless
1101: * we are in debugging mode.
1102: */
1103: if (debug_flag) {
1104: /*
1105: * In debugging mode. Close the listening
1106: * socket, and start processing the
1107: * connection without forking.
1108: */
1109: debug("Server will not fork when running in debugging mode.");
1110: close_listen_socks();
1111: *sock_in = *newsock;
1112: *sock_out = *newsock;
1113: close(startup_p[0]);
1114: close(startup_p[1]);
1115: startup_pipe = -1;
1116: pid = getpid();
1117: if (rexec_flag) {
1.511 markus 1118: send_rexec_state(config_s[0], cfg);
1.345 djm 1119: close(config_s[0]);
1120: }
1121: break;
1122: }
1123:
1124: /*
1125: * Normal production daemon. Fork, and have
1126: * the child process the connection. The
1127: * parent continues listening.
1128: */
1129: if ((pid = fork()) == 0) {
1130: /*
1131: * Child. Close the listening and
1132: * max_startup sockets. Start using
1133: * the accepted socket. Reinitialize
1134: * logging (since our pid has changed).
1135: * We break out of the loop to handle
1136: * the connection.
1137: */
1138: startup_pipe = startup_p[1];
1139: close_startup_pipes();
1140: close_listen_socks();
1141: *sock_in = *newsock;
1142: *sock_out = *newsock;
1143: log_init(__progname,
1144: options.log_level,
1145: options.log_facility,
1146: log_stderr);
1147: if (rexec_flag)
1148: close(config_s[0]);
1149: break;
1150: }
1151:
1152: /* Parent. Stay in the loop. */
1153: if (pid < 0)
1154: error("fork: %.100s", strerror(errno));
1155: else
1156: debug("Forked child %ld.", (long)pid);
1157:
1158: close(startup_p[1]);
1159:
1160: if (rexec_flag) {
1.511 markus 1161: send_rexec_state(config_s[0], cfg);
1.345 djm 1162: close(config_s[0]);
1163: close(config_s[1]);
1164: }
1165: close(*newsock);
1166: }
1167:
1168: /* child process check (or debug mode) */
1169: if (num_listen_socks < 0)
1170: break;
1171: }
1172: }
1173:
1.466 djm 1174: /*
1175: * If IP options are supported, make sure there are none (log and
1176: * return an error if any are found). Basically we are worried about
1177: * source routing; it can be used to pretend you are somebody
1178: * (ip-address) you are not. That itself may be "almost acceptable"
1.507 djm 1179: * under certain circumstances, but rhosts authentication is useless
1.466 djm 1180: * if source routing is accepted. Notice also that if we just dropped
1181: * source routing here, the other side could use IP spoofing to do
1182: * rest of the interaction and could still bypass security. So we
1183: * exit here if we detect any IP options.
1184: */
1185: static void
1186: check_ip_options(struct ssh *ssh)
1187: {
1188: int sock_in = ssh_packet_get_connection_in(ssh);
1189: struct sockaddr_storage from;
1190: u_char opts[200];
1.475 djm 1191: socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1.466 djm 1192: char text[sizeof(opts) * 3 + 1];
1193:
1194: memset(&from, 0, sizeof(from));
1195: if (getpeername(sock_in, (struct sockaddr *)&from,
1196: &fromlen) < 0)
1197: return;
1198: if (from.ss_family != AF_INET)
1199: return;
1200: /* XXX IPv6 options? */
1201:
1202: if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1203: &option_size) >= 0 && option_size != 0) {
1204: text[0] = '\0';
1205: for (i = 0; i < option_size; i++)
1206: snprintf(text + i*3, sizeof(text) - i*3,
1207: " %2.2x", opts[i]);
1208: fatal("Connection from %.100s port %d with IP opts: %.800s",
1209: ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1210: }
1211: return;
1212: }
1.345 djm 1213:
1.495 djm 1214: /* Set the routing domain for this process */
1215: static void
1216: set_process_rdomain(struct ssh *ssh, const char *name)
1217: {
1218: int rtable, ortable = getrtable();
1219: const char *errstr;
1220:
1221: if (name == NULL)
1222: return; /* default */
1223:
1224: if (strcmp(name, "%D") == 0) {
1225: /* "expands" to routing domain of connection */
1226: if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1227: return;
1228: }
1229:
1230: rtable = (int)strtonum(name, 0, 255, &errstr);
1231: if (errstr != NULL) /* Shouldn't happen */
1232: fatal("Invalid routing domain \"%s\": %s", name, errstr);
1233: if (rtable != ortable && setrtable(rtable) != 0)
1234: fatal("Unable to set routing domain %d: %s",
1235: rtable, strerror(errno));
1236: debug("%s: set routing domain %d (was %d)", __func__, rtable, ortable);
1237: }
1238:
1.508 dtucker 1239: static void
1240: accumulate_host_timing_secret(struct sshbuf *server_cfg,
1241: const struct sshkey *key)
1242: {
1243: static struct ssh_digest_ctx *ctx;
1244: u_char *hash;
1245: size_t len;
1246: struct sshbuf *buf;
1247: int r;
1248:
1249: if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1250: fatal("%s: ssh_digest_start", __func__);
1251: if (key == NULL) { /* finalize */
1252: /* add server config in case we are using agent for host keys */
1253: if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1254: sshbuf_len(server_cfg)) != 0)
1255: fatal("%s: ssh_digest_update", __func__);
1256: len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1257: hash = xmalloc(len);
1258: if (ssh_digest_final(ctx, hash, len) != 0)
1259: fatal("%s: ssh_digest_final", __func__);
1260: options.timing_secret = PEEK_U64(hash);
1261: freezero(hash, len);
1262: ssh_digest_free(ctx);
1263: ctx = NULL;
1264: return;
1265: }
1266: if ((buf = sshbuf_new()) == NULL)
1267: fatal("%s could not allocate buffer", __func__);
1268: if ((r = sshkey_private_serialize(key, buf)) != 0)
1269: fatal("sshkey_private_serialize: %s", ssh_err(r));
1270: if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1271: fatal("%s: ssh_digest_update", __func__);
1272: sshbuf_reset(buf);
1273: sshbuf_free(buf);
1274: }
1275:
1.65 deraadt 1276: /*
1277: * Main program for the daemon.
1278: */
1.2 provos 1279: int
1280: main(int ac, char **av)
1.1 deraadt 1281: {
1.466 djm 1282: struct ssh *ssh = NULL;
1.64 markus 1283: extern char *optarg;
1284: extern int optind;
1.493 djm 1285: int r, opt, on = 1, already_daemon, remote_port;
1.297 avsm 1286: int sock_in = -1, sock_out = -1, newsock = -1;
1.496 djm 1287: const char *remote_ip, *rdomain;
1.447 dtucker 1288: char *fp, *line, *laddr, *logfile = NULL;
1.345 djm 1289: int config_s[2] = { -1 , -1 };
1.493 djm 1290: u_int i, j;
1.364 markus 1291: u_int64_t ibytes, obytes;
1.362 dtucker 1292: mode_t new_umask;
1.488 markus 1293: struct sshkey *key;
1294: struct sshkey *pubkey;
1.404 markus 1295: int keytype;
1.230 provos 1296: Authctxt *authctxt;
1.498 dtucker 1297: struct connection_info *connection_info = NULL;
1.64 markus 1298:
1.465 dtucker 1299: ssh_malloc_init(); /* must be called before any mallocs */
1.138 markus 1300: /* Save argv. */
1.64 markus 1301: saved_argv = av;
1.294 djm 1302: rexec_argc = ac;
1.313 djm 1303:
1304: /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1305: sanitise_stdfd();
1.64 markus 1306:
1307: /* Initialize configuration options to their default values. */
1308: initialize_server_options(&options);
1309:
1310: /* Parse command-line arguments. */
1.450 djm 1311: while ((opt = getopt(ac, av,
1312: "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1.64 markus 1313: switch (opt) {
1.75 markus 1314: case '4':
1.305 djm 1315: options.address_family = AF_INET;
1.75 markus 1316: break;
1317: case '6':
1.305 djm 1318: options.address_family = AF_INET6;
1.75 markus 1319: break;
1.64 markus 1320: case 'f':
1321: config_file_name = optarg;
1322: break;
1.373 djm 1323: case 'c':
1.493 djm 1324: servconf_add_hostcert("[command-line]", 0,
1325: &options, optarg);
1.373 djm 1326: break;
1.64 markus 1327: case 'd':
1.273 markus 1328: if (debug_flag == 0) {
1.127 markus 1329: debug_flag = 1;
1330: options.log_level = SYSLOG_LEVEL_DEBUG1;
1.273 markus 1331: } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1.127 markus 1332: options.log_level++;
1.64 markus 1333: break;
1.135 markus 1334: case 'D':
1335: no_daemon_flag = 1;
1.192 lebel 1336: break;
1.399 dtucker 1337: case 'E':
1.459 dtucker 1338: logfile = optarg;
1.399 dtucker 1339: /* FALLTHROUGH */
1.192 lebel 1340: case 'e':
1341: log_stderr = 1;
1.135 markus 1342: break;
1.64 markus 1343: case 'i':
1344: inetd_flag = 1;
1345: break;
1.294 djm 1346: case 'r':
1347: rexec_flag = 0;
1348: break;
1349: case 'R':
1350: rexeced_flag = 1;
1351: inetd_flag = 1;
1352: break;
1.64 markus 1353: case 'Q':
1.158 markus 1354: /* ignored */
1.64 markus 1355: break;
1356: case 'q':
1357: options.log_level = SYSLOG_LEVEL_QUIET;
1358: break;
1359: case 'b':
1.473 naddy 1360: /* protocol 1, ignored */
1.64 markus 1361: break;
1362: case 'p':
1.75 markus 1363: options.ports_from_cmdline = 1;
1.127 markus 1364: if (options.num_ports >= MAX_PORTS) {
1365: fprintf(stderr, "too many ports.\n");
1366: exit(1);
1367: }
1.193 stevesk 1368: options.ports[options.num_ports++] = a2port(optarg);
1.366 djm 1369: if (options.ports[options.num_ports-1] <= 0) {
1.193 stevesk 1370: fprintf(stderr, "Bad port number.\n");
1371: exit(1);
1372: }
1.64 markus 1373: break;
1374: case 'g':
1.197 stevesk 1375: if ((options.login_grace_time = convtime(optarg)) == -1) {
1376: fprintf(stderr, "Invalid login grace time.\n");
1377: exit(1);
1378: }
1.64 markus 1379: break;
1380: case 'k':
1.473 naddy 1381: /* protocol 1, ignored */
1.64 markus 1382: break;
1383: case 'h':
1.493 djm 1384: servconf_add_hostkey("[command-line]", 0,
1.519 djm 1385: &options, optarg, 1);
1.64 markus 1386: break;
1.203 stevesk 1387: case 't':
1388: test_flag = 1;
1389: break;
1.358 dtucker 1390: case 'T':
1391: test_flag = 2;
1392: break;
1393: case 'C':
1.523 djm 1394: connection_info = get_connection_info(ssh, 0, 0);
1.391 dtucker 1395: if (parse_server_match_testspec(connection_info,
1396: optarg) == -1)
1397: exit(1);
1.358 dtucker 1398: break;
1.125 markus 1399: case 'u':
1.438 deraadt 1400: utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1401: if (utmp_len > HOST_NAME_MAX+1) {
1.257 stevesk 1402: fprintf(stderr, "Invalid utmp length.\n");
1403: exit(1);
1404: }
1.125 markus 1405: break;
1.215 markus 1406: case 'o':
1.283 markus 1407: line = xstrdup(optarg);
1408: if (process_server_config_line(&options, line,
1.391 dtucker 1409: "command-line", 0, NULL, NULL) != 0)
1.217 deraadt 1410: exit(1);
1.402 djm 1411: free(line);
1.215 markus 1412: break;
1.64 markus 1413: case '?':
1414: default:
1.215 markus 1415: usage();
1416: break;
1.64 markus 1417: }
1418: }
1.294 djm 1419: if (rexeced_flag || inetd_flag)
1420: rexec_flag = 0;
1.518 djm 1421: if (!test_flag && rexec_flag && !path_absolute(av[0]))
1.294 djm 1422: fatal("sshd re-exec requires execution with an absolute path");
1423: if (rexeced_flag)
1.296 djm 1424: closefrom(REEXEC_MIN_FREE_FD);
1425: else
1426: closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1.294 djm 1427:
1.426 markus 1428: #ifdef WITH_OPENSSL
1.379 djm 1429: OpenSSL_add_all_algorithms();
1.426 markus 1430: #endif
1.64 markus 1431:
1.399 dtucker 1432: /* If requested, redirect the logs to the specified logfile. */
1.459 dtucker 1433: if (logfile != NULL)
1.399 dtucker 1434: log_redirect_stderr_to(logfile);
1.75 markus 1435: /*
1436: * Force logging to stderr until we have loaded the private host
1437: * key (unless started from inetd)
1438: */
1.138 markus 1439: log_init(__progname,
1.224 markus 1440: options.log_level == SYSLOG_LEVEL_NOT_SET ?
1441: SYSLOG_LEVEL_INFO : options.log_level,
1442: options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1443: SYSLOG_FACILITY_AUTH : options.log_facility,
1.261 markus 1444: log_stderr || !inetd_flag);
1.75 markus 1445:
1.294 djm 1446: sensitive_data.have_ssh2_key = 0;
1447:
1.358 dtucker 1448: /*
1.498 dtucker 1449: * If we're not doing an extended test do not silently ignore connection
1450: * test params.
1.358 dtucker 1451: */
1.498 dtucker 1452: if (test_flag < 2 && connection_info != NULL)
1.358 dtucker 1453: fatal("Config test connection parameter (-C) provided without "
1454: "test mode (-T)");
1455:
1.294 djm 1456: /* Fetch our configuration */
1.511 markus 1457: if ((cfg = sshbuf_new()) == NULL)
1458: fatal("%s: sshbuf_new failed", __func__);
1.294 djm 1459: if (rexeced_flag)
1.511 markus 1460: recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1.448 djm 1461: else if (strcasecmp(config_file_name, "none") != 0)
1.511 markus 1462: load_server_config(config_file_name, cfg);
1.294 djm 1463:
1.337 dtucker 1464: parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1.511 markus 1465: cfg, NULL);
1.64 markus 1466:
1467: /* Fill in default values for those options not explicitly set. */
1468: fill_default_server_options(&options);
1.350 dtucker 1469:
1470: /* challenge-response is implemented via keyboard interactive */
1471: if (options.challenge_response_authentication)
1472: options.kbd_interactive_authentication = 1;
1.395 djm 1473:
1474: /* Check that options are sensible */
1475: if (options.authorized_keys_command_user == NULL &&
1476: (options.authorized_keys_command != NULL &&
1477: strcasecmp(options.authorized_keys_command, "none") != 0))
1478: fatal("AuthorizedKeysCommand set without "
1479: "AuthorizedKeysCommandUser");
1.449 djm 1480: if (options.authorized_principals_command_user == NULL &&
1481: (options.authorized_principals_command != NULL &&
1482: strcasecmp(options.authorized_principals_command, "none") != 0))
1483: fatal("AuthorizedPrincipalsCommand set without "
1484: "AuthorizedPrincipalsCommandUser");
1.396 djm 1485:
1486: /*
1487: * Check whether there is any path through configured auth methods.
1488: * Unfortunately it is not possible to verify this generally before
1489: * daemonisation in the presence of Match block, but this catches
1490: * and warns for trivial misconfigurations that could break login.
1491: */
1492: if (options.num_auth_methods != 0) {
1.493 djm 1493: for (i = 0; i < options.num_auth_methods; i++) {
1494: if (auth2_methods_valid(options.auth_methods[i],
1.396 djm 1495: 1) == 0)
1496: break;
1497: }
1.493 djm 1498: if (i >= options.num_auth_methods)
1.396 djm 1499: fatal("AuthenticationMethods cannot be satisfied by "
1500: "enabled authentication methods");
1501: }
1.305 djm 1502:
1.64 markus 1503: /* Check that there are no remaining arguments. */
1504: if (optind < ac) {
1505: fprintf(stderr, "Extra argument %s.\n", av[optind]);
1506: exit(1);
1507: }
1508:
1.397 dtucker 1509: debug("sshd version %s, %s", SSH_VERSION,
1.426 markus 1510: #ifdef WITH_OPENSSL
1.517 djm 1511: OpenSSL_version(OPENSSL_VERSION)
1.426 markus 1512: #else
1513: "without OpenSSL"
1514: #endif
1515: );
1.64 markus 1516:
1.404 markus 1517: /* load host keys */
1.329 djm 1518: sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1.488 markus 1519: sizeof(struct sshkey *));
1.404 markus 1520: sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1.488 markus 1521: sizeof(struct sshkey *));
1.404 markus 1522:
1523: if (options.host_key_agent) {
1524: if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1525: setenv(SSH_AUTHSOCKET_ENV_NAME,
1526: options.host_key_agent, 1);
1.433 djm 1527: if ((r = ssh_get_authentication_socket(NULL)) == 0)
1528: have_agent = 1;
1529: else
1530: error("Could not connect to agent \"%s\": %s",
1531: options.host_key_agent, ssh_err(r));
1.404 markus 1532: }
1.134 markus 1533:
1.217 deraadt 1534: for (i = 0; i < options.num_host_key_files; i++) {
1.519 djm 1535: int ll = options.host_key_file_userprovided[i] ?
1536: SYSLOG_LEVEL_ERROR : SYSLOG_LEVEL_DEBUG1;
1537:
1.430 djm 1538: if (options.host_key_files[i] == NULL)
1539: continue;
1.512 markus 1540: if ((r = sshkey_load_private(options.host_key_files[i], "",
1541: &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1.519 djm 1542: do_log2(ll, "Unable to load host key \"%s\": %s",
1.512 markus 1543: options.host_key_files[i], ssh_err(r));
1544: if ((r = sshkey_load_public(options.host_key_files[i],
1545: &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1.519 djm 1546: do_log2(ll, "Unable to load host key \"%s\": %s",
1.512 markus 1547: options.host_key_files[i], ssh_err(r));
1.439 djm 1548: if (pubkey == NULL && key != NULL)
1.515 djm 1549: if ((r = sshkey_from_private(key, &pubkey)) != 0)
1.512 markus 1550: fatal("Could not demote key: \"%s\": %s",
1551: options.host_key_files[i], ssh_err(r));
1.179 markus 1552: sensitive_data.host_keys[i] = key;
1.404 markus 1553: sensitive_data.host_pubkeys[i] = pubkey;
1554:
1.472 markus 1555: if (key == NULL && pubkey != NULL && have_agent) {
1.443 djm 1556: debug("will rely on agent for hostkey %s",
1557: options.host_key_files[i]);
1.404 markus 1558: keytype = pubkey->type;
1559: } else if (key != NULL) {
1560: keytype = key->type;
1.511 markus 1561: accumulate_host_timing_secret(cfg, key);
1.404 markus 1562: } else {
1.519 djm 1563: do_log2(ll, "Unable to load host key: %s",
1.195 markus 1564: options.host_key_files[i]);
1.179 markus 1565: sensitive_data.host_keys[i] = NULL;
1.404 markus 1566: sensitive_data.host_pubkeys[i] = NULL;
1.134 markus 1567: continue;
1568: }
1.404 markus 1569:
1570: switch (keytype) {
1.134 markus 1571: case KEY_RSA:
1572: case KEY_DSA:
1.378 djm 1573: case KEY_ECDSA:
1.412 markus 1574: case KEY_ED25519:
1.505 markus 1575: case KEY_XMSS:
1.441 djm 1576: if (have_agent || key != NULL)
1577: sensitive_data.have_ssh2_key = 1;
1.134 markus 1578: break;
1579: }
1.441 djm 1580: if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1581: SSH_FP_DEFAULT)) == NULL)
1582: fatal("sshkey_fingerprint failed");
1583: debug("%s host key #%d: %s %s",
1.472 markus 1584: key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1.441 djm 1585: free(fp);
1.134 markus 1586: }
1.511 markus 1587: accumulate_host_timing_secret(cfg, NULL);
1.472 markus 1588: if (!sensitive_data.have_ssh2_key) {
1.264 itojun 1589: logit("sshd: no hostkeys available -- exiting.");
1.64 markus 1590: exit(1);
1591: }
1592:
1.373 djm 1593: /*
1594: * Load certificates. They are stored in an array at identical
1595: * indices to the public keys that they relate to.
1596: */
1597: sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1.488 markus 1598: sizeof(struct sshkey *));
1.373 djm 1599: for (i = 0; i < options.num_host_key_files; i++)
1600: sensitive_data.host_certificates[i] = NULL;
1601:
1602: for (i = 0; i < options.num_host_cert_files; i++) {
1.430 djm 1603: if (options.host_cert_files[i] == NULL)
1604: continue;
1.512 markus 1605: if ((r = sshkey_load_public(options.host_cert_files[i],
1606: &key, NULL)) != 0) {
1607: error("Could not load host certificate \"%s\": %s",
1608: options.host_cert_files[i], ssh_err(r));
1.373 djm 1609: continue;
1610: }
1.512 markus 1611: if (!sshkey_is_cert(key)) {
1.373 djm 1612: error("Certificate file is not a certificate: %s",
1613: options.host_cert_files[i]);
1.512 markus 1614: sshkey_free(key);
1.373 djm 1615: continue;
1616: }
1617: /* Find matching private key */
1618: for (j = 0; j < options.num_host_key_files; j++) {
1.512 markus 1619: if (sshkey_equal_public(key,
1.373 djm 1620: sensitive_data.host_keys[j])) {
1621: sensitive_data.host_certificates[j] = key;
1622: break;
1623: }
1624: }
1625: if (j >= options.num_host_key_files) {
1626: error("No matching private key for certificate: %s",
1627: options.host_cert_files[i]);
1.512 markus 1628: sshkey_free(key);
1.373 djm 1629: continue;
1630: }
1631: sensitive_data.host_certificates[j] = key;
1.493 djm 1632: debug("host certificate: #%u type %d %s", j, key->type,
1.512 markus 1633: sshkey_type(key));
1.373 djm 1634: }
1.426 markus 1635:
1.244 markus 1636: if (use_privsep) {
1637: struct stat st;
1638:
1.327 deraadt 1639: if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1.244 markus 1640: fatal("Privilege separation user %s does not exist",
1641: SSH_PRIVSEP_USER);
1.500 djm 1642: endpwent();
1.244 markus 1643: if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1644: (S_ISDIR(st.st_mode) == 0))
1645: fatal("Missing privilege separation directory: %s",
1.247 stevesk 1646: _PATH_PRIVSEP_CHROOT_DIR);
1647: if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1.262 markus 1648: fatal("%s must be owned by root and not group or "
1649: "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1.358 dtucker 1650: }
1651:
1652: if (test_flag > 1) {
1.499 djm 1653: /*
1654: * If no connection info was provided by -C then use
1655: * use a blank one that will cause no predicate to match.
1656: */
1657: if (connection_info == NULL)
1.523 djm 1658: connection_info = get_connection_info(ssh, 0, 0);
1.498 dtucker 1659: parse_server_match_config(&options, connection_info);
1.358 dtucker 1660: dump_config(&options);
1.108 markus 1661: }
1.203 stevesk 1662:
1663: /* Configuration looks good, so exit if in test mode. */
1664: if (test_flag)
1665: exit(0);
1.108 markus 1666:
1.294 djm 1667: if (rexec_flag) {
1.493 djm 1668: if (rexec_argc < 0)
1669: fatal("rexec_argc %d < 0", rexec_argc);
1.329 djm 1670: rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1.493 djm 1671: for (i = 0; i < (u_int)rexec_argc; i++) {
1.294 djm 1672: debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1673: rexec_argv[i] = saved_argv[i];
1674: }
1675: rexec_argv[rexec_argc] = "-R";
1676: rexec_argv[rexec_argc + 1] = NULL;
1677: }
1.362 dtucker 1678:
1679: /* Ensure that umask disallows at least group and world write */
1680: new_umask = umask(0077) | 0022;
1681: (void) umask(new_umask);
1.294 djm 1682:
1.108 markus 1683: /* Initialize the log (it is reinitialized below in case we forked). */
1.306 dtucker 1684: if (debug_flag && (!inetd_flag || rexeced_flag))
1.64 markus 1685: log_stderr = 1;
1.138 markus 1686: log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64 markus 1687:
1.108 markus 1688: /*
1.478 dtucker 1689: * If not in debugging mode, not started from inetd and not already
1690: * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1691: * terminal, and fork. The original process exits.
1.108 markus 1692: */
1.478 dtucker 1693: already_daemon = daemonized();
1694: if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1.345 djm 1695:
1.64 markus 1696: if (daemon(0, 0) < 0)
1697: fatal("daemon() failed: %.200s", strerror(errno));
1698:
1.477 dtucker 1699: disconnect_controlling_tty();
1.64 markus 1700: }
1701: /* Reinitialize the log (because of the fork above). */
1.138 markus 1702: log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64 markus 1703:
1704: /* Chdir to the root directory so that the current disk can be
1705: unmounted if desired. */
1.401 dtucker 1706: if (chdir("/") == -1)
1707: error("chdir(\"/\"): %s", strerror(errno));
1.217 deraadt 1708:
1.178 markus 1709: /* ignore SIGPIPE */
1710: signal(SIGPIPE, SIG_IGN);
1.64 markus 1711:
1.345 djm 1712: /* Get a connection, either from inetd or a listening TCP socket */
1.64 markus 1713: if (inetd_flag) {
1.345 djm 1714: server_accept_inetd(&sock_in, &sock_out);
1.64 markus 1715: } else {
1.345 djm 1716: server_listen();
1.75 markus 1717:
1.201 markus 1718: signal(SIGHUP, sighup_handler);
1.345 djm 1719: signal(SIGCHLD, main_sigchld_handler);
1.201 markus 1720: signal(SIGTERM, sigterm_handler);
1721: signal(SIGQUIT, sigterm_handler);
1722:
1.345 djm 1723: /*
1724: * Write out the pid file after the sigterm handler
1725: * is setup and the listen sockets are bound
1726: */
1.479 dtucker 1727: if (options.pid_file != NULL && !debug_flag) {
1.345 djm 1728: FILE *f = fopen(options.pid_file, "w");
1.201 markus 1729:
1.270 djm 1730: if (f == NULL) {
1731: error("Couldn't create pid file \"%s\": %s",
1732: options.pid_file, strerror(errno));
1733: } else {
1.245 mpech 1734: fprintf(f, "%ld\n", (long) getpid());
1.64 markus 1735: fclose(f);
1736: }
1737: }
1738:
1.345 djm 1739: /* Accept a connection and return in a forked child */
1740: server_accept_loop(&sock_in, &sock_out,
1741: &newsock, config_s);
1.1 deraadt 1742: }
1743:
1.64 markus 1744: /* This is the child processing a new connection. */
1.288 markus 1745: setproctitle("%s", "[accepted]");
1.294 djm 1746:
1.300 markus 1747: /*
1748: * Create a new session and process group since the 4.4BSD
1749: * setlogin() affects the entire process group. We don't
1750: * want the child to be able to affect the parent.
1751: */
1752: if (!debug_flag && !inetd_flag && setsid() < 0)
1753: error("setsid: %.100s", strerror(errno));
1754:
1.294 djm 1755: if (rexec_flag) {
1756: int fd;
1757:
1.296 djm 1758: debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1759: sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294 djm 1760: dup2(newsock, STDIN_FILENO);
1761: dup2(STDIN_FILENO, STDOUT_FILENO);
1762: if (startup_pipe == -1)
1.296 djm 1763: close(REEXEC_STARTUP_PIPE_FD);
1.407 djm 1764: else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
1.296 djm 1765: dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1.407 djm 1766: close(startup_pipe);
1767: startup_pipe = REEXEC_STARTUP_PIPE_FD;
1768: }
1.294 djm 1769:
1.296 djm 1770: dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1.294 djm 1771: close(config_s[1]);
1.296 djm 1772:
1.294 djm 1773: execv(rexec_argv[0], rexec_argv);
1774:
1775: /* Reexec has failed, fall back and continue */
1776: error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1.296 djm 1777: recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1.294 djm 1778: log_init(__progname, options.log_level,
1779: options.log_facility, log_stderr);
1780:
1781: /* Clean up fds */
1.296 djm 1782: close(REEXEC_CONFIG_PASS_FD);
1783: newsock = sock_out = sock_in = dup(STDIN_FILENO);
1.294 djm 1784: if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1785: dup2(fd, STDIN_FILENO);
1786: dup2(fd, STDOUT_FILENO);
1787: if (fd > STDERR_FILENO)
1788: close(fd);
1789: }
1.296 djm 1790: debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1791: sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294 djm 1792: }
1.372 djm 1793:
1794: /* Executed child processes don't need these. */
1795: fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1796: fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1.64 markus 1797:
1.66 markus 1798: /*
1799: * Disable the key regeneration alarm. We will not regenerate the
1800: * key since we are no longer in a position to give it to anyone. We
1801: * will not restart on SIGHUP since it no longer makes sense.
1802: */
1.64 markus 1803: alarm(0);
1804: signal(SIGALRM, SIG_DFL);
1805: signal(SIGHUP, SIG_DFL);
1806: signal(SIGTERM, SIG_DFL);
1807: signal(SIGQUIT, SIG_DFL);
1808: signal(SIGCHLD, SIG_DFL);
1.150 markus 1809:
1.66 markus 1810: /*
1811: * Register our connection. This turns encryption off because we do
1812: * not have a key.
1813: */
1.525 ! djm 1814: if ((ssh = ssh_packet_set_connection(NULL, sock_in, sock_out)) == NULL)
! 1815: fatal("Unable to create connection");
! 1816: ssh_packet_set_server(ssh);
! 1817: active_state = ssh; /* XXX needed elsewhere */
1.492 djm 1818:
1.466 djm 1819: check_ip_options(ssh);
1.309 djm 1820:
1.492 djm 1821: /* Prepare the channels layer */
1822: channel_init_channels(ssh);
1823: channel_set_af(ssh, options.address_family);
1824: process_permitopen(ssh, &options);
1825:
1.309 djm 1826: /* Set SO_KEEPALIVE if requested. */
1.525 ! djm 1827: if (options.tcp_keep_alive && ssh_packet_connection_is_on_socket(ssh) &&
1.309 djm 1828: setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1829: error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.1 deraadt 1830:
1.466 djm 1831: if ((remote_port = ssh_remote_port(ssh)) < 0) {
1832: debug("ssh_remote_port failed");
1.310 markus 1833: cleanup_exit(255);
1834: }
1.316 dtucker 1835:
1836: /*
1.331 markus 1837: * The rest of the code depends on the fact that
1.466 djm 1838: * ssh_remote_ipaddr() caches the remote ip, even if
1.331 markus 1839: * the socket goes away.
1840: */
1.466 djm 1841: remote_ip = ssh_remote_ipaddr(ssh);
1.209 markus 1842:
1.496 djm 1843: rdomain = ssh_packet_rdomain_in(ssh);
1844:
1.64 markus 1845: /* Log the connection. */
1.447 dtucker 1846: laddr = get_local_ipaddr(sock_in);
1.497 djm 1847: verbose("Connection from %s port %d on %s port %d%s%s%s",
1.496 djm 1848: remote_ip, remote_port, laddr, ssh_local_port(ssh),
1.497 djm 1849: rdomain == NULL ? "" : " rdomain \"",
1850: rdomain == NULL ? "" : rdomain,
1851: rdomain == NULL ? "" : "\"");
1.447 dtucker 1852: free(laddr);
1.1 deraadt 1853:
1.66 markus 1854: /*
1.317 djm 1855: * We don't want to listen forever unless the other side
1.66 markus 1856: * successfully authenticates itself. So we set up an alarm which is
1857: * cleared after successful authentication. A limit of zero
1.317 djm 1858: * indicates no limit. Note that we don't set the alarm in debugging
1.66 markus 1859: * mode; it is just annoying to have the server exit just when you
1860: * are about to discover the bug.
1861: */
1.64 markus 1862: signal(SIGALRM, grace_alarm_handler);
1863: if (!debug_flag)
1864: alarm(options.login_grace_time);
1865:
1.520 djm 1866: if (kex_exchange_identification(ssh, -1, options.version_addendum) != 0)
1867: cleanup_exit(255); /* error already logged */
1868:
1.525 ! djm 1869: ssh_packet_set_nonblocking(ssh);
1.1 deraadt 1870:
1.278 markus 1871: /* allocate authentication context */
1.329 djm 1872: authctxt = xcalloc(1, sizeof(*authctxt));
1.525 ! djm 1873: ssh->authctxt = authctxt;
1.278 markus 1874:
1875: /* XXX global for cleanup, access from other modules */
1876: the_authctxt = authctxt;
1.506 djm 1877:
1878: /* Set default key authentication options */
1879: if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
1880: fatal("allocation failed");
1.278 markus 1881:
1.307 otto 1882: /* prepare buffer to collect messages to display to user after login */
1.510 markus 1883: if ((loginmsg = sshbuf_new()) == NULL)
1884: fatal("%s: sshbuf_new failed", __func__);
1.374 dtucker 1885: auth_debug_reset();
1.307 otto 1886:
1.404 markus 1887: if (use_privsep) {
1.525 ! djm 1888: if (privsep_preauth(ssh) == 1)
1.237 markus 1889: goto authenticated;
1.472 markus 1890: } else if (have_agent) {
1.432 djm 1891: if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
1892: error("Unable to get agent socket: %s", ssh_err(r));
1.433 djm 1893: have_agent = 0;
1.432 djm 1894: }
1895: }
1.231 provos 1896:
1.77 markus 1897: /* perform the key exchange */
1898: /* authenticate user and start session */
1.525 ! djm 1899: do_ssh2_kex(ssh);
1.524 djm 1900: do_authentication2(ssh);
1.472 markus 1901:
1.237 markus 1902: /*
1903: * If we use privilege separation, the unprivileged child transfers
1904: * the current keystate and exits
1905: */
1906: if (use_privsep) {
1.242 mouring 1907: mm_send_keystate(pmonitor);
1.525 ! djm 1908: ssh_packet_clear_keys(ssh);
1.231 provos 1909: exit(0);
1.237 markus 1910: }
1.231 provos 1911:
1912: authenticated:
1.318 djm 1913: /*
1914: * Cancel the alarm we set to limit the time taken for
1915: * authentication.
1916: */
1917: alarm(0);
1918: signal(SIGALRM, SIG_DFL);
1.347 markus 1919: authctxt->authenticated = 1;
1.318 djm 1920: if (startup_pipe != -1) {
1921: close(startup_pipe);
1922: startup_pipe = -1;
1923: }
1.495 djm 1924:
1925: if (options.routing_domain != NULL)
1926: set_process_rdomain(ssh, options.routing_domain);
1.318 djm 1927:
1.234 markus 1928: /*
1.231 provos 1929: * In privilege separation, we fork another child and prepare
1930: * file descriptor passing.
1931: */
1932: if (use_privsep) {
1.525 ! djm 1933: privsep_postauth(ssh, authctxt);
1.237 markus 1934: /* the monitor process [priv] will not return */
1.231 provos 1935: }
1.360 dtucker 1936:
1.525 ! djm 1937: ssh_packet_set_timeout(ssh, options.client_alive_interval,
1.360 dtucker 1938: options.client_alive_count_max);
1.439 djm 1939:
1940: /* Try to send all our hostkeys to the client */
1.492 djm 1941: notify_hostkeys(ssh);
1.230 provos 1942:
1.278 markus 1943: /* Start session. */
1.492 djm 1944: do_authenticated(ssh, authctxt);
1.230 provos 1945:
1.64 markus 1946: /* The connection has been terminated. */
1.525 ! djm 1947: ssh_packet_get_bytes(ssh, &ibytes, &obytes);
1.381 djm 1948: verbose("Transferred: sent %llu, received %llu bytes",
1949: (unsigned long long)obytes, (unsigned long long)ibytes);
1.364 markus 1950:
1951: verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1.525 ! djm 1952: ssh_packet_close(ssh);
1.231 provos 1953:
1954: if (use_privsep)
1955: mm_terminate();
1956:
1.64 markus 1957: exit(0);
1.1 deraadt 1958: }
1.98 markus 1959:
1.435 markus 1960: int
1.488 markus 1961: sshd_hostkey_sign(struct sshkey *privkey, struct sshkey *pubkey,
1.512 markus 1962: u_char **signature, size_t *slenp, const u_char *data, size_t dlen,
1.488 markus 1963: const char *alg, u_int flag)
1.404 markus 1964: {
1.432 djm 1965: int r;
1966:
1.404 markus 1967: if (privkey) {
1.512 markus 1968: if (PRIVSEP(sshkey_sign(privkey, signature, slenp, data, dlen,
1969: alg, datafellows)) < 0)
1.404 markus 1970: fatal("%s: key_sign failed", __func__);
1971: } else if (use_privsep) {
1.512 markus 1972: if (mm_sshkey_sign(pubkey, signature, slenp, data, dlen,
1973: alg, datafellows) < 0)
1.404 markus 1974: fatal("%s: pubkey_sign failed", __func__);
1975: } else {
1.512 markus 1976: if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slenp,
1.461 markus 1977: data, dlen, alg, datafellows)) != 0)
1.432 djm 1978: fatal("%s: ssh_agent_sign failed: %s",
1979: __func__, ssh_err(r));
1.404 markus 1980: }
1.435 markus 1981: return 0;
1.404 markus 1982: }
1983:
1.452 djm 1984: /* SSH2 key exchange */
1.200 itojun 1985: static void
1.525 ! djm 1986: do_ssh2_kex(struct ssh *ssh)
1.98 markus 1987: {
1.422 markus 1988: char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
1.435 markus 1989: struct kex *kex;
1.437 markus 1990: int r;
1.102 markus 1991:
1.457 djm 1992: myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
1.514 djm 1993: options.kex_algorithms);
1.457 djm 1994: myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
1.514 djm 1995: options.ciphers);
1.457 djm 1996: myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
1.514 djm 1997: options.ciphers);
1.457 djm 1998: myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1999: myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2000:
1.312 markus 2001: if (options.compression == COMP_NONE) {
1.246 markus 2002: myproposal[PROPOSAL_COMP_ALGS_CTOS] =
1.470 dtucker 2003: myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1.102 markus 2004: }
1.400 dtucker 2005:
2006: if (options.rekey_limit || options.rekey_interval)
1.525 ! djm 2007: ssh_packet_set_rekey_limits(ssh, options.rekey_limit,
1.481 dtucker 2008: options.rekey_interval);
1.327 deraadt 2009:
1.413 djm 2010: myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
1.514 djm 2011: list_hostkey_types());
1.134 markus 2012:
1.189 markus 2013: /* start key exchange */
1.525 ! djm 2014: if ((r = kex_setup(ssh, myproposal)) != 0)
1.437 markus 2015: fatal("kex_setup: %s", ssh_err(r));
1.525 ! djm 2016: kex = ssh->kex;
1.426 markus 2017: #ifdef WITH_OPENSSL
1.263 markus 2018: kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1.292 djm 2019: kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1.468 djm 2020: kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
2021: kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
2022: kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
1.263 markus 2023: kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1.324 djm 2024: kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1.378 djm 2025: kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1.426 markus 2026: #endif
1.410 markus 2027: kex->kex[KEX_C25519_SHA256] = kexc25519_server;
1.373 djm 2028: kex->load_host_public_key=&get_hostkey_public_by_type;
2029: kex->load_host_private_key=&get_hostkey_private_by_type;
1.231 provos 2030: kex->host_key_index=&get_hostkey_index;
1.404 markus 2031: kex->sign = sshd_hostkey_sign;
1.189 markus 2032:
1.525 ! djm 2033: ssh_dispatch_run_fatal(ssh, DISPATCH_BLOCK, &kex->done);
1.187 markus 2034:
2035: session_id2 = kex->session_id;
2036: session_id2_len = kex->session_id_len;
1.129 provos 2037:
2038: #ifdef DEBUG_KEXDH
2039: /* send 1st encrypted/maced/compressed message */
2040: packet_start(SSH2_MSG_IGNORE);
2041: packet_put_cstring("markus");
2042: packet_send();
2043: packet_write_wait();
2044: #endif
1.186 markus 2045: debug("KEX done");
1.278 markus 2046: }
2047:
2048: /* server specific fatal cleanup */
2049: void
2050: cleanup_exit(int i)
2051: {
1.492 djm 2052: struct ssh *ssh = active_state; /* XXX */
2053:
1.386 djm 2054: if (the_authctxt) {
1.492 djm 2055: do_cleanup(ssh, the_authctxt);
1.423 djm 2056: if (use_privsep && privsep_is_preauth &&
2057: pmonitor != NULL && pmonitor->m_pid > 1) {
1.386 djm 2058: debug("Killing privsep child %d", pmonitor->m_pid);
2059: if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
1.388 djm 2060: errno != ESRCH)
1.386 djm 2061: error("%s: kill(%d): %s", __func__,
2062: pmonitor->m_pid, strerror(errno));
2063: }
2064: }
1.278 markus 2065: _exit(i);
1.1 deraadt 2066: }