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