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