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