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