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