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