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