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