Annotation of src/usr.bin/ssh/sshd.c, Revision 1.395
1.395 ! djm 1: /* $OpenBSD: sshd.c,v 1.394 2012/10/30 21:29:55 djm Exp $ */
1.86 markus 2: /*
1.65 deraadt 3: * Author: Tatu Ylonen <ylo@cs.hut.fi>
4: * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5: * All rights reserved
1.126 deraadt 6: * This program is the ssh daemon. It listens for connections from clients,
7: * and performs authentication, executes use commands or shell, and forwards
1.65 deraadt 8: * information to/from the application to the user client over an encrypted
1.126 deraadt 9: * connection. This can also handle forwarding of X11, TCP/IP, and
10: * authentication agent connections.
1.98 markus 11: *
1.126 deraadt 12: * As far as I am concerned, the code I have written for this software
13: * can be used freely for any purpose. Any derived versions of this
14: * software must be clearly marked as such, and if the derived work is
15: * incompatible with the protocol description in the RFC file, it must be
16: * called by a name other than "ssh" or "Secure Shell".
17: *
18: * SSH2 implementation:
1.231 provos 19: * Privilege Separation:
1.126 deraadt 20: *
1.231 provos 21: * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22: * Copyright (c) 2002 Niels Provos. All rights reserved.
1.126 deraadt 23: *
24: * Redistribution and use in source and binary forms, with or without
25: * modification, are permitted provided that the following conditions
26: * are met:
27: * 1. Redistributions of source code must retain the above copyright
28: * notice, this list of conditions and the following disclaimer.
29: * 2. Redistributions in binary form must reproduce the above copyright
30: * notice, this list of conditions and the following disclaimer in the
31: * documentation and/or other materials provided with the distribution.
32: *
33: * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34: * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36: * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37: * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38: * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39: * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40: * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41: * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42: * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1.65 deraadt 43: */
1.1 deraadt 44:
1.343 deraadt 45: #include <sys/types.h>
1.320 stevesk 46: #include <sys/ioctl.h>
1.321 stevesk 47: #include <sys/wait.h>
1.343 deraadt 48: #include <sys/tree.h>
1.323 stevesk 49: #include <sys/stat.h>
1.334 stevesk 50: #include <sys/socket.h>
1.340 stevesk 51: #include <sys/time.h>
1.357 djm 52: #include <sys/queue.h>
1.319 stevesk 53:
1.336 stevesk 54: #include <errno.h>
1.335 stevesk 55: #include <fcntl.h>
1.338 stevesk 56: #include <netdb.h>
1.319 stevesk 57: #include <paths.h>
1.333 stevesk 58: #include <pwd.h>
1.322 stevesk 59: #include <signal.h>
1.342 stevesk 60: #include <stdio.h>
1.341 stevesk 61: #include <stdlib.h>
1.339 stevesk 62: #include <string.h>
1.344 dtucker 63: #include <unistd.h>
1.1 deraadt 64:
1.155 markus 65: #include <openssl/dh.h>
66: #include <openssl/bn.h>
1.226 markus 67: #include <openssl/md5.h>
1.231 provos 68: #include <openssl/rand.h>
1.155 markus 69:
1.343 deraadt 70: #include "xmalloc.h"
1.155 markus 71: #include "ssh.h"
72: #include "ssh1.h"
73: #include "ssh2.h"
1.1 deraadt 74: #include "rsa.h"
1.171 djm 75: #include "sshpty.h"
1.1 deraadt 76: #include "packet.h"
1.155 markus 77: #include "log.h"
1.343 deraadt 78: #include "buffer.h"
1.1 deraadt 79: #include "servconf.h"
80: #include "uidswap.h"
1.33 markus 81: #include "compat.h"
1.155 markus 82: #include "cipher.h"
1.343 deraadt 83: #include "key.h"
1.98 markus 84: #include "kex.h"
1.129 provos 85: #include "dh.h"
1.98 markus 86: #include "myproposal.h"
1.108 markus 87: #include "authfile.h"
1.154 markus 88: #include "pathnames.h"
1.155 markus 89: #include "atomicio.h"
90: #include "canohost.h"
1.343 deraadt 91: #include "hostfile.h"
1.155 markus 92: #include "auth.h"
93: #include "misc.h"
1.294 djm 94: #include "msg.h"
1.186 markus 95: #include "dispatch.h"
1.206 stevesk 96: #include "channels.h"
1.230 provos 97: #include "session.h"
1.231 provos 98: #include "monitor_mm.h"
99: #include "monitor.h"
1.343 deraadt 100: #ifdef GSSAPI
101: #include "ssh-gss.h"
102: #endif
1.231 provos 103: #include "monitor_wrap.h"
1.367 andreas 104: #include "roaming.h"
1.385 djm 105: #include "ssh-sandbox.h"
1.332 stevesk 106: #include "version.h"
1.1 deraadt 107:
108: #ifdef LIBWRAP
109: #include <tcpd.h>
110: #include <syslog.h>
111: int allow_severity = LOG_INFO;
112: int deny_severity = LOG_WARNING;
113: #endif /* LIBWRAP */
114:
115: #ifndef O_NOCTTY
116: #define O_NOCTTY 0
117: #endif
118:
1.296 djm 119: /* Re-exec fds */
120: #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
121: #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
122: #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
123: #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
124:
1.138 markus 125: extern char *__progname;
126:
1.1 deraadt 127: /* Server configuration options. */
128: ServerOptions options;
129:
130: /* Name of the server configuration file. */
1.154 markus 131: char *config_file_name = _PATH_SERVER_CONFIG_FILE;
1.1 deraadt 132:
1.105 markus 133: /*
1.65 deraadt 134: * Debug mode flag. This can be set on the command line. If debug
135: * mode is enabled, extra debugging output will be sent to the system
136: * log, the daemon will not go to background, and will exit after processing
137: * the first connection.
138: */
1.1 deraadt 139: int debug_flag = 0;
140:
1.203 stevesk 141: /* Flag indicating that the daemon should only test the configuration and keys. */
142: int test_flag = 0;
143:
1.1 deraadt 144: /* Flag indicating that the daemon is being started from inetd. */
145: int inetd_flag = 0;
146:
1.135 markus 147: /* Flag indicating that sshd should not detach and become a daemon. */
148: int no_daemon_flag = 0;
149:
1.47 markus 150: /* debug goes to stderr unless inetd_flag is set */
151: int log_stderr = 0;
152:
1.1 deraadt 153: /* Saved arguments to main(). */
154: char **saved_argv;
155:
1.294 djm 156: /* re-exec */
157: int rexeced_flag = 0;
158: int rexec_flag = 1;
159: int rexec_argc = 0;
160: char **rexec_argv;
161:
1.66 markus 162: /*
1.75 markus 163: * The sockets that the server is listening; this is used in the SIGHUP
164: * signal handler.
1.66 markus 165: */
1.75 markus 166: #define MAX_LISTEN_SOCKS 16
167: int listen_socks[MAX_LISTEN_SOCKS];
168: int num_listen_socks = 0;
1.1 deraadt 169:
1.66 markus 170: /*
171: * the client's version string, passed by sshd2 in compat mode. if != NULL,
172: * sshd will skip the version-number exchange
173: */
1.61 markus 174: char *client_version_string = NULL;
1.96 markus 175: char *server_version_string = NULL;
1.1 deraadt 176:
1.189 markus 177: /* for rekeying XXX fixme */
178: Kex *xxx_kex;
179:
1.66 markus 180: /*
181: * Any really sensitive data in the application is contained in this
182: * structure. The idea is that this structure could be locked into memory so
183: * that the pages do not get written into swap. However, there are some
184: * problems. The private key contains BIGNUMs, and we do not (in principle)
185: * have access to the internals of them, and locking just the structure is
186: * not very useful. Currently, memory locking is not implemented.
187: */
1.64 markus 188: struct {
1.174 deraadt 189: Key *server_key; /* ephemeral server key */
1.134 markus 190: Key *ssh1_host_key; /* ssh1 host key */
191: Key **host_keys; /* all private host keys */
1.373 djm 192: Key **host_certificates; /* all public host certificates */
1.134 markus 193: int have_ssh1_key;
194: int have_ssh2_key;
1.169 markus 195: u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
1.1 deraadt 196: } sensitive_data;
197:
1.66 markus 198: /*
1.151 markus 199: * Flag indicating whether the RSA server key needs to be regenerated.
200: * Is set in the SIGALRM handler and cleared when the key is regenerated.
1.66 markus 201: */
1.212 markus 202: static volatile sig_atomic_t key_do_regen = 0;
1.1 deraadt 203:
1.199 markus 204: /* This is set to true when a signal is received. */
1.212 markus 205: static volatile sig_atomic_t received_sighup = 0;
206: static volatile sig_atomic_t received_sigterm = 0;
1.1 deraadt 207:
1.96 markus 208: /* session identifier, used by RSA-auth */
1.140 markus 209: u_char session_id[16];
1.96 markus 210:
1.108 markus 211: /* same for ssh2 */
1.140 markus 212: u_char *session_id2 = NULL;
1.269 markus 213: u_int session_id2_len = 0;
1.108 markus 214:
1.125 markus 215: /* record remote hostname or ip */
1.140 markus 216: u_int utmp_len = MAXHOSTNAMELEN;
1.125 markus 217:
1.211 markus 218: /* options.max_startup sized array of fd ints */
219: int *startup_pipes = NULL;
220: int startup_pipe; /* in child */
221:
1.231 provos 222: /* variables used for privilege separation */
1.337 dtucker 223: int use_privsep = -1;
1.285 dtucker 224: struct monitor *pmonitor = NULL;
1.386 djm 225: int privsep_is_preauth = 1;
1.231 provos 226:
1.278 markus 227: /* global authentication context */
228: Authctxt *the_authctxt = NULL;
229:
1.337 dtucker 230: /* sshd_config buffer */
231: Buffer cfg;
232:
1.299 dtucker 233: /* message to be displayed after login */
234: Buffer loginmsg;
235:
1.1 deraadt 236: /* Prototypes for various functions defined later in this file. */
1.200 itojun 237: void destroy_sensitive_data(void);
1.231 provos 238: void demote_sensitive_data(void);
1.87 markus 239:
1.200 itojun 240: static void do_ssh1_kex(void);
241: static void do_ssh2_kex(void);
1.129 provos 242:
1.87 markus 243: /*
1.75 markus 244: * Close all listening sockets
245: */
1.200 itojun 246: static void
1.75 markus 247: close_listen_socks(void)
248: {
249: int i;
1.250 deraadt 250:
1.75 markus 251: for (i = 0; i < num_listen_socks; i++)
252: close(listen_socks[i]);
253: num_listen_socks = -1;
254: }
255:
1.211 markus 256: static void
257: close_startup_pipes(void)
258: {
259: int i;
1.250 deraadt 260:
1.211 markus 261: if (startup_pipes)
262: for (i = 0; i < options.max_startups; i++)
263: if (startup_pipes[i] != -1)
264: close(startup_pipes[i]);
265: }
266:
1.75 markus 267: /*
1.65 deraadt 268: * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
269: * the effect is to reread the configuration file (and to regenerate
270: * the server key).
271: */
1.327 deraadt 272:
273: /*ARGSUSED*/
1.200 itojun 274: static void
1.64 markus 275: sighup_handler(int sig)
1.1 deraadt 276: {
1.210 deraadt 277: int save_errno = errno;
278:
1.64 markus 279: received_sighup = 1;
280: signal(SIGHUP, sighup_handler);
1.210 deraadt 281: errno = save_errno;
1.1 deraadt 282: }
283:
1.65 deraadt 284: /*
285: * Called from the main program after receiving SIGHUP.
286: * Restarts the server.
287: */
1.200 itojun 288: static void
1.165 itojun 289: sighup_restart(void)
1.1 deraadt 290: {
1.264 itojun 291: logit("Received SIGHUP; restarting.");
1.75 markus 292: close_listen_socks();
1.211 markus 293: close_startup_pipes();
1.349 dtucker 294: alarm(0); /* alarm timer persists across exec */
1.369 dtucker 295: signal(SIGHUP, SIG_IGN); /* will be restored after exec */
1.64 markus 296: execv(saved_argv[0], saved_argv);
1.264 itojun 297: logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
1.250 deraadt 298: strerror(errno));
1.64 markus 299: exit(1);
1.1 deraadt 300: }
301:
1.65 deraadt 302: /*
303: * Generic signal handler for terminating signals in the master daemon.
304: */
1.327 deraadt 305: /*ARGSUSED*/
1.200 itojun 306: static void
1.64 markus 307: sigterm_handler(int sig)
1.1 deraadt 308: {
1.199 markus 309: received_sigterm = sig;
1.1 deraadt 310: }
311:
1.65 deraadt 312: /*
313: * SIGCHLD handler. This is called whenever a child dies. This will then
1.199 markus 314: * reap any zombies left by exited children.
1.65 deraadt 315: */
1.327 deraadt 316: /*ARGSUSED*/
1.200 itojun 317: static void
1.64 markus 318: main_sigchld_handler(int sig)
1.1 deraadt 319: {
1.250 deraadt 320: int save_errno = errno;
1.239 markus 321: pid_t pid;
1.64 markus 322: int status;
1.60 deraadt 323:
1.239 markus 324: while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
325: (pid < 0 && errno == EINTR))
1.64 markus 326: ;
1.60 deraadt 327:
1.64 markus 328: signal(SIGCHLD, main_sigchld_handler);
329: errno = save_errno;
1.1 deraadt 330: }
331:
1.65 deraadt 332: /*
333: * Signal handler for the alarm after the login grace period has expired.
334: */
1.327 deraadt 335: /*ARGSUSED*/
1.200 itojun 336: static void
1.64 markus 337: grace_alarm_handler(int sig)
1.1 deraadt 338: {
1.285 dtucker 339: if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
340: kill(pmonitor->m_pid, SIGALRM);
1.394 djm 341:
342: /*
343: * Try to kill any processes that we have spawned, E.g. authorized
344: * keys command helpers.
345: */
346: if (getpgid(0) == getpid()) {
347: signal(SIGTERM, SIG_IGN);
348: killpg(0, SIGTERM);
349: }
1.285 dtucker 350:
1.64 markus 351: /* Log error and exit. */
1.346 deraadt 352: sigdie("Timeout before authentication for %s", get_remote_ipaddr());
1.62 markus 353: }
354:
1.65 deraadt 355: /*
356: * Signal handler for the key regeneration alarm. Note that this
357: * alarm only occurs in the daemon waiting for connections, and it does not
358: * do anything with the private key or random state before forking.
359: * Thus there should be no concurrency control/asynchronous execution
360: * problems.
361: */
1.200 itojun 362: static void
1.174 deraadt 363: generate_ephemeral_server_key(void)
1.134 markus 364: {
1.191 markus 365: verbose("Generating %s%d bit RSA key.",
1.185 djm 366: sensitive_data.server_key ? "new " : "", options.server_key_bits);
1.134 markus 367: if (sensitive_data.server_key != NULL)
368: key_free(sensitive_data.server_key);
1.191 markus 369: sensitive_data.server_key = key_generate(KEY_RSA1,
1.185 djm 370: options.server_key_bits);
371: verbose("RSA key generation complete.");
1.169 markus 372:
1.356 djm 373: arc4random_buf(sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1.134 markus 374: arc4random_stir();
375: }
1.147 deraadt 376:
1.327 deraadt 377: /*ARGSUSED*/
1.200 itojun 378: static void
1.64 markus 379: key_regeneration_alarm(int sig)
1.1 deraadt 380: {
1.64 markus 381: int save_errno = errno;
1.250 deraadt 382:
1.151 markus 383: signal(SIGALRM, SIG_DFL);
1.64 markus 384: errno = save_errno;
1.151 markus 385: key_do_regen = 1;
1.98 markus 386: }
387:
1.200 itojun 388: static void
1.96 markus 389: sshd_exchange_identification(int sock_in, int sock_out)
390: {
1.311 djm 391: u_int i;
392: int mismatch;
1.96 markus 393: int remote_major, remote_minor;
1.102 markus 394: int major, minor;
1.363 dtucker 395: char *s, *newline = "\n";
1.96 markus 396: char buf[256]; /* Must not be larger than remote_version. */
397: char remote_version[256]; /* Must be at least as big as buf. */
398:
1.103 markus 399: if ((options.protocol & SSH_PROTO_1) &&
400: (options.protocol & SSH_PROTO_2)) {
1.102 markus 401: major = PROTOCOL_MAJOR_1;
402: minor = 99;
403: } else if (options.protocol & SSH_PROTO_2) {
404: major = PROTOCOL_MAJOR_2;
405: minor = PROTOCOL_MINOR_2;
1.363 dtucker 406: newline = "\r\n";
1.102 markus 407: } else {
408: major = PROTOCOL_MAJOR_1;
409: minor = PROTOCOL_MINOR_1;
410: }
1.390 djm 411:
412: xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s%s",
413: major, minor, SSH_VERSION,
414: *options.version_addendum == '\0' ? "" : " ",
415: options.version_addendum, newline);
1.96 markus 416:
1.272 markus 417: /* Send our protocol version identification. */
1.367 andreas 418: if (roaming_atomicio(vwrite, sock_out, server_version_string,
1.272 markus 419: strlen(server_version_string))
420: != strlen(server_version_string)) {
421: logit("Could not write ident string to %s", get_remote_ipaddr());
1.278 markus 422: cleanup_exit(255);
1.272 markus 423: }
424:
425: /* Read other sides version identification. */
426: memset(buf, 0, sizeof(buf));
427: for (i = 0; i < sizeof(buf) - 1; i++) {
1.367 andreas 428: if (roaming_atomicio(read, sock_in, &buf[i], 1) != 1) {
1.272 markus 429: logit("Did not receive identification string from %s",
430: get_remote_ipaddr());
1.278 markus 431: cleanup_exit(255);
1.96 markus 432: }
1.272 markus 433: if (buf[i] == '\r') {
434: buf[i] = 0;
435: /* Kludge for F-Secure Macintosh < 1.0.2 */
436: if (i == 12 &&
437: strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
1.96 markus 438: break;
1.272 markus 439: continue;
440: }
441: if (buf[i] == '\n') {
442: buf[i] = 0;
443: break;
1.96 markus 444: }
445: }
1.272 markus 446: buf[sizeof(buf) - 1] = 0;
447: client_version_string = xstrdup(buf);
1.96 markus 448:
449: /*
450: * Check that the versions match. In future this might accept
451: * several versions and set appropriate flags to handle them.
452: */
453: if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
454: &remote_major, &remote_minor, remote_version) != 3) {
1.105 markus 455: s = "Protocol mismatch.\n";
1.271 deraadt 456: (void) atomicio(vwrite, sock_out, s, strlen(s));
1.96 markus 457: close(sock_in);
458: close(sock_out);
1.264 itojun 459: logit("Bad protocol version identification '%.100s' from %s",
1.96 markus 460: client_version_string, get_remote_ipaddr());
1.278 markus 461: cleanup_exit(255);
1.96 markus 462: }
463: debug("Client protocol version %d.%d; client software version %.100s",
1.217 deraadt 464: remote_major, remote_minor, remote_version);
1.96 markus 465:
1.98 markus 466: compat_datafellows(remote_version);
1.260 mickey 467:
468: if (datafellows & SSH_BUG_PROBE) {
1.264 itojun 469: logit("probed from %s with %s. Don't panic.",
1.260 mickey 470: get_remote_ipaddr(), client_version_string);
1.278 markus 471: cleanup_exit(255);
1.260 mickey 472: }
1.175 deraadt 473:
474: if (datafellows & SSH_BUG_SCANNER) {
1.264 itojun 475: logit("scanned from %s with %s. Don't panic.",
1.175 deraadt 476: get_remote_ipaddr(), client_version_string);
1.278 markus 477: cleanup_exit(255);
1.175 deraadt 478: }
1.98 markus 479:
1.102 markus 480: mismatch = 0;
1.214 deraadt 481: switch (remote_major) {
1.96 markus 482: case 1:
1.108 markus 483: if (remote_minor == 99) {
484: if (options.protocol & SSH_PROTO_2)
485: enable_compat20();
486: else
487: mismatch = 1;
488: break;
489: }
1.102 markus 490: if (!(options.protocol & SSH_PROTO_1)) {
491: mismatch = 1;
492: break;
493: }
1.96 markus 494: if (remote_minor < 3) {
1.121 provos 495: packet_disconnect("Your ssh version is too old and "
1.96 markus 496: "is no longer supported. Please install a newer version.");
497: } else if (remote_minor == 3) {
498: /* note that this disables agent-forwarding */
499: enable_compat13();
500: }
1.102 markus 501: break;
1.98 markus 502: case 2:
1.102 markus 503: if (options.protocol & SSH_PROTO_2) {
1.98 markus 504: enable_compat20();
505: break;
506: }
1.99 markus 507: /* FALLTHROUGH */
1.105 markus 508: default:
1.102 markus 509: mismatch = 1;
510: break;
511: }
512: chop(server_version_string);
513: debug("Local version string %.200s", server_version_string);
514:
515: if (mismatch) {
1.96 markus 516: s = "Protocol major versions differ.\n";
1.271 deraadt 517: (void) atomicio(vwrite, sock_out, s, strlen(s));
1.96 markus 518: close(sock_in);
519: close(sock_out);
1.264 itojun 520: logit("Protocol major versions differ for %s: %.200s vs. %.200s",
1.102 markus 521: get_remote_ipaddr(),
522: server_version_string, client_version_string);
1.278 markus 523: cleanup_exit(255);
1.96 markus 524: }
1.108 markus 525: }
526:
1.134 markus 527: /* Destroy the host and server keys. They will no longer be needed. */
1.108 markus 528: void
529: destroy_sensitive_data(void)
530: {
1.134 markus 531: int i;
532:
533: if (sensitive_data.server_key) {
534: key_free(sensitive_data.server_key);
535: sensitive_data.server_key = NULL;
536: }
1.217 deraadt 537: for (i = 0; i < options.num_host_key_files; i++) {
1.134 markus 538: if (sensitive_data.host_keys[i]) {
539: key_free(sensitive_data.host_keys[i]);
540: sensitive_data.host_keys[i] = NULL;
541: }
1.373 djm 542: if (sensitive_data.host_certificates[i]) {
543: key_free(sensitive_data.host_certificates[i]);
544: sensitive_data.host_certificates[i] = NULL;
545: }
1.134 markus 546: }
547: sensitive_data.ssh1_host_key = NULL;
1.169 markus 548: memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
1.134 markus 549: }
550:
1.231 provos 551: /* Demote private to public keys for network child */
552: void
553: demote_sensitive_data(void)
554: {
555: Key *tmp;
556: int i;
557:
558: if (sensitive_data.server_key) {
559: tmp = key_demote(sensitive_data.server_key);
560: key_free(sensitive_data.server_key);
561: sensitive_data.server_key = tmp;
562: }
563:
564: for (i = 0; i < options.num_host_key_files; i++) {
565: if (sensitive_data.host_keys[i]) {
566: tmp = key_demote(sensitive_data.host_keys[i]);
567: key_free(sensitive_data.host_keys[i]);
568: sensitive_data.host_keys[i] = tmp;
569: if (tmp->type == KEY_RSA1)
570: sensitive_data.ssh1_host_key = tmp;
571: }
1.373 djm 572: /* Certs do not need demotion */
1.231 provos 573: }
574:
575: /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
576: }
577:
1.233 markus 578: static void
1.231 provos 579: privsep_preauth_child(void)
580: {
1.254 deraadt 581: u_int32_t rnd[256];
1.253 deraadt 582: gid_t gidset[1];
1.250 deraadt 583: struct passwd *pw;
1.231 provos 584:
585: /* Enable challenge-response authentication for privilege separation */
586: privsep_challenge_enable();
587:
1.354 djm 588: arc4random_stir();
1.356 djm 589: arc4random_buf(rnd, sizeof(rnd));
1.254 deraadt 590: RAND_seed(rnd, sizeof(rnd));
1.231 provos 591:
592: /* Demote the private keys to public keys. */
593: demote_sensitive_data();
594:
1.235 stevesk 595: if ((pw = getpwnam(SSH_PRIVSEP_USER)) == NULL)
1.240 djm 596: fatal("Privilege separation user %s does not exist",
597: SSH_PRIVSEP_USER);
1.235 stevesk 598: memset(pw->pw_passwd, 0, strlen(pw->pw_passwd));
599: endpwent();
600:
1.255 deraadt 601: /* Change our root directory */
1.232 stevesk 602: if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
603: fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
604: strerror(errno));
1.231 provos 605: if (chdir("/") == -1)
1.236 stevesk 606: fatal("chdir(\"/\"): %s", strerror(errno));
1.234 markus 607:
1.231 provos 608: /* Drop our privileges */
1.235 stevesk 609: debug3("privsep user:group %u:%u", (u_int)pw->pw_uid,
610: (u_int)pw->pw_gid);
1.251 markus 611: #if 0
1.287 djm 612: /* XXX not ready, too heavy after chroot */
1.235 stevesk 613: do_setusercontext(pw);
1.251 markus 614: #else
615: gidset[0] = pw->pw_gid;
616: if (setgroups(1, gidset) < 0)
617: fatal("setgroups: %.100s", strerror(errno));
618: permanently_set_uid(pw);
619: #endif
1.231 provos 620: }
621:
1.278 markus 622: static int
623: privsep_preauth(Authctxt *authctxt)
1.237 markus 624: {
625: int status;
626: pid_t pid;
1.384 djm 627: struct ssh_sandbox *box = NULL;
1.237 markus 628:
629: /* Set up unprivileged child process to deal with network data */
1.242 mouring 630: pmonitor = monitor_init();
1.237 markus 631: /* Store a pointer to the kex for later rekeying */
1.242 mouring 632: pmonitor->m_pkex = &xxx_kex;
1.237 markus 633:
1.393 djm 634: if (use_privsep == PRIVSEP_ON)
1.384 djm 635: box = ssh_sandbox_init();
1.237 markus 636: pid = fork();
637: if (pid == -1) {
638: fatal("fork of unprivileged child failed");
639: } else if (pid != 0) {
1.245 mpech 640: debug2("Network child is on pid %ld", (long)pid);
1.237 markus 641:
1.392 markus 642: pmonitor->m_pid = pid;
1.384 djm 643: if (box != NULL)
644: ssh_sandbox_parent_preauth(box, pid);
1.278 markus 645: monitor_child_preauth(authctxt, pmonitor);
1.237 markus 646:
647: /* Sync memory */
1.242 mouring 648: monitor_sync(pmonitor);
1.237 markus 649:
650: /* Wait for the child's exit status */
1.384 djm 651: while (waitpid(pid, &status, 0) < 0) {
1.386 djm 652: if (errno == EINTR)
653: continue;
654: pmonitor->m_pid = -1;
655: fatal("%s: waitpid: %s", __func__, strerror(errno));
1.384 djm 656: }
1.386 djm 657: privsep_is_preauth = 0;
658: pmonitor->m_pid = -1;
1.384 djm 659: if (WIFEXITED(status)) {
660: if (WEXITSTATUS(status) != 0)
661: fatal("%s: preauth child exited with status %d",
662: __func__, WEXITSTATUS(status));
663: } else if (WIFSIGNALED(status))
664: fatal("%s: preauth child terminated by signal %d",
665: __func__, WTERMSIG(status));
666: if (box != NULL)
667: ssh_sandbox_parent_finish(box);
668: return 1;
1.237 markus 669: } else {
670: /* child */
1.383 djm 671: close(pmonitor->m_sendfd);
672: close(pmonitor->m_log_recvfd);
1.237 markus 673:
1.383 djm 674: /* Arrange for logging to be sent to the monitor */
675: set_log_handler(mm_log_handler, pmonitor);
1.237 markus 676:
677: /* Demote the child */
678: if (getuid() == 0 || geteuid() == 0)
679: privsep_preauth_child();
1.238 stevesk 680: setproctitle("%s", "[net]");
1.384 djm 681: if (box != NULL)
682: ssh_sandbox_child(box);
683:
684: return 0;
1.237 markus 685: }
686: }
687:
1.233 markus 688: static void
1.237 markus 689: privsep_postauth(Authctxt *authctxt)
1.231 provos 690: {
1.354 djm 691: u_int32_t rnd[256];
692:
1.231 provos 693: if (authctxt->pw->pw_uid == 0 || options.use_login) {
694: /* File descriptor passing is broken or root login */
695: use_privsep = 0;
1.315 djm 696: goto skip;
1.231 provos 697: }
1.234 markus 698:
1.231 provos 699: /* New socket pair */
1.242 mouring 700: monitor_reinit(pmonitor);
1.231 provos 701:
1.242 mouring 702: pmonitor->m_pid = fork();
703: if (pmonitor->m_pid == -1)
1.231 provos 704: fatal("fork of unprivileged child failed");
1.242 mouring 705: else if (pmonitor->m_pid != 0) {
1.364 markus 706: verbose("User child is on pid %ld", (long)pmonitor->m_pid);
1.307 otto 707: buffer_clear(&loginmsg);
1.242 mouring 708: monitor_child_postauth(pmonitor);
1.231 provos 709:
710: /* NEVERREACHED */
711: exit(0);
712: }
713:
1.383 djm 714: /* child */
715:
1.242 mouring 716: close(pmonitor->m_sendfd);
1.383 djm 717: pmonitor->m_sendfd = -1;
1.231 provos 718:
719: /* Demote the private keys to public keys. */
720: demote_sensitive_data();
1.354 djm 721:
722: arc4random_stir();
1.356 djm 723: arc4random_buf(rnd, sizeof(rnd));
1.354 djm 724: RAND_seed(rnd, sizeof(rnd));
1.231 provos 725:
726: /* Drop privileges */
727: do_setusercontext(authctxt->pw);
728:
1.315 djm 729: skip:
1.231 provos 730: /* It is safe now to apply the key state */
1.242 mouring 731: monitor_apply_keystate(pmonitor);
1.312 markus 732:
733: /*
734: * Tell the packet layer that authentication was successful, since
735: * this information is not part of the key state.
736: */
737: packet_set_authenticated();
1.231 provos 738: }
739:
1.200 itojun 740: static char *
1.134 markus 741: list_hostkey_types(void)
742: {
1.223 markus 743: Buffer b;
1.281 jakob 744: const char *p;
745: char *ret;
1.134 markus 746: int i;
1.373 djm 747: Key *key;
1.223 markus 748:
749: buffer_init(&b);
1.217 deraadt 750: for (i = 0; i < options.num_host_key_files; i++) {
1.373 djm 751: key = sensitive_data.host_keys[i];
1.134 markus 752: if (key == NULL)
753: continue;
1.214 deraadt 754: switch (key->type) {
1.134 markus 755: case KEY_RSA:
756: case KEY_DSA:
1.378 djm 757: case KEY_ECDSA:
1.223 markus 758: if (buffer_len(&b) > 0)
759: buffer_append(&b, ",", 1);
760: p = key_ssh_name(key);
761: buffer_append(&b, p, strlen(p));
1.134 markus 762: break;
763: }
1.373 djm 764: /* If the private key has a cert peer, then list that too */
765: key = sensitive_data.host_certificates[i];
766: if (key == NULL)
767: continue;
768: switch (key->type) {
1.375 djm 769: case KEY_RSA_CERT_V00:
770: case KEY_DSA_CERT_V00:
1.373 djm 771: case KEY_RSA_CERT:
772: case KEY_DSA_CERT:
1.378 djm 773: case KEY_ECDSA_CERT:
1.373 djm 774: if (buffer_len(&b) > 0)
775: buffer_append(&b, ",", 1);
776: p = key_ssh_name(key);
777: buffer_append(&b, p, strlen(p));
778: break;
779: }
1.134 markus 780: }
1.223 markus 781: buffer_append(&b, "\0", 1);
1.281 jakob 782: ret = xstrdup(buffer_ptr(&b));
1.223 markus 783: buffer_free(&b);
1.281 jakob 784: debug("list_hostkey_types: %s", ret);
785: return ret;
1.134 markus 786: }
787:
1.373 djm 788: static Key *
789: get_hostkey_by_type(int type, int need_private)
1.134 markus 790: {
791: int i;
1.373 djm 792: Key *key;
1.250 deraadt 793:
1.217 deraadt 794: for (i = 0; i < options.num_host_key_files; i++) {
1.375 djm 795: switch (type) {
796: case KEY_RSA_CERT_V00:
797: case KEY_DSA_CERT_V00:
798: case KEY_RSA_CERT:
799: case KEY_DSA_CERT:
1.378 djm 800: case KEY_ECDSA_CERT:
1.373 djm 801: key = sensitive_data.host_certificates[i];
1.375 djm 802: break;
803: default:
1.373 djm 804: key = sensitive_data.host_keys[i];
1.375 djm 805: break;
806: }
1.134 markus 807: if (key != NULL && key->type == type)
1.373 djm 808: return need_private ?
809: sensitive_data.host_keys[i] : key;
1.134 markus 810: }
811: return NULL;
1.96 markus 812: }
813:
1.231 provos 814: Key *
1.373 djm 815: get_hostkey_public_by_type(int type)
816: {
817: return get_hostkey_by_type(type, 0);
818: }
819:
820: Key *
821: get_hostkey_private_by_type(int type)
822: {
823: return get_hostkey_by_type(type, 1);
824: }
825:
826: Key *
1.231 provos 827: get_hostkey_by_index(int ind)
828: {
829: if (ind < 0 || ind >= options.num_host_key_files)
830: return (NULL);
831: return (sensitive_data.host_keys[ind]);
832: }
833:
834: int
835: get_hostkey_index(Key *key)
836: {
837: int i;
1.250 deraadt 838:
1.231 provos 839: for (i = 0; i < options.num_host_key_files; i++) {
1.373 djm 840: if (key_is_cert(key)) {
841: if (key == sensitive_data.host_certificates[i])
842: return (i);
843: } else {
844: if (key == sensitive_data.host_keys[i])
845: return (i);
846: }
1.231 provos 847: }
848: return (-1);
849: }
850:
1.124 markus 851: /*
852: * returns 1 if connection should be dropped, 0 otherwise.
853: * dropping starts at connection #max_startups_begin with a probability
854: * of (max_startups_rate/100). the probability increases linearly until
855: * all connections are dropped for startups > max_startups
856: */
1.200 itojun 857: static int
1.124 markus 858: drop_connection(int startups)
859: {
1.303 mickey 860: int p, r;
1.124 markus 861:
862: if (startups < options.max_startups_begin)
863: return 0;
864: if (startups >= options.max_startups)
865: return 1;
866: if (options.max_startups_rate == 100)
867: return 1;
868:
869: p = 100 - options.max_startups_rate;
870: p *= startups - options.max_startups_begin;
1.303 mickey 871: p /= options.max_startups - options.max_startups_begin;
1.124 markus 872: p += options.max_startups_rate;
1.356 djm 873: r = arc4random_uniform(100);
1.124 markus 874:
1.304 djm 875: debug("drop_connection: p %d, r %d", p, r);
1.124 markus 876: return (r < p) ? 1 : 0;
877: }
878:
1.215 markus 879: static void
880: usage(void)
881: {
1.290 markus 882: fprintf(stderr, "%s, %s\n",
1.280 markus 883: SSH_VERSION, SSLeay_version(SSLEAY_VERSION));
1.289 markus 884: fprintf(stderr,
1.373 djm 885: "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
886: " [-f config_file] [-g login_grace_time] [-h host_key_file]\n"
887: " [-k key_gen_time] [-o option] [-p port] [-u len]\n"
1.289 markus 888: );
1.215 markus 889: exit(1);
890: }
891:
1.294 djm 892: static void
893: send_rexec_state(int fd, Buffer *conf)
894: {
895: Buffer m;
896:
897: debug3("%s: entering fd = %d config len %d", __func__, fd,
898: buffer_len(conf));
899:
900: /*
901: * Protocol from reexec master to child:
902: * string configuration
903: * u_int ephemeral_key_follows
904: * bignum e (only if ephemeral_key_follows == 1)
905: * bignum n "
906: * bignum d "
907: * bignum iqmp "
908: * bignum p "
909: * bignum q "
910: */
911: buffer_init(&m);
912: buffer_put_cstring(&m, buffer_ptr(conf));
913:
1.298 deraadt 914: if (sensitive_data.server_key != NULL &&
1.294 djm 915: sensitive_data.server_key->type == KEY_RSA1) {
916: buffer_put_int(&m, 1);
917: buffer_put_bignum(&m, sensitive_data.server_key->rsa->e);
918: buffer_put_bignum(&m, sensitive_data.server_key->rsa->n);
919: buffer_put_bignum(&m, sensitive_data.server_key->rsa->d);
920: buffer_put_bignum(&m, sensitive_data.server_key->rsa->iqmp);
921: buffer_put_bignum(&m, sensitive_data.server_key->rsa->p);
922: buffer_put_bignum(&m, sensitive_data.server_key->rsa->q);
923: } else
924: buffer_put_int(&m, 0);
925:
926: if (ssh_msg_send(fd, 0, &m) == -1)
927: fatal("%s: ssh_msg_send failed", __func__);
928:
929: buffer_free(&m);
930:
931: debug3("%s: done", __func__);
932: }
933:
934: static void
935: recv_rexec_state(int fd, Buffer *conf)
936: {
937: Buffer m;
938: char *cp;
939: u_int len;
940:
941: debug3("%s: entering fd = %d", __func__, fd);
942:
943: buffer_init(&m);
944:
945: if (ssh_msg_recv(fd, &m) == -1)
946: fatal("%s: ssh_msg_recv failed", __func__);
947: if (buffer_get_char(&m) != 0)
948: fatal("%s: rexec version mismatch", __func__);
949:
950: cp = buffer_get_string(&m, &len);
951: if (conf != NULL)
952: buffer_append(conf, cp, len + 1);
953: xfree(cp);
954:
955: if (buffer_get_int(&m)) {
956: if (sensitive_data.server_key != NULL)
957: key_free(sensitive_data.server_key);
958: sensitive_data.server_key = key_new_private(KEY_RSA1);
959: buffer_get_bignum(&m, sensitive_data.server_key->rsa->e);
960: buffer_get_bignum(&m, sensitive_data.server_key->rsa->n);
961: buffer_get_bignum(&m, sensitive_data.server_key->rsa->d);
962: buffer_get_bignum(&m, sensitive_data.server_key->rsa->iqmp);
963: buffer_get_bignum(&m, sensitive_data.server_key->rsa->p);
964: buffer_get_bignum(&m, sensitive_data.server_key->rsa->q);
965: rsa_generate_additional_parameters(
966: sensitive_data.server_key->rsa);
967: }
968: buffer_free(&m);
969:
970: debug3("%s: done", __func__);
971: }
972:
1.345 djm 973: /* Accept a connection from inetd */
974: static void
975: server_accept_inetd(int *sock_in, int *sock_out)
976: {
977: int fd;
978:
979: startup_pipe = -1;
980: if (rexeced_flag) {
981: close(REEXEC_CONFIG_PASS_FD);
982: *sock_in = *sock_out = dup(STDIN_FILENO);
983: if (!debug_flag) {
984: startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
985: close(REEXEC_STARTUP_PIPE_FD);
986: }
987: } else {
988: *sock_in = dup(STDIN_FILENO);
989: *sock_out = dup(STDOUT_FILENO);
990: }
991: /*
992: * We intentionally do not close the descriptors 0, 1, and 2
993: * as our code for setting the descriptors won't work if
994: * ttyfd happens to be one of those.
995: */
996: if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
997: dup2(fd, STDIN_FILENO);
998: dup2(fd, STDOUT_FILENO);
999: if (fd > STDOUT_FILENO)
1000: close(fd);
1001: }
1002: debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1003: }
1004:
1005: /*
1006: * Listen for TCP connections
1007: */
1008: static void
1009: server_listen(void)
1010: {
1011: int ret, listen_sock, on = 1;
1012: struct addrinfo *ai;
1013: char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1014:
1015: for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
1016: if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1017: continue;
1018: if (num_listen_socks >= MAX_LISTEN_SOCKS)
1019: fatal("Too many listen sockets. "
1020: "Enlarge MAX_LISTEN_SOCKS");
1021: if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1022: ntop, sizeof(ntop), strport, sizeof(strport),
1023: NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1024: error("getnameinfo failed: %.100s",
1.352 dtucker 1025: ssh_gai_strerror(ret));
1.345 djm 1026: continue;
1027: }
1028: /* Create socket for listening. */
1.370 dtucker 1029: listen_sock = socket(ai->ai_family, ai->ai_socktype,
1030: ai->ai_protocol);
1.345 djm 1031: if (listen_sock < 0) {
1032: /* kernel may not support ipv6 */
1033: verbose("socket: %.100s", strerror(errno));
1034: continue;
1035: }
1036: if (set_nonblock(listen_sock) == -1) {
1037: close(listen_sock);
1038: continue;
1039: }
1040: /*
1041: * Set socket options.
1042: * Allow local port reuse in TIME_WAIT.
1043: */
1044: if (setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
1045: &on, sizeof(on)) == -1)
1046: error("setsockopt SO_REUSEADDR: %s", strerror(errno));
1047:
1048: debug("Bind to port %s on %s.", strport, ntop);
1049:
1050: /* Bind the socket to the desired port. */
1051: if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1052: error("Bind to port %s on %s failed: %.200s.",
1053: strport, ntop, strerror(errno));
1054: close(listen_sock);
1055: continue;
1056: }
1057: listen_socks[num_listen_socks] = listen_sock;
1058: num_listen_socks++;
1059:
1060: /* Start listening on the port. */
1061: if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1062: fatal("listen on [%s]:%s: %.100s",
1063: ntop, strport, strerror(errno));
1064: logit("Server listening on %s port %s.", ntop, strport);
1065: }
1066: freeaddrinfo(options.listen_addrs);
1067:
1068: if (!num_listen_socks)
1069: fatal("Cannot bind any address.");
1070: }
1071:
1072: /*
1073: * The main TCP accept loop. Note that, for the non-debug case, returns
1074: * from this function are in a forked subprocess.
1075: */
1076: static void
1077: server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1078: {
1079: fd_set *fdset;
1080: int i, j, ret, maxfd;
1081: int key_used = 0, startups = 0;
1082: int startup_p[2] = { -1 , -1 };
1083: struct sockaddr_storage from;
1084: socklen_t fromlen;
1085: pid_t pid;
1086:
1087: /* setup fd set for accept */
1088: fdset = NULL;
1089: maxfd = 0;
1090: for (i = 0; i < num_listen_socks; i++)
1091: if (listen_socks[i] > maxfd)
1092: maxfd = listen_socks[i];
1093: /* pipes connected to unauthenticated childs */
1094: startup_pipes = xcalloc(options.max_startups, sizeof(int));
1095: for (i = 0; i < options.max_startups; i++)
1096: startup_pipes[i] = -1;
1097:
1098: /*
1099: * Stay listening for connections until the system crashes or
1100: * the daemon is killed with a signal.
1101: */
1102: for (;;) {
1103: if (received_sighup)
1104: sighup_restart();
1105: if (fdset != NULL)
1106: xfree(fdset);
1107: fdset = (fd_set *)xcalloc(howmany(maxfd + 1, NFDBITS),
1108: sizeof(fd_mask));
1109:
1110: for (i = 0; i < num_listen_socks; i++)
1111: FD_SET(listen_socks[i], fdset);
1112: for (i = 0; i < options.max_startups; i++)
1113: if (startup_pipes[i] != -1)
1114: FD_SET(startup_pipes[i], fdset);
1115:
1116: /* Wait in select until there is a connection. */
1117: ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1118: if (ret < 0 && errno != EINTR)
1119: error("select: %.100s", strerror(errno));
1120: if (received_sigterm) {
1121: logit("Received signal %d; terminating.",
1122: (int) received_sigterm);
1123: close_listen_socks();
1124: unlink(options.pid_file);
1.382 djm 1125: exit(received_sigterm == SIGTERM ? 0 : 255);
1.345 djm 1126: }
1127: if (key_used && key_do_regen) {
1128: generate_ephemeral_server_key();
1129: key_used = 0;
1130: key_do_regen = 0;
1131: }
1132: if (ret < 0)
1133: continue;
1134:
1135: for (i = 0; i < options.max_startups; i++)
1136: if (startup_pipes[i] != -1 &&
1137: FD_ISSET(startup_pipes[i], fdset)) {
1138: /*
1139: * the read end of the pipe is ready
1140: * if the child has closed the pipe
1141: * after successful authentication
1142: * or if the child has died
1143: */
1144: close(startup_pipes[i]);
1145: startup_pipes[i] = -1;
1146: startups--;
1147: }
1148: for (i = 0; i < num_listen_socks; i++) {
1149: if (!FD_ISSET(listen_socks[i], fdset))
1150: continue;
1151: fromlen = sizeof(from);
1152: *newsock = accept(listen_socks[i],
1153: (struct sockaddr *)&from, &fromlen);
1154: if (*newsock < 0) {
1155: if (errno != EINTR && errno != EWOULDBLOCK)
1.389 djm 1156: error("accept: %.100s",
1157: strerror(errno));
1158: if (errno == EMFILE || errno == ENFILE)
1159: usleep(100 * 1000);
1.345 djm 1160: continue;
1161: }
1162: if (unset_nonblock(*newsock) == -1) {
1163: close(*newsock);
1164: continue;
1165: }
1166: if (drop_connection(startups) == 1) {
1167: debug("drop connection #%d", startups);
1168: close(*newsock);
1169: continue;
1170: }
1171: if (pipe(startup_p) == -1) {
1172: close(*newsock);
1173: continue;
1174: }
1175:
1176: if (rexec_flag && socketpair(AF_UNIX,
1177: SOCK_STREAM, 0, config_s) == -1) {
1178: error("reexec socketpair: %s",
1179: strerror(errno));
1180: close(*newsock);
1181: close(startup_p[0]);
1182: close(startup_p[1]);
1183: continue;
1184: }
1185:
1186: for (j = 0; j < options.max_startups; j++)
1187: if (startup_pipes[j] == -1) {
1188: startup_pipes[j] = startup_p[0];
1189: if (maxfd < startup_p[0])
1190: maxfd = startup_p[0];
1191: startups++;
1192: break;
1193: }
1194:
1195: /*
1196: * Got connection. Fork a child to handle it, unless
1197: * we are in debugging mode.
1198: */
1199: if (debug_flag) {
1200: /*
1201: * In debugging mode. Close the listening
1202: * socket, and start processing the
1203: * connection without forking.
1204: */
1205: debug("Server will not fork when running in debugging mode.");
1206: close_listen_socks();
1207: *sock_in = *newsock;
1208: *sock_out = *newsock;
1209: close(startup_p[0]);
1210: close(startup_p[1]);
1211: startup_pipe = -1;
1212: pid = getpid();
1213: if (rexec_flag) {
1214: send_rexec_state(config_s[0],
1215: &cfg);
1216: close(config_s[0]);
1217: }
1218: break;
1219: }
1220:
1221: /*
1222: * Normal production daemon. Fork, and have
1223: * the child process the connection. The
1224: * parent continues listening.
1225: */
1226: if ((pid = fork()) == 0) {
1227: /*
1228: * Child. Close the listening and
1229: * max_startup sockets. Start using
1230: * the accepted socket. Reinitialize
1231: * logging (since our pid has changed).
1232: * We break out of the loop to handle
1233: * the connection.
1234: */
1235: startup_pipe = startup_p[1];
1236: close_startup_pipes();
1237: close_listen_socks();
1238: *sock_in = *newsock;
1239: *sock_out = *newsock;
1240: log_init(__progname,
1241: options.log_level,
1242: options.log_facility,
1243: log_stderr);
1244: if (rexec_flag)
1245: close(config_s[0]);
1246: break;
1247: }
1248:
1249: /* Parent. Stay in the loop. */
1250: if (pid < 0)
1251: error("fork: %.100s", strerror(errno));
1252: else
1253: debug("Forked child %ld.", (long)pid);
1254:
1255: close(startup_p[1]);
1256:
1257: if (rexec_flag) {
1258: send_rexec_state(config_s[0], &cfg);
1259: close(config_s[0]);
1260: close(config_s[1]);
1261: }
1262:
1263: /*
1264: * Mark that the key has been used (it
1265: * was "given" to the child).
1266: */
1267: if ((options.protocol & SSH_PROTO_1) &&
1268: key_used == 0) {
1269: /* Schedule server key regeneration alarm. */
1270: signal(SIGALRM, key_regeneration_alarm);
1271: alarm(options.key_regeneration_time);
1272: key_used = 1;
1273: }
1274:
1275: close(*newsock);
1276:
1277: /*
1278: * Ensure that our random state differs
1279: * from that of the child
1280: */
1281: arc4random_stir();
1282: }
1283:
1284: /* child process check (or debug mode) */
1285: if (num_listen_socks < 0)
1286: break;
1287: }
1288: }
1289:
1290:
1.65 deraadt 1291: /*
1292: * Main program for the daemon.
1293: */
1.2 provos 1294: int
1295: main(int ac, char **av)
1.1 deraadt 1296: {
1.64 markus 1297: extern char *optarg;
1298: extern int optind;
1.373 djm 1299: int opt, i, j, on = 1;
1.297 avsm 1300: int sock_in = -1, sock_out = -1, newsock = -1;
1.64 markus 1301: const char *remote_ip;
1302: int remote_port;
1.391 dtucker 1303: char *line;
1.345 djm 1304: int config_s[2] = { -1 , -1 };
1.364 markus 1305: u_int64_t ibytes, obytes;
1.362 dtucker 1306: mode_t new_umask;
1.278 markus 1307: Key *key;
1.230 provos 1308: Authctxt *authctxt;
1.391 dtucker 1309: struct connection_info *connection_info = get_connection_info(0, 0);
1.64 markus 1310:
1.138 markus 1311: /* Save argv. */
1.64 markus 1312: saved_argv = av;
1.294 djm 1313: rexec_argc = ac;
1.313 djm 1314:
1315: /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1316: sanitise_stdfd();
1.64 markus 1317:
1318: /* Initialize configuration options to their default values. */
1319: initialize_server_options(&options);
1320:
1321: /* Parse command-line arguments. */
1.358 dtucker 1322: while ((opt = getopt(ac, av, "f:p:b:k:h:g:u:o:C:dDeiqrtQRT46")) != -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;
1351: case 'e':
1352: log_stderr = 1;
1.135 markus 1353: break;
1.64 markus 1354: case 'i':
1355: inetd_flag = 1;
1356: break;
1.294 djm 1357: case 'r':
1358: rexec_flag = 0;
1359: break;
1360: case 'R':
1361: rexeced_flag = 1;
1362: inetd_flag = 1;
1363: break;
1.64 markus 1364: case 'Q':
1.158 markus 1365: /* ignored */
1.64 markus 1366: break;
1367: case 'q':
1368: options.log_level = SYSLOG_LEVEL_QUIET;
1369: break;
1370: case 'b':
1.327 deraadt 1371: options.server_key_bits = (int)strtonum(optarg, 256,
1372: 32768, NULL);
1.64 markus 1373: break;
1374: case 'p':
1.75 markus 1375: options.ports_from_cmdline = 1;
1.127 markus 1376: if (options.num_ports >= MAX_PORTS) {
1377: fprintf(stderr, "too many ports.\n");
1378: exit(1);
1379: }
1.193 stevesk 1380: options.ports[options.num_ports++] = a2port(optarg);
1.366 djm 1381: if (options.ports[options.num_ports-1] <= 0) {
1.193 stevesk 1382: fprintf(stderr, "Bad port number.\n");
1383: exit(1);
1384: }
1.64 markus 1385: break;
1386: case 'g':
1.197 stevesk 1387: if ((options.login_grace_time = convtime(optarg)) == -1) {
1388: fprintf(stderr, "Invalid login grace time.\n");
1389: exit(1);
1390: }
1.64 markus 1391: break;
1392: case 'k':
1.197 stevesk 1393: if ((options.key_regeneration_time = convtime(optarg)) == -1) {
1394: fprintf(stderr, "Invalid key regeneration interval.\n");
1395: exit(1);
1396: }
1.64 markus 1397: break;
1398: case 'h':
1.134 markus 1399: if (options.num_host_key_files >= MAX_HOSTKEYS) {
1400: fprintf(stderr, "too many host keys.\n");
1401: exit(1);
1402: }
1.371 djm 1403: options.host_key_files[options.num_host_key_files++] =
1404: derelativise_path(optarg);
1.64 markus 1405: break;
1.203 stevesk 1406: case 't':
1407: test_flag = 1;
1408: break;
1.358 dtucker 1409: case 'T':
1410: test_flag = 2;
1411: break;
1412: case 'C':
1.391 dtucker 1413: if (parse_server_match_testspec(connection_info,
1414: optarg) == -1)
1415: exit(1);
1.358 dtucker 1416: break;
1.125 markus 1417: case 'u':
1.327 deraadt 1418: utmp_len = (u_int)strtonum(optarg, 0, MAXHOSTNAMELEN+1, NULL);
1.257 stevesk 1419: if (utmp_len > MAXHOSTNAMELEN) {
1420: fprintf(stderr, "Invalid utmp length.\n");
1421: exit(1);
1422: }
1.125 markus 1423: break;
1.215 markus 1424: case 'o':
1.283 markus 1425: line = xstrdup(optarg);
1426: if (process_server_config_line(&options, line,
1.391 dtucker 1427: "command-line", 0, NULL, NULL) != 0)
1.217 deraadt 1428: exit(1);
1.283 markus 1429: xfree(line);
1.215 markus 1430: break;
1.64 markus 1431: case '?':
1432: default:
1.215 markus 1433: usage();
1434: break;
1.64 markus 1435: }
1436: }
1.294 djm 1437: if (rexeced_flag || inetd_flag)
1438: rexec_flag = 0;
1.355 mbalmer 1439: if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1.294 djm 1440: fatal("sshd re-exec requires execution with an absolute path");
1441: if (rexeced_flag)
1.296 djm 1442: closefrom(REEXEC_MIN_FREE_FD);
1443: else
1444: closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1.294 djm 1445:
1.379 djm 1446: OpenSSL_add_all_algorithms();
1.64 markus 1447:
1.75 markus 1448: /*
1449: * Force logging to stderr until we have loaded the private host
1450: * key (unless started from inetd)
1451: */
1.138 markus 1452: log_init(__progname,
1.224 markus 1453: options.log_level == SYSLOG_LEVEL_NOT_SET ?
1454: SYSLOG_LEVEL_INFO : options.log_level,
1455: options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1456: SYSLOG_FACILITY_AUTH : options.log_facility,
1.261 markus 1457: log_stderr || !inetd_flag);
1.75 markus 1458:
1.294 djm 1459: sensitive_data.server_key = NULL;
1460: sensitive_data.ssh1_host_key = NULL;
1461: sensitive_data.have_ssh1_key = 0;
1462: sensitive_data.have_ssh2_key = 0;
1463:
1.358 dtucker 1464: /*
1465: * If we're doing an extended config test, make sure we have all of
1466: * the parameters we need. If we're not doing an extended test,
1467: * do not silently ignore connection test params.
1468: */
1.391 dtucker 1469: if (test_flag >= 2 && server_match_spec_complete(connection_info) == 0)
1.358 dtucker 1470: fatal("user, host and addr are all required when testing "
1471: "Match configs");
1.391 dtucker 1472: if (test_flag < 2 && server_match_spec_complete(connection_info) >= 0)
1.358 dtucker 1473: fatal("Config test connection parameter (-C) provided without "
1474: "test mode (-T)");
1475:
1.294 djm 1476: /* Fetch our configuration */
1477: buffer_init(&cfg);
1478: if (rexeced_flag)
1.296 djm 1479: recv_rexec_state(REEXEC_CONFIG_PASS_FD, &cfg);
1.294 djm 1480: else
1481: load_server_config(config_file_name, &cfg);
1482:
1.337 dtucker 1483: parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1.391 dtucker 1484: &cfg, NULL);
1.64 markus 1485:
1486: /* Fill in default values for those options not explicitly set. */
1487: fill_default_server_options(&options);
1.350 dtucker 1488:
1489: /* challenge-response is implemented via keyboard interactive */
1490: if (options.challenge_response_authentication)
1491: options.kbd_interactive_authentication = 1;
1.395 ! djm 1492:
! 1493: /* Check that options are sensible */
! 1494: if (options.authorized_keys_command_user == NULL &&
! 1495: (options.authorized_keys_command != NULL &&
! 1496: strcasecmp(options.authorized_keys_command, "none") != 0))
! 1497: fatal("AuthorizedKeysCommand set without "
! 1498: "AuthorizedKeysCommandUser");
1.305 djm 1499:
1.370 dtucker 1500: /* set default channel AF */
1.305 djm 1501: channel_set_af(options.address_family);
1.64 markus 1502:
1503: /* Check that there are no remaining arguments. */
1504: if (optind < ac) {
1505: fprintf(stderr, "Extra argument %s.\n", av[optind]);
1506: exit(1);
1507: }
1508:
1509: debug("sshd version %.100s", SSH_VERSION);
1510:
1.134 markus 1511: /* load private host keys */
1.329 djm 1512: sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1.255 deraadt 1513: sizeof(Key *));
1.217 deraadt 1514: for (i = 0; i < options.num_host_key_files; i++)
1.141 markus 1515: sensitive_data.host_keys[i] = NULL;
1.134 markus 1516:
1.217 deraadt 1517: for (i = 0; i < options.num_host_key_files; i++) {
1.179 markus 1518: key = key_load_private(options.host_key_files[i], "", NULL);
1519: sensitive_data.host_keys[i] = key;
1.134 markus 1520: if (key == NULL) {
1.195 markus 1521: error("Could not load host key: %s",
1522: options.host_key_files[i]);
1.179 markus 1523: sensitive_data.host_keys[i] = NULL;
1.134 markus 1524: continue;
1525: }
1.214 deraadt 1526: switch (key->type) {
1.134 markus 1527: case KEY_RSA1:
1528: sensitive_data.ssh1_host_key = key;
1529: sensitive_data.have_ssh1_key = 1;
1530: break;
1531: case KEY_RSA:
1532: case KEY_DSA:
1.378 djm 1533: case KEY_ECDSA:
1.134 markus 1534: sensitive_data.have_ssh2_key = 1;
1535: break;
1536: }
1.179 markus 1537: debug("private host key: #%d type %d %s", i, key->type,
1538: key_type(key));
1.134 markus 1539: }
1540: if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
1.264 itojun 1541: logit("Disabling protocol version 1. Could not load host key");
1.108 markus 1542: options.protocol &= ~SSH_PROTO_1;
1543: }
1.134 markus 1544: if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
1.264 itojun 1545: logit("Disabling protocol version 2. Could not load host key");
1.134 markus 1546: options.protocol &= ~SSH_PROTO_2;
1.108 markus 1547: }
1.162 stevesk 1548: if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
1.264 itojun 1549: logit("sshd: no hostkeys available -- exiting.");
1.64 markus 1550: exit(1);
1551: }
1552:
1.373 djm 1553: /*
1554: * Load certificates. They are stored in an array at identical
1555: * indices to the public keys that they relate to.
1556: */
1557: sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1558: sizeof(Key *));
1559: for (i = 0; i < options.num_host_key_files; i++)
1560: sensitive_data.host_certificates[i] = NULL;
1561:
1562: for (i = 0; i < options.num_host_cert_files; i++) {
1563: key = key_load_public(options.host_cert_files[i], NULL);
1564: if (key == NULL) {
1565: error("Could not load host certificate: %s",
1566: options.host_cert_files[i]);
1567: continue;
1568: }
1569: if (!key_is_cert(key)) {
1570: error("Certificate file is not a certificate: %s",
1571: options.host_cert_files[i]);
1572: key_free(key);
1573: continue;
1574: }
1575: /* Find matching private key */
1576: for (j = 0; j < options.num_host_key_files; j++) {
1577: if (key_equal_public(key,
1578: sensitive_data.host_keys[j])) {
1579: sensitive_data.host_certificates[j] = key;
1580: break;
1581: }
1582: }
1583: if (j >= options.num_host_key_files) {
1584: error("No matching private key for certificate: %s",
1585: options.host_cert_files[i]);
1586: key_free(key);
1587: continue;
1588: }
1589: sensitive_data.host_certificates[j] = key;
1590: debug("host certificate: #%d type %d %s", j, key->type,
1591: key_type(key));
1592: }
1.108 markus 1593: /* Check certain values for sanity. */
1594: if (options.protocol & SSH_PROTO_1) {
1595: if (options.server_key_bits < 512 ||
1596: options.server_key_bits > 32768) {
1597: fprintf(stderr, "Bad server key size.\n");
1598: exit(1);
1599: }
1600: /*
1601: * Check that server and host key lengths differ sufficiently. This
1602: * is necessary to make double encryption work with rsaref. Oh, I
1603: * hate software patents. I dont know if this can go? Niels
1604: */
1605: if (options.server_key_bits >
1.250 deraadt 1606: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) -
1607: SSH_KEY_BITS_RESERVED && options.server_key_bits <
1608: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1609: SSH_KEY_BITS_RESERVED) {
1.108 markus 1610: options.server_key_bits =
1.250 deraadt 1611: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1612: SSH_KEY_BITS_RESERVED;
1.108 markus 1613: debug("Forcing server key to %d bits to make it differ from host key.",
1614: options.server_key_bits);
1615: }
1.244 markus 1616: }
1617:
1618: if (use_privsep) {
1619: struct stat st;
1620:
1.327 deraadt 1621: if (getpwnam(SSH_PRIVSEP_USER) == NULL)
1.244 markus 1622: fatal("Privilege separation user %s does not exist",
1623: SSH_PRIVSEP_USER);
1624: if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1625: (S_ISDIR(st.st_mode) == 0))
1626: fatal("Missing privilege separation directory: %s",
1.247 stevesk 1627: _PATH_PRIVSEP_CHROOT_DIR);
1628: if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1.262 markus 1629: fatal("%s must be owned by root and not group or "
1630: "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1.358 dtucker 1631: }
1632:
1633: if (test_flag > 1) {
1.391 dtucker 1634: if (server_match_spec_complete(connection_info) == 1)
1635: parse_server_match_config(&options, connection_info);
1.358 dtucker 1636: dump_config(&options);
1.108 markus 1637: }
1.203 stevesk 1638:
1639: /* Configuration looks good, so exit if in test mode. */
1640: if (test_flag)
1641: exit(0);
1.108 markus 1642:
1.294 djm 1643: if (rexec_flag) {
1.329 djm 1644: rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1.294 djm 1645: for (i = 0; i < rexec_argc; i++) {
1646: debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1647: rexec_argv[i] = saved_argv[i];
1648: }
1649: rexec_argv[rexec_argc] = "-R";
1650: rexec_argv[rexec_argc + 1] = NULL;
1651: }
1.362 dtucker 1652:
1653: /* Ensure that umask disallows at least group and world write */
1654: new_umask = umask(0077) | 0022;
1655: (void) umask(new_umask);
1.294 djm 1656:
1.108 markus 1657: /* Initialize the log (it is reinitialized below in case we forked). */
1.306 dtucker 1658: if (debug_flag && (!inetd_flag || rexeced_flag))
1.64 markus 1659: log_stderr = 1;
1.138 markus 1660: log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64 markus 1661:
1.108 markus 1662: /*
1663: * If not in debugging mode, and not started from inetd, disconnect
1664: * from the controlling terminal, and fork. The original process
1665: * exits.
1666: */
1.135 markus 1667: if (!(debug_flag || inetd_flag || no_daemon_flag)) {
1.64 markus 1668: int fd;
1.345 djm 1669:
1.64 markus 1670: if (daemon(0, 0) < 0)
1671: fatal("daemon() failed: %.200s", strerror(errno));
1672:
1673: /* Disconnect from the controlling tty. */
1.165 itojun 1674: fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
1.64 markus 1675: if (fd >= 0) {
1676: (void) ioctl(fd, TIOCNOTTY, NULL);
1677: close(fd);
1678: }
1679: }
1680: /* Reinitialize the log (because of the fork above). */
1.138 markus 1681: log_init(__progname, options.log_level, options.log_facility, log_stderr);
1.64 markus 1682:
1683: /* Initialize the random number generator. */
1684: arc4random_stir();
1685:
1686: /* Chdir to the root directory so that the current disk can be
1687: unmounted if desired. */
1688: chdir("/");
1.217 deraadt 1689:
1.178 markus 1690: /* ignore SIGPIPE */
1691: signal(SIGPIPE, SIG_IGN);
1.64 markus 1692:
1.345 djm 1693: /* Get a connection, either from inetd or a listening TCP socket */
1.64 markus 1694: if (inetd_flag) {
1.345 djm 1695: server_accept_inetd(&sock_in, &sock_out);
1.64 markus 1696: } else {
1.345 djm 1697: server_listen();
1.75 markus 1698:
1.201 markus 1699: if (options.protocol & SSH_PROTO_1)
1700: generate_ephemeral_server_key();
1701:
1702: signal(SIGHUP, sighup_handler);
1.345 djm 1703: signal(SIGCHLD, main_sigchld_handler);
1.201 markus 1704: signal(SIGTERM, sigterm_handler);
1705: signal(SIGQUIT, sigterm_handler);
1706:
1.345 djm 1707: /*
1708: * Write out the pid file after the sigterm handler
1709: * is setup and the listen sockets are bound
1710: */
1711: if (!debug_flag) {
1712: FILE *f = fopen(options.pid_file, "w");
1.201 markus 1713:
1.270 djm 1714: if (f == NULL) {
1715: error("Couldn't create pid file \"%s\": %s",
1716: options.pid_file, strerror(errno));
1717: } else {
1.245 mpech 1718: fprintf(f, "%ld\n", (long) getpid());
1.64 markus 1719: fclose(f);
1720: }
1721: }
1722:
1.345 djm 1723: /* Accept a connection and return in a forked child */
1724: server_accept_loop(&sock_in, &sock_out,
1725: &newsock, config_s);
1.1 deraadt 1726: }
1727:
1.64 markus 1728: /* This is the child processing a new connection. */
1.288 markus 1729: setproctitle("%s", "[accepted]");
1.294 djm 1730:
1.300 markus 1731: /*
1732: * Create a new session and process group since the 4.4BSD
1733: * setlogin() affects the entire process group. We don't
1734: * want the child to be able to affect the parent.
1735: */
1736: if (!debug_flag && !inetd_flag && setsid() < 0)
1737: error("setsid: %.100s", strerror(errno));
1738:
1.294 djm 1739: if (rexec_flag) {
1740: int fd;
1741:
1.296 djm 1742: debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1743: sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294 djm 1744: dup2(newsock, STDIN_FILENO);
1745: dup2(STDIN_FILENO, STDOUT_FILENO);
1746: if (startup_pipe == -1)
1.296 djm 1747: close(REEXEC_STARTUP_PIPE_FD);
1.294 djm 1748: else
1.296 djm 1749: dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
1.294 djm 1750:
1.296 djm 1751: dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
1.294 djm 1752: close(config_s[1]);
1.301 dtucker 1753: if (startup_pipe != -1)
1754: close(startup_pipe);
1.296 djm 1755:
1.294 djm 1756: execv(rexec_argv[0], rexec_argv);
1757:
1758: /* Reexec has failed, fall back and continue */
1759: error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
1.296 djm 1760: recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
1.294 djm 1761: log_init(__progname, options.log_level,
1762: options.log_facility, log_stderr);
1763:
1764: /* Clean up fds */
1.296 djm 1765: startup_pipe = REEXEC_STARTUP_PIPE_FD;
1.294 djm 1766: close(config_s[1]);
1.296 djm 1767: close(REEXEC_CONFIG_PASS_FD);
1768: newsock = sock_out = sock_in = dup(STDIN_FILENO);
1.294 djm 1769: if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1770: dup2(fd, STDIN_FILENO);
1771: dup2(fd, STDOUT_FILENO);
1772: if (fd > STDERR_FILENO)
1773: close(fd);
1774: }
1.296 djm 1775: debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
1776: sock_in, sock_out, newsock, startup_pipe, config_s[0]);
1.294 djm 1777: }
1.372 djm 1778:
1779: /* Executed child processes don't need these. */
1780: fcntl(sock_out, F_SETFD, FD_CLOEXEC);
1781: fcntl(sock_in, F_SETFD, FD_CLOEXEC);
1.64 markus 1782:
1.66 markus 1783: /*
1784: * Disable the key regeneration alarm. We will not regenerate the
1785: * key since we are no longer in a position to give it to anyone. We
1786: * will not restart on SIGHUP since it no longer makes sense.
1787: */
1.64 markus 1788: alarm(0);
1789: signal(SIGALRM, SIG_DFL);
1790: signal(SIGHUP, SIG_DFL);
1791: signal(SIGTERM, SIG_DFL);
1792: signal(SIGQUIT, SIG_DFL);
1793: signal(SIGCHLD, SIG_DFL);
1.150 markus 1794:
1.66 markus 1795: /*
1796: * Register our connection. This turns encryption off because we do
1797: * not have a key.
1798: */
1.64 markus 1799: packet_set_connection(sock_in, sock_out);
1.312 markus 1800: packet_set_server();
1.309 djm 1801:
1802: /* Set SO_KEEPALIVE if requested. */
1803: if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
1804: setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
1805: error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1.1 deraadt 1806:
1.310 markus 1807: if ((remote_port = get_remote_port()) < 0) {
1808: debug("get_remote_port failed");
1809: cleanup_exit(255);
1810: }
1.316 dtucker 1811:
1812: /*
1813: * We use get_canonical_hostname with usedns = 0 instead of
1814: * get_remote_ipaddr here so IP options will be checked.
1815: */
1.331 markus 1816: (void) get_canonical_hostname(0);
1817: /*
1818: * The rest of the code depends on the fact that
1819: * get_remote_ipaddr() caches the remote ip, even if
1820: * the socket goes away.
1821: */
1822: remote_ip = get_remote_ipaddr();
1.52 markus 1823:
1.209 markus 1824: #ifdef LIBWRAP
1.64 markus 1825: /* Check whether logins are denied from this host. */
1.295 djm 1826: if (packet_connection_is_on_socket()) {
1.64 markus 1827: struct request_info req;
1.37 dugsong 1828:
1.204 camield 1829: request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
1.64 markus 1830: fromhost(&req);
1.37 dugsong 1831:
1.64 markus 1832: if (!hosts_access(&req)) {
1.209 markus 1833: debug("Connection refused by tcp wrapper");
1.182 markus 1834: refuse(&req);
1.209 markus 1835: /* NOTREACHED */
1836: fatal("libwrap refuse returns");
1.64 markus 1837: }
1838: }
1.75 markus 1839: #endif /* LIBWRAP */
1.209 markus 1840:
1.64 markus 1841: /* Log the connection. */
1842: verbose("Connection from %.500s port %d", remote_ip, remote_port);
1.1 deraadt 1843:
1.66 markus 1844: /*
1.317 djm 1845: * We don't want to listen forever unless the other side
1.66 markus 1846: * successfully authenticates itself. So we set up an alarm which is
1847: * cleared after successful authentication. A limit of zero
1.317 djm 1848: * indicates no limit. Note that we don't set the alarm in debugging
1.66 markus 1849: * mode; it is just annoying to have the server exit just when you
1850: * are about to discover the bug.
1851: */
1.64 markus 1852: signal(SIGALRM, grace_alarm_handler);
1853: if (!debug_flag)
1854: alarm(options.login_grace_time);
1855:
1.96 markus 1856: sshd_exchange_identification(sock_in, sock_out);
1.353 dtucker 1857:
1858: /* In inetd mode, generate ephemeral key only for proto 1 connections */
1859: if (!compat20 && inetd_flag && sensitive_data.server_key == NULL)
1860: generate_ephemeral_server_key();
1.275 markus 1861:
1.64 markus 1862: packet_set_nonblocking();
1.1 deraadt 1863:
1.278 markus 1864: /* allocate authentication context */
1.329 djm 1865: authctxt = xcalloc(1, sizeof(*authctxt));
1.278 markus 1866:
1867: /* XXX global for cleanup, access from other modules */
1868: the_authctxt = authctxt;
1869:
1.307 otto 1870: /* prepare buffer to collect messages to display to user after login */
1871: buffer_init(&loginmsg);
1.374 dtucker 1872: auth_debug_reset();
1.307 otto 1873:
1.237 markus 1874: if (use_privsep)
1.278 markus 1875: if (privsep_preauth(authctxt) == 1)
1.237 markus 1876: goto authenticated;
1.231 provos 1877:
1.77 markus 1878: /* perform the key exchange */
1879: /* authenticate user and start session */
1.98 markus 1880: if (compat20) {
1881: do_ssh2_kex();
1.278 markus 1882: do_authentication2(authctxt);
1.98 markus 1883: } else {
1884: do_ssh1_kex();
1.278 markus 1885: do_authentication(authctxt);
1.98 markus 1886: }
1.237 markus 1887: /*
1888: * If we use privilege separation, the unprivileged child transfers
1889: * the current keystate and exits
1890: */
1891: if (use_privsep) {
1.242 mouring 1892: mm_send_keystate(pmonitor);
1.231 provos 1893: exit(0);
1.237 markus 1894: }
1.231 provos 1895:
1896: authenticated:
1.318 djm 1897: /*
1898: * Cancel the alarm we set to limit the time taken for
1899: * authentication.
1900: */
1901: alarm(0);
1902: signal(SIGALRM, SIG_DFL);
1.347 markus 1903: authctxt->authenticated = 1;
1.318 djm 1904: if (startup_pipe != -1) {
1905: close(startup_pipe);
1906: startup_pipe = -1;
1907: }
1908:
1.234 markus 1909: /*
1.231 provos 1910: * In privilege separation, we fork another child and prepare
1911: * file descriptor passing.
1912: */
1913: if (use_privsep) {
1.237 markus 1914: privsep_postauth(authctxt);
1915: /* the monitor process [priv] will not return */
1.231 provos 1916: if (!compat20)
1917: destroy_sensitive_data();
1918: }
1.360 dtucker 1919:
1920: packet_set_timeout(options.client_alive_interval,
1921: options.client_alive_count_max);
1.230 provos 1922:
1.278 markus 1923: /* Start session. */
1.230 provos 1924: do_authenticated(authctxt);
1925:
1.64 markus 1926: /* The connection has been terminated. */
1.364 markus 1927: packet_get_state(MODE_IN, NULL, NULL, NULL, &ibytes);
1928: packet_get_state(MODE_OUT, NULL, NULL, NULL, &obytes);
1.381 djm 1929: verbose("Transferred: sent %llu, received %llu bytes",
1930: (unsigned long long)obytes, (unsigned long long)ibytes);
1.364 markus 1931:
1932: verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
1.64 markus 1933: packet_close();
1.231 provos 1934:
1935: if (use_privsep)
1936: mm_terminate();
1937:
1.64 markus 1938: exit(0);
1.1 deraadt 1939: }
1940:
1.65 deraadt 1941: /*
1.229 markus 1942: * Decrypt session_key_int using our private server key and private host key
1943: * (key with larger modulus first).
1944: */
1.231 provos 1945: int
1.229 markus 1946: ssh1_session_key(BIGNUM *session_key_int)
1947: {
1948: int rsafail = 0;
1949:
1.327 deraadt 1950: if (BN_cmp(sensitive_data.server_key->rsa->n,
1951: sensitive_data.ssh1_host_key->rsa->n) > 0) {
1.229 markus 1952: /* Server key has bigger modulus. */
1953: if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1.327 deraadt 1954: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) +
1955: SSH_KEY_BITS_RESERVED) {
1956: fatal("do_connection: %s: "
1957: "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1.229 markus 1958: get_remote_ipaddr(),
1959: BN_num_bits(sensitive_data.server_key->rsa->n),
1960: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1961: SSH_KEY_BITS_RESERVED);
1962: }
1963: if (rsa_private_decrypt(session_key_int, session_key_int,
1964: sensitive_data.server_key->rsa) <= 0)
1965: rsafail++;
1966: if (rsa_private_decrypt(session_key_int, session_key_int,
1967: sensitive_data.ssh1_host_key->rsa) <= 0)
1968: rsafail++;
1969: } else {
1970: /* Host key has bigger modulus (or they are equal). */
1971: if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1.327 deraadt 1972: BN_num_bits(sensitive_data.server_key->rsa->n) +
1973: SSH_KEY_BITS_RESERVED) {
1974: fatal("do_connection: %s: "
1975: "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1.229 markus 1976: get_remote_ipaddr(),
1977: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1978: BN_num_bits(sensitive_data.server_key->rsa->n),
1979: SSH_KEY_BITS_RESERVED);
1980: }
1981: if (rsa_private_decrypt(session_key_int, session_key_int,
1982: sensitive_data.ssh1_host_key->rsa) < 0)
1983: rsafail++;
1984: if (rsa_private_decrypt(session_key_int, session_key_int,
1985: sensitive_data.server_key->rsa) < 0)
1986: rsafail++;
1987: }
1988: return (rsafail);
1989: }
1990: /*
1.77 markus 1991: * SSH1 key exchange
1.65 deraadt 1992: */
1.200 itojun 1993: static void
1.142 markus 1994: do_ssh1_kex(void)
1.1 deraadt 1995: {
1.64 markus 1996: int i, len;
1.159 markus 1997: int rsafail = 0;
1.64 markus 1998: BIGNUM *session_key_int;
1.140 markus 1999: u_char session_key[SSH_SESSION_KEY_LENGTH];
2000: u_char cookie[8];
2001: u_int cipher_type, auth_mask, protocol_flags;
1.64 markus 2002:
1.66 markus 2003: /*
2004: * Generate check bytes that the client must send back in the user
2005: * packet in order for it to be accepted; this is used to defy ip
2006: * spoofing attacks. Note that this only works against somebody
2007: * doing IP spoofing from a remote machine; any machine on the local
2008: * network can still see outgoing packets and catch the random
2009: * cookie. This only affects rhosts authentication, and this is one
2010: * of the reasons why it is inherently insecure.
2011: */
1.356 djm 2012: arc4random_buf(cookie, sizeof(cookie));
1.64 markus 2013:
1.66 markus 2014: /*
2015: * Send our public key. We include in the packet 64 bits of random
2016: * data that must be matched in the reply in order to prevent IP
2017: * spoofing.
2018: */
1.64 markus 2019: packet_start(SSH_SMSG_PUBLIC_KEY);
2020: for (i = 0; i < 8; i++)
1.77 markus 2021: packet_put_char(cookie[i]);
1.64 markus 2022:
2023: /* Store our public server RSA key. */
1.134 markus 2024: packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
2025: packet_put_bignum(sensitive_data.server_key->rsa->e);
2026: packet_put_bignum(sensitive_data.server_key->rsa->n);
1.64 markus 2027:
2028: /* Store our public host RSA key. */
1.134 markus 2029: packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
2030: packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
2031: packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1.64 markus 2032:
2033: /* Put protocol flags. */
2034: packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
2035:
2036: /* Declare which ciphers we support. */
1.131 markus 2037: packet_put_int(cipher_mask_ssh1(0));
1.64 markus 2038:
2039: /* Declare supported authentication types. */
2040: auth_mask = 0;
2041: if (options.rhosts_rsa_authentication)
2042: auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
2043: if (options.rsa_authentication)
2044: auth_mask |= 1 << SSH_AUTH_RSA;
1.196 markus 2045: if (options.challenge_response_authentication == 1)
1.64 markus 2046: auth_mask |= 1 << SSH_AUTH_TIS;
2047: if (options.password_authentication)
2048: auth_mask |= 1 << SSH_AUTH_PASSWORD;
2049: packet_put_int(auth_mask);
2050:
2051: /* Send the packet and wait for it to be sent. */
2052: packet_send();
2053: packet_write_wait();
2054:
1.134 markus 2055: debug("Sent %d bit server key and %d bit host key.",
2056: BN_num_bits(sensitive_data.server_key->rsa->n),
2057: BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1.64 markus 2058:
2059: /* Read clients reply (cipher type and session key). */
1.222 markus 2060: packet_read_expect(SSH_CMSG_SESSION_KEY);
1.64 markus 2061:
1.69 markus 2062: /* Get cipher type and check whether we accept this. */
1.64 markus 2063: cipher_type = packet_get_char();
1.69 markus 2064:
1.131 markus 2065: if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1.69 markus 2066: packet_disconnect("Warning: client selects unsupported cipher.");
1.64 markus 2067:
2068: /* Get check bytes from the packet. These must match those we
2069: sent earlier with the public key packet. */
2070: for (i = 0; i < 8; i++)
1.77 markus 2071: if (cookie[i] != packet_get_char())
1.64 markus 2072: packet_disconnect("IP Spoofing check bytes do not match.");
2073:
2074: debug("Encryption type: %.200s", cipher_name(cipher_type));
2075:
2076: /* Get the encrypted integer. */
1.218 markus 2077: if ((session_key_int = BN_new()) == NULL)
2078: fatal("do_ssh1_kex: BN_new failed");
1.221 markus 2079: packet_get_bignum(session_key_int);
1.64 markus 2080:
2081: protocol_flags = packet_get_int();
2082: packet_set_protocol_flags(protocol_flags);
1.220 markus 2083: packet_check_eom();
1.64 markus 2084:
1.229 markus 2085: /* Decrypt session_key_int using host/server keys */
1.231 provos 2086: rsafail = PRIVSEP(ssh1_session_key(session_key_int));
2087:
1.66 markus 2088: /*
2089: * Extract session key from the decrypted integer. The key is in the
2090: * least significant 256 bits of the integer; the first byte of the
2091: * key is in the highest bits.
2092: */
1.159 markus 2093: if (!rsafail) {
1.348 markus 2094: (void) BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1.159 markus 2095: len = BN_num_bytes(session_key_int);
1.311 djm 2096: if (len < 0 || (u_int)len > sizeof(session_key)) {
1.348 markus 2097: error("do_ssh1_kex: bad session key len from %s: "
1.165 itojun 2098: "session_key_int %d > sizeof(session_key) %lu",
2099: get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1.159 markus 2100: rsafail++;
2101: } else {
2102: memset(session_key, 0, sizeof(session_key));
2103: BN_bn2bin(session_key_int,
2104: session_key + sizeof(session_key) - len);
1.169 markus 2105:
1.291 djm 2106: derive_ssh1_session_id(
1.298 deraadt 2107: sensitive_data.ssh1_host_key->rsa->n,
1.291 djm 2108: sensitive_data.server_key->rsa->n,
2109: cookie, session_id);
1.169 markus 2110: /*
2111: * Xor the first 16 bytes of the session key with the
2112: * session id.
2113: */
2114: for (i = 0; i < 16; i++)
2115: session_key[i] ^= session_id[i];
1.159 markus 2116: }
2117: }
2118: if (rsafail) {
1.169 markus 2119: int bytes = BN_num_bytes(session_key_int);
1.227 stevesk 2120: u_char *buf = xmalloc(bytes);
1.169 markus 2121: MD5_CTX md;
2122:
1.264 itojun 2123: logit("do_connection: generating a fake encryption key");
1.169 markus 2124: BN_bn2bin(session_key_int, buf);
2125: MD5_Init(&md);
2126: MD5_Update(&md, buf, bytes);
2127: MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2128: MD5_Final(session_key, &md);
2129: MD5_Init(&md);
2130: MD5_Update(&md, session_key, 16);
2131: MD5_Update(&md, buf, bytes);
2132: MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
2133: MD5_Final(session_key + 16, &md);
2134: memset(buf, 0, bytes);
2135: xfree(buf);
1.170 markus 2136: for (i = 0; i < 16; i++)
2137: session_id[i] = session_key[i] ^ session_key[i + 16];
1.159 markus 2138: }
1.231 provos 2139: /* Destroy the private and public keys. No longer. */
1.169 markus 2140: destroy_sensitive_data();
2141:
1.231 provos 2142: if (use_privsep)
2143: mm_ssh1_session_id(session_id);
2144:
1.77 markus 2145: /* Destroy the decrypted integer. It is no longer needed. */
2146: BN_clear_free(session_key_int);
1.64 markus 2147:
2148: /* Set the session key. From this on all communications will be encrypted. */
2149: packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
2150:
2151: /* Destroy our copy of the session key. It is no longer needed. */
2152: memset(session_key, 0, sizeof(session_key));
2153:
2154: debug("Received session key; encryption turned on.");
2155:
1.243 deraadt 2156: /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
1.64 markus 2157: packet_start(SSH_SMSG_SUCCESS);
2158: packet_send();
2159: packet_write_wait();
1.98 markus 2160: }
2161:
2162: /*
2163: * SSH2 key exchange: diffie-hellman-group1-sha1
2164: */
1.200 itojun 2165: static void
1.142 markus 2166: do_ssh2_kex(void)
1.98 markus 2167: {
2168: Kex *kex;
1.102 markus 2169:
2170: if (options.ciphers != NULL) {
1.105 markus 2171: myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1.102 markus 2172: myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1.166 markus 2173: }
1.184 stevesk 2174: myproposal[PROPOSAL_ENC_ALGS_CTOS] =
2175: compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
2176: myproposal[PROPOSAL_ENC_ALGS_STOC] =
2177: compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
2178:
1.166 markus 2179: if (options.macs != NULL) {
2180: myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2181: myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1.246 markus 2182: }
1.312 markus 2183: if (options.compression == COMP_NONE) {
1.246 markus 2184: myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2185: myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
1.312 markus 2186: } else if (options.compression == COMP_DELAYED) {
2187: myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2188: myproposal[PROPOSAL_COMP_ALGS_STOC] = "none,zlib@openssh.com";
1.102 markus 2189: }
1.380 djm 2190: if (options.kex_algorithms != NULL)
2191: myproposal[PROPOSAL_KEX_ALGS] = options.kex_algorithms;
1.327 deraadt 2192:
1.134 markus 2193: myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
2194:
1.189 markus 2195: /* start key exchange */
1.188 markus 2196: kex = kex_setup(myproposal);
1.263 markus 2197: kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
1.292 djm 2198: kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
1.263 markus 2199: kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
1.324 djm 2200: kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
1.378 djm 2201: kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
1.186 markus 2202: kex->server = 1;
2203: kex->client_version_string=client_version_string;
2204: kex->server_version_string=server_version_string;
1.373 djm 2205: kex->load_host_public_key=&get_hostkey_public_by_type;
2206: kex->load_host_private_key=&get_hostkey_private_by_type;
1.231 provos 2207: kex->host_key_index=&get_hostkey_index;
1.129 provos 2208:
1.189 markus 2209: xxx_kex = kex;
2210:
1.190 markus 2211: dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1.187 markus 2212:
2213: session_id2 = kex->session_id;
2214: session_id2_len = kex->session_id_len;
1.129 provos 2215:
2216: #ifdef DEBUG_KEXDH
2217: /* send 1st encrypted/maced/compressed message */
2218: packet_start(SSH2_MSG_IGNORE);
2219: packet_put_cstring("markus");
2220: packet_send();
2221: packet_write_wait();
2222: #endif
1.186 markus 2223: debug("KEX done");
1.278 markus 2224: }
2225:
2226: /* server specific fatal cleanup */
2227: void
2228: cleanup_exit(int i)
2229: {
1.386 djm 2230: if (the_authctxt) {
1.278 markus 2231: do_cleanup(the_authctxt);
1.387 dtucker 2232: if (use_privsep && privsep_is_preauth && pmonitor->m_pid > 1) {
1.386 djm 2233: debug("Killing privsep child %d", pmonitor->m_pid);
2234: if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
1.388 djm 2235: errno != ESRCH)
1.386 djm 2236: error("%s: kill(%d): %s", __func__,
2237: pmonitor->m_pid, strerror(errno));
2238: }
2239: }
1.278 markus 2240: _exit(i);
1.1 deraadt 2241: }