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