]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - crypto/openssh/sshd.c
zfs: merge OpenZFS master-bedbc13da
[FreeBSD/FreeBSD.git] / crypto / openssh / sshd.c
1 /* $OpenBSD: sshd.c,v 1.516 2018/09/21 12:23:17 djm Exp $ */
2 /*
3  * Author: Tatu Ylonen <ylo@cs.hut.fi>
4  * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
5  *                    All rights reserved
6  * This program is the ssh daemon.  It listens for connections from clients,
7  * and performs authentication, executes use commands or shell, and forwards
8  * information to/from the application to the user client over an encrypted
9  * connection.  This can also handle forwarding of X11, TCP/IP, and
10  * authentication agent connections.
11  *
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:
19  * Privilege Separation:
20  *
21  * Copyright (c) 2000, 2001, 2002 Markus Friedl.  All rights reserved.
22  * Copyright (c) 2002 Niels Provos.  All rights reserved.
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.
43  */
44
45 #include "includes.h"
46 __RCSID("$FreeBSD$");
47
48 #include <sys/types.h>
49 #include <sys/ioctl.h>
50 #include <sys/mman.h>
51 #include <sys/socket.h>
52 #ifdef HAVE_SYS_STAT_H
53 # include <sys/stat.h>
54 #endif
55 #ifdef HAVE_SYS_TIME_H
56 # include <sys/time.h>
57 #endif
58 #include "openbsd-compat/sys-tree.h"
59 #include "openbsd-compat/sys-queue.h"
60 #include <sys/wait.h>
61
62 #include <errno.h>
63 #include <fcntl.h>
64 #include <netdb.h>
65 #ifdef HAVE_PATHS_H
66 #include <paths.h>
67 #endif
68 #include <grp.h>
69 #include <pwd.h>
70 #include <signal.h>
71 #include <stdarg.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <unistd.h>
76 #include <limits.h>
77
78 #ifdef WITH_OPENSSL
79 #include <openssl/dh.h>
80 #include <openssl/bn.h>
81 #include <openssl/rand.h>
82 #include "openbsd-compat/openssl-compat.h"
83 #endif
84
85 #ifdef HAVE_SECUREWARE
86 #include <sys/security.h>
87 #include <prot.h>
88 #endif
89
90 #ifdef __FreeBSD__
91 #include <resolv.h>
92 #if defined(GSSAPI) && defined(HAVE_GSSAPI_GSSAPI_H)
93 #include <gssapi/gssapi.h>
94 #elif defined(GSSAPI) && defined(HAVE_GSSAPI_H)
95 #include <gssapi.h>
96 #endif
97 #endif
98
99 #include "xmalloc.h"
100 #include "ssh.h"
101 #include "ssh2.h"
102 #include "sshpty.h"
103 #include "packet.h"
104 #include "log.h"
105 #include "sshbuf.h"
106 #include "misc.h"
107 #include "match.h"
108 #include "servconf.h"
109 #include "uidswap.h"
110 #include "compat.h"
111 #include "cipher.h"
112 #include "digest.h"
113 #include "sshkey.h"
114 #include "kex.h"
115 #include "myproposal.h"
116 #include "authfile.h"
117 #include "pathnames.h"
118 #include "atomicio.h"
119 #include "canohost.h"
120 #include "hostfile.h"
121 #include "auth.h"
122 #include "authfd.h"
123 #include "msg.h"
124 #include "dispatch.h"
125 #include "channels.h"
126 #include "session.h"
127 #include "monitor.h"
128 #ifdef GSSAPI
129 #include "ssh-gss.h"
130 #endif
131 #include "monitor_wrap.h"
132 #include "ssh-sandbox.h"
133 #include "auth-options.h"
134 #include "version.h"
135 #include "ssherr.h"
136 #include "blacklist_client.h"
137
138 #ifdef LIBWRAP
139 #include <tcpd.h>
140 #include <syslog.h>
141 int allow_severity;
142 int deny_severity;
143 #endif /* LIBWRAP */
144
145 /* Re-exec fds */
146 #define REEXEC_DEVCRYPTO_RESERVED_FD    (STDERR_FILENO + 1)
147 #define REEXEC_STARTUP_PIPE_FD          (STDERR_FILENO + 2)
148 #define REEXEC_CONFIG_PASS_FD           (STDERR_FILENO + 3)
149 #define REEXEC_MIN_FREE_FD              (STDERR_FILENO + 4)
150
151 extern char *__progname;
152
153 /* Server configuration options. */
154 ServerOptions options;
155
156 /* Name of the server configuration file. */
157 char *config_file_name = _PATH_SERVER_CONFIG_FILE;
158
159 /*
160  * Debug mode flag.  This can be set on the command line.  If debug
161  * mode is enabled, extra debugging output will be sent to the system
162  * log, the daemon will not go to background, and will exit after processing
163  * the first connection.
164  */
165 int debug_flag = 0;
166
167 /*
168  * Indicating that the daemon should only test the configuration and keys.
169  * If test_flag > 1 ("-T" flag), then sshd will also dump the effective
170  * configuration, optionally using connection information provided by the
171  * "-C" flag.
172  */
173 int test_flag = 0;
174
175 /* Flag indicating that the daemon is being started from inetd. */
176 int inetd_flag = 0;
177
178 /* Flag indicating that sshd should not detach and become a daemon. */
179 int no_daemon_flag = 0;
180
181 /* debug goes to stderr unless inetd_flag is set */
182 int log_stderr = 0;
183
184 /* Saved arguments to main(). */
185 char **saved_argv;
186 int saved_argc;
187
188 /* re-exec */
189 int rexeced_flag = 0;
190 int rexec_flag = 1;
191 int rexec_argc = 0;
192 char **rexec_argv;
193
194 /*
195  * The sockets that the server is listening; this is used in the SIGHUP
196  * signal handler.
197  */
198 #define MAX_LISTEN_SOCKS        16
199 int listen_socks[MAX_LISTEN_SOCKS];
200 int num_listen_socks = 0;
201
202 /*
203  * the client's version string, passed by sshd2 in compat mode. if != NULL,
204  * sshd will skip the version-number exchange
205  */
206 char *client_version_string = NULL;
207 char *server_version_string = NULL;
208
209 /* Daemon's agent connection */
210 int auth_sock = -1;
211 int have_agent = 0;
212
213 /*
214  * Any really sensitive data in the application is contained in this
215  * structure. The idea is that this structure could be locked into memory so
216  * that the pages do not get written into swap.  However, there are some
217  * problems. The private key contains BIGNUMs, and we do not (in principle)
218  * have access to the internals of them, and locking just the structure is
219  * not very useful.  Currently, memory locking is not implemented.
220  */
221 struct {
222         struct sshkey   **host_keys;            /* all private host keys */
223         struct sshkey   **host_pubkeys;         /* all public host keys */
224         struct sshkey   **host_certificates;    /* all public host certificates */
225         int             have_ssh2_key;
226 } sensitive_data;
227
228 /* This is set to true when a signal is received. */
229 static volatile sig_atomic_t received_sighup = 0;
230 static volatile sig_atomic_t received_sigterm = 0;
231
232 /* session identifier, used by RSA-auth */
233 u_char session_id[16];
234
235 /* same for ssh2 */
236 u_char *session_id2 = NULL;
237 u_int session_id2_len = 0;
238
239 /* record remote hostname or ip */
240 u_int utmp_len = HOST_NAME_MAX+1;
241
242 /* options.max_startup sized array of fd ints */
243 int *startup_pipes = NULL;
244 int startup_pipe;               /* in child */
245
246 /* variables used for privilege separation */
247 int use_privsep = -1;
248 struct monitor *pmonitor = NULL;
249 int privsep_is_preauth = 1;
250 static int privsep_chroot = 1;
251
252 /* global authentication context */
253 Authctxt *the_authctxt = NULL;
254
255 /* global key/cert auth options. XXX move to permanent ssh->authctxt? */
256 struct sshauthopt *auth_opts = NULL;
257
258 /* sshd_config buffer */
259 struct sshbuf *cfg;
260
261 /* message to be displayed after login */
262 struct sshbuf *loginmsg;
263
264 /* Unprivileged user */
265 struct passwd *privsep_pw = NULL;
266
267 /* Prototypes for various functions defined later in this file. */
268 void destroy_sensitive_data(void);
269 void demote_sensitive_data(void);
270 static void do_ssh2_kex(void);
271
272 /*
273  * Close all listening sockets
274  */
275 static void
276 close_listen_socks(void)
277 {
278         int i;
279
280         for (i = 0; i < num_listen_socks; i++)
281                 close(listen_socks[i]);
282         num_listen_socks = -1;
283 }
284
285 static void
286 close_startup_pipes(void)
287 {
288         int i;
289
290         if (startup_pipes)
291                 for (i = 0; i < options.max_startups; i++)
292                         if (startup_pipes[i] != -1)
293                                 close(startup_pipes[i]);
294 }
295
296 /*
297  * Signal handler for SIGHUP.  Sshd execs itself when it receives SIGHUP;
298  * the effect is to reread the configuration file (and to regenerate
299  * the server key).
300  */
301
302 /*ARGSUSED*/
303 static void
304 sighup_handler(int sig)
305 {
306         int save_errno = errno;
307
308         received_sighup = 1;
309         errno = save_errno;
310 }
311
312 /*
313  * Called from the main program after receiving SIGHUP.
314  * Restarts the server.
315  */
316 static void
317 sighup_restart(void)
318 {
319         logit("Received SIGHUP; restarting.");
320         if (options.pid_file != NULL)
321                 unlink(options.pid_file);
322         platform_pre_restart();
323         close_listen_socks();
324         close_startup_pipes();
325         alarm(0);  /* alarm timer persists across exec */
326         signal(SIGHUP, SIG_IGN); /* will be restored after exec */
327         execv(saved_argv[0], saved_argv);
328         logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0],
329             strerror(errno));
330         exit(1);
331 }
332
333 /*
334  * Generic signal handler for terminating signals in the master daemon.
335  */
336 /*ARGSUSED*/
337 static void
338 sigterm_handler(int sig)
339 {
340         received_sigterm = sig;
341 }
342
343 /*
344  * SIGCHLD handler.  This is called whenever a child dies.  This will then
345  * reap any zombies left by exited children.
346  */
347 /*ARGSUSED*/
348 static void
349 main_sigchld_handler(int sig)
350 {
351         int save_errno = errno;
352         pid_t pid;
353         int status;
354
355         while ((pid = waitpid(-1, &status, WNOHANG)) > 0 ||
356             (pid < 0 && errno == EINTR))
357                 ;
358         errno = save_errno;
359 }
360
361 /*
362  * Signal handler for the alarm after the login grace period has expired.
363  */
364 /*ARGSUSED*/
365 static void
366 grace_alarm_handler(int sig)
367 {
368         if (use_privsep && pmonitor != NULL && pmonitor->m_pid > 0)
369                 kill(pmonitor->m_pid, SIGALRM);
370
371         /*
372          * Try to kill any processes that we have spawned, E.g. authorized
373          * keys command helpers.
374          */
375         if (getpgid(0) == getpid()) {
376                 signal(SIGTERM, SIG_IGN);
377                 kill(0, SIGTERM);
378         }
379
380         BLACKLIST_NOTIFY(BLACKLIST_AUTH_FAIL, "ssh");
381
382         /* Log error and exit. */
383         sigdie("Timeout before authentication for %s port %d",
384             ssh_remote_ipaddr(active_state), ssh_remote_port(active_state));
385 }
386
387 static void
388 sshd_exchange_identification(struct ssh *ssh, int sock_in, int sock_out)
389 {
390         u_int i;
391         int remote_major, remote_minor;
392         char *s;
393         char buf[256];                  /* Must not be larger than remote_version. */
394         char remote_version[256];       /* Must be at least as big as buf. */
395
396         xasprintf(&server_version_string, "SSH-%d.%d-%.100s%s%s\r\n",
397             PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
398             *options.version_addendum == '\0' ? "" : " ",
399             options.version_addendum);
400
401         /* Send our protocol version identification. */
402         if (atomicio(vwrite, sock_out, server_version_string,
403             strlen(server_version_string))
404             != strlen(server_version_string)) {
405                 logit("Could not write ident string to %s port %d",
406                     ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
407                 cleanup_exit(255);
408         }
409
410         /* Read other sides version identification. */
411         memset(buf, 0, sizeof(buf));
412         for (i = 0; i < sizeof(buf) - 1; i++) {
413                 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
414                         logit("Did not receive identification string "
415                             "from %s port %d",
416                             ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
417                         cleanup_exit(255);
418                 }
419                 if (buf[i] == '\r') {
420                         buf[i] = 0;
421                         /* Kludge for F-Secure Macintosh < 1.0.2 */
422                         if (i == 12 &&
423                             strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
424                                 break;
425                         continue;
426                 }
427                 if (buf[i] == '\n') {
428                         buf[i] = 0;
429                         break;
430                 }
431         }
432         buf[sizeof(buf) - 1] = 0;
433         client_version_string = xstrdup(buf);
434
435         /*
436          * Check that the versions match.  In future this might accept
437          * several versions and set appropriate flags to handle them.
438          */
439         if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
440             &remote_major, &remote_minor, remote_version) != 3) {
441                 s = "Protocol mismatch.\n";
442                 (void) atomicio(vwrite, sock_out, s, strlen(s));
443                 logit("Bad protocol version identification '%.100s' "
444                     "from %s port %d", client_version_string,
445                     ssh_remote_ipaddr(ssh), ssh_remote_port(ssh));
446                 close(sock_in);
447                 close(sock_out);
448                 cleanup_exit(255);
449         }
450         debug("Client protocol version %d.%d; client software version %.100s",
451             remote_major, remote_minor, remote_version);
452
453         ssh->compat = compat_datafellows(remote_version);
454
455         if ((ssh->compat & SSH_BUG_PROBE) != 0) {
456                 logit("probed from %s port %d with %s.  Don't panic.",
457                     ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
458                     client_version_string);
459                 cleanup_exit(255);
460         }
461         if ((ssh->compat & SSH_BUG_SCANNER) != 0) {
462                 logit("scanned from %s port %d with %s.  Don't panic.",
463                     ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
464                     client_version_string);
465                 cleanup_exit(255);
466         }
467         if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
468                 logit("Client version \"%.100s\" uses unsafe RSA signature "
469                     "scheme; disabling use of RSA keys", remote_version);
470         }
471
472         chop(server_version_string);
473         debug("Local version string %.200s", server_version_string);
474
475         if (remote_major != 2 &&
476             !(remote_major == 1 && remote_minor == 99)) {
477                 s = "Protocol major versions differ.\n";
478                 (void) atomicio(vwrite, sock_out, s, strlen(s));
479                 close(sock_in);
480                 close(sock_out);
481                 logit("Protocol major versions differ for %s port %d: "
482                     "%.200s vs. %.200s",
483                     ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
484                     server_version_string, client_version_string);
485                 cleanup_exit(255);
486         }
487 }
488
489 /* Destroy the host and server keys.  They will no longer be needed. */
490 void
491 destroy_sensitive_data(void)
492 {
493         u_int i;
494
495         for (i = 0; i < options.num_host_key_files; i++) {
496                 if (sensitive_data.host_keys[i]) {
497                         sshkey_free(sensitive_data.host_keys[i]);
498                         sensitive_data.host_keys[i] = NULL;
499                 }
500                 if (sensitive_data.host_certificates[i]) {
501                         sshkey_free(sensitive_data.host_certificates[i]);
502                         sensitive_data.host_certificates[i] = NULL;
503                 }
504         }
505 }
506
507 /* Demote private to public keys for network child */
508 void
509 demote_sensitive_data(void)
510 {
511         struct sshkey *tmp;
512         u_int i;
513         int r;
514
515         for (i = 0; i < options.num_host_key_files; i++) {
516                 if (sensitive_data.host_keys[i]) {
517                         if ((r = sshkey_from_private(
518                             sensitive_data.host_keys[i], &tmp)) != 0)
519                                 fatal("could not demote host %s key: %s",
520                                     sshkey_type(sensitive_data.host_keys[i]),
521                                     ssh_err(r));
522                         sshkey_free(sensitive_data.host_keys[i]);
523                         sensitive_data.host_keys[i] = tmp;
524                 }
525                 /* Certs do not need demotion */
526         }
527 }
528
529 static void
530 reseed_prngs(void)
531 {
532         u_int32_t rnd[256];
533
534 #ifdef WITH_OPENSSL
535         RAND_poll();
536 #endif
537         arc4random_stir(); /* noop on recent arc4random() implementations */
538         arc4random_buf(rnd, sizeof(rnd)); /* let arc4random notice PID change */
539
540 #ifdef WITH_OPENSSL
541         RAND_seed(rnd, sizeof(rnd));
542         /* give libcrypto a chance to notice the PID change */
543         if ((RAND_bytes((u_char *)rnd, 1)) != 1)
544                 fatal("%s: RAND_bytes failed", __func__);
545 #endif
546
547         explicit_bzero(rnd, sizeof(rnd));
548 }
549
550 static void
551 privsep_preauth_child(void)
552 {
553         gid_t gidset[1];
554
555         /* Enable challenge-response authentication for privilege separation */
556         privsep_challenge_enable();
557
558 #ifdef GSSAPI
559         /* Cache supported mechanism OIDs for later use */
560         ssh_gssapi_prepare_supported_oids();
561 #endif
562
563         reseed_prngs();
564
565         /* Demote the private keys to public keys. */
566         demote_sensitive_data();
567
568         /* Demote the child */
569         if (privsep_chroot) {
570                 /* Change our root directory */
571                 if (chroot(_PATH_PRIVSEP_CHROOT_DIR) == -1)
572                         fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR,
573                             strerror(errno));
574                 if (chdir("/") == -1)
575                         fatal("chdir(\"/\"): %s", strerror(errno));
576
577                 /* Drop our privileges */
578                 debug3("privsep user:group %u:%u", (u_int)privsep_pw->pw_uid,
579                     (u_int)privsep_pw->pw_gid);
580                 gidset[0] = privsep_pw->pw_gid;
581                 if (setgroups(1, gidset) < 0)
582                         fatal("setgroups: %.100s", strerror(errno));
583                 permanently_set_uid(privsep_pw);
584         }
585 }
586
587 static int
588 privsep_preauth(Authctxt *authctxt)
589 {
590         int status, r;
591         pid_t pid;
592         struct ssh_sandbox *box = NULL;
593
594         /* Set up unprivileged child process to deal with network data */
595         pmonitor = monitor_init();
596         /* Store a pointer to the kex for later rekeying */
597         pmonitor->m_pkex = &active_state->kex;
598
599         if (use_privsep == PRIVSEP_ON)
600                 box = ssh_sandbox_init(pmonitor);
601         pid = fork();
602         if (pid == -1) {
603                 fatal("fork of unprivileged child failed");
604         } else if (pid != 0) {
605                 debug2("Network child is on pid %ld", (long)pid);
606
607                 pmonitor->m_pid = pid;
608                 if (have_agent) {
609                         r = ssh_get_authentication_socket(&auth_sock);
610                         if (r != 0) {
611                                 error("Could not get agent socket: %s",
612                                     ssh_err(r));
613                                 have_agent = 0;
614                         }
615                 }
616                 if (box != NULL)
617                         ssh_sandbox_parent_preauth(box, pid);
618                 monitor_child_preauth(authctxt, pmonitor);
619
620                 /* Wait for the child's exit status */
621                 while (waitpid(pid, &status, 0) < 0) {
622                         if (errno == EINTR)
623                                 continue;
624                         pmonitor->m_pid = -1;
625                         fatal("%s: waitpid: %s", __func__, strerror(errno));
626                 }
627                 privsep_is_preauth = 0;
628                 pmonitor->m_pid = -1;
629                 if (WIFEXITED(status)) {
630                         if (WEXITSTATUS(status) != 0)
631                                 fatal("%s: preauth child exited with status %d",
632                                     __func__, WEXITSTATUS(status));
633                 } else if (WIFSIGNALED(status))
634                         fatal("%s: preauth child terminated by signal %d",
635                             __func__, WTERMSIG(status));
636                 if (box != NULL)
637                         ssh_sandbox_parent_finish(box);
638                 return 1;
639         } else {
640                 /* child */
641                 close(pmonitor->m_sendfd);
642                 close(pmonitor->m_log_recvfd);
643
644                 /* Arrange for logging to be sent to the monitor */
645                 set_log_handler(mm_log_handler, pmonitor);
646
647                 privsep_preauth_child();
648                 setproctitle("%s", "[net]");
649                 if (box != NULL)
650                         ssh_sandbox_child(box);
651
652                 return 0;
653         }
654 }
655
656 static void
657 privsep_postauth(Authctxt *authctxt)
658 {
659 #ifdef DISABLE_FD_PASSING
660         if (1) {
661 #else
662         if (authctxt->pw->pw_uid == 0) {
663 #endif
664                 /* File descriptor passing is broken or root login */
665                 use_privsep = 0;
666                 goto skip;
667         }
668
669         /* New socket pair */
670         monitor_reinit(pmonitor);
671
672         pmonitor->m_pid = fork();
673         if (pmonitor->m_pid == -1)
674                 fatal("fork of unprivileged child failed");
675         else if (pmonitor->m_pid != 0) {
676                 verbose("User child is on pid %ld", (long)pmonitor->m_pid);
677                 sshbuf_reset(loginmsg);
678                 monitor_clear_keystate(pmonitor);
679                 monitor_child_postauth(pmonitor);
680
681                 /* NEVERREACHED */
682                 exit(0);
683         }
684
685         /* child */
686
687         close(pmonitor->m_sendfd);
688         pmonitor->m_sendfd = -1;
689
690         /* Demote the private keys to public keys. */
691         demote_sensitive_data();
692
693         reseed_prngs();
694
695         /* Drop privileges */
696         do_setusercontext(authctxt->pw);
697
698  skip:
699         /* It is safe now to apply the key state */
700         monitor_apply_keystate(pmonitor);
701
702         /*
703          * Tell the packet layer that authentication was successful, since
704          * this information is not part of the key state.
705          */
706         packet_set_authenticated();
707 }
708
709 static void
710 append_hostkey_type(struct sshbuf *b, const char *s)
711 {
712         int r;
713
714         if (match_pattern_list(s, options.hostkeyalgorithms, 0) != 1) {
715                 debug3("%s: %s key not permitted by HostkeyAlgorithms",
716                     __func__, s);
717                 return;
718         }
719         if ((r = sshbuf_putf(b, "%s%s", sshbuf_len(b) > 0 ? "," : "", s)) != 0)
720                 fatal("%s: sshbuf_putf: %s", __func__, ssh_err(r));
721 }
722
723 static char *
724 list_hostkey_types(void)
725 {
726         struct sshbuf *b;
727         struct sshkey *key;
728         char *ret;
729         u_int i;
730
731         if ((b = sshbuf_new()) == NULL)
732                 fatal("%s: sshbuf_new failed", __func__);
733         for (i = 0; i < options.num_host_key_files; i++) {
734                 key = sensitive_data.host_keys[i];
735                 if (key == NULL)
736                         key = sensitive_data.host_pubkeys[i];
737                 if (key == NULL)
738                         continue;
739                 switch (key->type) {
740                 case KEY_RSA:
741                         /* for RSA we also support SHA2 signatures */
742                         append_hostkey_type(b, "rsa-sha2-512");
743                         append_hostkey_type(b, "rsa-sha2-256");
744                         /* FALLTHROUGH */
745                 case KEY_DSA:
746                 case KEY_ECDSA:
747                 case KEY_ED25519:
748                 case KEY_XMSS:
749                         append_hostkey_type(b, sshkey_ssh_name(key));
750                         break;
751                 }
752                 /* If the private key has a cert peer, then list that too */
753                 key = sensitive_data.host_certificates[i];
754                 if (key == NULL)
755                         continue;
756                 switch (key->type) {
757                 case KEY_RSA_CERT:
758                         /* for RSA we also support SHA2 signatures */
759                         append_hostkey_type(b,
760                             "rsa-sha2-512-cert-v01@openssh.com");
761                         append_hostkey_type(b,
762                             "rsa-sha2-256-cert-v01@openssh.com");
763                         /* FALLTHROUGH */
764                 case KEY_DSA_CERT:
765                 case KEY_ECDSA_CERT:
766                 case KEY_ED25519_CERT:
767                 case KEY_XMSS_CERT:
768                         append_hostkey_type(b, sshkey_ssh_name(key));
769                         break;
770                 }
771         }
772         if ((ret = sshbuf_dup_string(b)) == NULL)
773                 fatal("%s: sshbuf_dup_string failed", __func__);
774         sshbuf_free(b);
775         debug("%s: %s", __func__, ret);
776         return ret;
777 }
778
779 static struct sshkey *
780 get_hostkey_by_type(int type, int nid, int need_private, struct ssh *ssh)
781 {
782         u_int i;
783         struct sshkey *key;
784
785         for (i = 0; i < options.num_host_key_files; i++) {
786                 switch (type) {
787                 case KEY_RSA_CERT:
788                 case KEY_DSA_CERT:
789                 case KEY_ECDSA_CERT:
790                 case KEY_ED25519_CERT:
791                 case KEY_XMSS_CERT:
792                         key = sensitive_data.host_certificates[i];
793                         break;
794                 default:
795                         key = sensitive_data.host_keys[i];
796                         if (key == NULL && !need_private)
797                                 key = sensitive_data.host_pubkeys[i];
798                         break;
799                 }
800                 if (key != NULL && key->type == type &&
801                     (key->type != KEY_ECDSA || key->ecdsa_nid == nid))
802                         return need_private ?
803                             sensitive_data.host_keys[i] : key;
804         }
805         return NULL;
806 }
807
808 struct sshkey *
809 get_hostkey_public_by_type(int type, int nid, struct ssh *ssh)
810 {
811         return get_hostkey_by_type(type, nid, 0, ssh);
812 }
813
814 struct sshkey *
815 get_hostkey_private_by_type(int type, int nid, struct ssh *ssh)
816 {
817         return get_hostkey_by_type(type, nid, 1, ssh);
818 }
819
820 struct sshkey *
821 get_hostkey_by_index(int ind)
822 {
823         if (ind < 0 || (u_int)ind >= options.num_host_key_files)
824                 return (NULL);
825         return (sensitive_data.host_keys[ind]);
826 }
827
828 struct sshkey *
829 get_hostkey_public_by_index(int ind, struct ssh *ssh)
830 {
831         if (ind < 0 || (u_int)ind >= options.num_host_key_files)
832                 return (NULL);
833         return (sensitive_data.host_pubkeys[ind]);
834 }
835
836 int
837 get_hostkey_index(struct sshkey *key, int compare, struct ssh *ssh)
838 {
839         u_int i;
840
841         for (i = 0; i < options.num_host_key_files; i++) {
842                 if (sshkey_is_cert(key)) {
843                         if (key == sensitive_data.host_certificates[i] ||
844                             (compare && sensitive_data.host_certificates[i] &&
845                             sshkey_equal(key,
846                             sensitive_data.host_certificates[i])))
847                                 return (i);
848                 } else {
849                         if (key == sensitive_data.host_keys[i] ||
850                             (compare && sensitive_data.host_keys[i] &&
851                             sshkey_equal(key, sensitive_data.host_keys[i])))
852                                 return (i);
853                         if (key == sensitive_data.host_pubkeys[i] ||
854                             (compare && sensitive_data.host_pubkeys[i] &&
855                             sshkey_equal(key, sensitive_data.host_pubkeys[i])))
856                                 return (i);
857                 }
858         }
859         return (-1);
860 }
861
862 /* Inform the client of all hostkeys */
863 static void
864 notify_hostkeys(struct ssh *ssh)
865 {
866         struct sshbuf *buf;
867         struct sshkey *key;
868         u_int i, nkeys;
869         int r;
870         char *fp;
871
872         /* Some clients cannot cope with the hostkeys message, skip those. */
873         if (datafellows & SSH_BUG_HOSTKEYS)
874                 return;
875
876         if ((buf = sshbuf_new()) == NULL)
877                 fatal("%s: sshbuf_new", __func__);
878         for (i = nkeys = 0; i < options.num_host_key_files; i++) {
879                 key = get_hostkey_public_by_index(i, ssh);
880                 if (key == NULL || key->type == KEY_UNSPEC ||
881                     sshkey_is_cert(key))
882                         continue;
883                 fp = sshkey_fingerprint(key, options.fingerprint_hash,
884                     SSH_FP_DEFAULT);
885                 debug3("%s: key %d: %s %s", __func__, i,
886                     sshkey_ssh_name(key), fp);
887                 free(fp);
888                 if (nkeys == 0) {
889                         packet_start(SSH2_MSG_GLOBAL_REQUEST);
890                         packet_put_cstring("hostkeys-00@openssh.com");
891                         packet_put_char(0); /* want-reply */
892                 }
893                 sshbuf_reset(buf);
894                 if ((r = sshkey_putb(key, buf)) != 0)
895                         fatal("%s: couldn't put hostkey %d: %s",
896                             __func__, i, ssh_err(r));
897                 packet_put_string(sshbuf_ptr(buf), sshbuf_len(buf));
898                 nkeys++;
899         }
900         debug3("%s: sent %u hostkeys", __func__, nkeys);
901         if (nkeys == 0)
902                 fatal("%s: no hostkeys", __func__);
903         packet_send();
904         sshbuf_free(buf);
905 }
906
907 /*
908  * returns 1 if connection should be dropped, 0 otherwise.
909  * dropping starts at connection #max_startups_begin with a probability
910  * of (max_startups_rate/100). the probability increases linearly until
911  * all connections are dropped for startups > max_startups
912  */
913 static int
914 drop_connection(int startups)
915 {
916         int p, r;
917
918         if (startups < options.max_startups_begin)
919                 return 0;
920         if (startups >= options.max_startups)
921                 return 1;
922         if (options.max_startups_rate == 100)
923                 return 1;
924
925         p  = 100 - options.max_startups_rate;
926         p *= startups - options.max_startups_begin;
927         p /= options.max_startups - options.max_startups_begin;
928         p += options.max_startups_rate;
929         r = arc4random_uniform(100);
930
931         debug("drop_connection: p %d, r %d", p, r);
932         return (r < p) ? 1 : 0;
933 }
934
935 static void
936 usage(void)
937 {
938         if (options.version_addendum && *options.version_addendum != '\0')
939                 fprintf(stderr, "%s %s, %s\n",
940                     SSH_RELEASE,
941                     options.version_addendum, OPENSSL_VERSION_STRING);
942         else
943                 fprintf(stderr, "%s, %s\n",
944                     SSH_RELEASE, OPENSSL_VERSION_STRING);
945         fprintf(stderr,
946 "usage: sshd [-46DdeiqTt] [-C connection_spec] [-c host_cert_file]\n"
947 "            [-E log_file] [-f config_file] [-g login_grace_time]\n"
948 "            [-h host_key_file] [-o option] [-p port] [-u len]\n"
949         );
950         exit(1);
951 }
952
953 static void
954 send_rexec_state(int fd, struct sshbuf *conf)
955 {
956         struct sshbuf *m;
957         int r;
958
959         debug3("%s: entering fd = %d config len %zu", __func__, fd,
960             sshbuf_len(conf));
961
962         /*
963          * Protocol from reexec master to child:
964          *      string  configuration
965          *      string rngseed          (only if OpenSSL is not self-seeded)
966          */
967         if ((m = sshbuf_new()) == NULL)
968                 fatal("%s: sshbuf_new failed", __func__);
969         if ((r = sshbuf_put_stringb(m, conf)) != 0)
970                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
971
972 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
973         rexec_send_rng_seed(m);
974 #endif
975
976         if (ssh_msg_send(fd, 0, m) == -1)
977                 fatal("%s: ssh_msg_send failed", __func__);
978
979         sshbuf_free(m);
980
981         debug3("%s: done", __func__);
982 }
983
984 static void
985 recv_rexec_state(int fd, struct sshbuf *conf)
986 {
987         struct sshbuf *m;
988         u_char *cp, ver;
989         size_t len;
990         int r;
991
992         debug3("%s: entering fd = %d", __func__, fd);
993
994         if ((m = sshbuf_new()) == NULL)
995                 fatal("%s: sshbuf_new failed", __func__);
996         if (ssh_msg_recv(fd, m) == -1)
997                 fatal("%s: ssh_msg_recv failed", __func__);
998         if ((r = sshbuf_get_u8(m, &ver)) != 0)
999                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1000         if (ver != 0)
1001                 fatal("%s: rexec version mismatch", __func__);
1002         if ((r = sshbuf_get_string(m, &cp, &len)) != 0)
1003                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1004         if (conf != NULL && (r = sshbuf_put(conf, cp, len)))
1005                 fatal("%s: buffer error: %s", __func__, ssh_err(r));
1006 #if defined(WITH_OPENSSL) && !defined(OPENSSL_PRNG_ONLY)
1007         rexec_recv_rng_seed(m);
1008 #endif
1009
1010         free(cp);
1011         sshbuf_free(m);
1012
1013         debug3("%s: done", __func__);
1014 }
1015
1016 /* Accept a connection from inetd */
1017 static void
1018 server_accept_inetd(int *sock_in, int *sock_out)
1019 {
1020         int fd;
1021
1022         startup_pipe = -1;
1023         if (rexeced_flag) {
1024                 close(REEXEC_CONFIG_PASS_FD);
1025                 *sock_in = *sock_out = dup(STDIN_FILENO);
1026                 if (!debug_flag) {
1027                         startup_pipe = dup(REEXEC_STARTUP_PIPE_FD);
1028                         close(REEXEC_STARTUP_PIPE_FD);
1029                 }
1030         } else {
1031                 *sock_in = dup(STDIN_FILENO);
1032                 *sock_out = dup(STDOUT_FILENO);
1033         }
1034         /*
1035          * We intentionally do not close the descriptors 0, 1, and 2
1036          * as our code for setting the descriptors won't work if
1037          * ttyfd happens to be one of those.
1038          */
1039         if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
1040                 dup2(fd, STDIN_FILENO);
1041                 dup2(fd, STDOUT_FILENO);
1042                 if (!log_stderr)
1043                         dup2(fd, STDERR_FILENO);
1044                 if (fd > (log_stderr ? STDERR_FILENO : STDOUT_FILENO))
1045                         close(fd);
1046         }
1047         debug("inetd sockets after dupping: %d, %d", *sock_in, *sock_out);
1048 }
1049
1050 /*
1051  * Listen for TCP connections
1052  */
1053 static void
1054 listen_on_addrs(struct listenaddr *la)
1055 {
1056         int ret, listen_sock;
1057         struct addrinfo *ai;
1058         char ntop[NI_MAXHOST], strport[NI_MAXSERV];
1059
1060         for (ai = la->addrs; ai; ai = ai->ai_next) {
1061                 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
1062                         continue;
1063                 if (num_listen_socks >= MAX_LISTEN_SOCKS)
1064                         fatal("Too many listen sockets. "
1065                             "Enlarge MAX_LISTEN_SOCKS");
1066                 if ((ret = getnameinfo(ai->ai_addr, ai->ai_addrlen,
1067                     ntop, sizeof(ntop), strport, sizeof(strport),
1068                     NI_NUMERICHOST|NI_NUMERICSERV)) != 0) {
1069                         error("getnameinfo failed: %.100s",
1070                             ssh_gai_strerror(ret));
1071                         continue;
1072                 }
1073                 /* Create socket for listening. */
1074                 listen_sock = socket(ai->ai_family, ai->ai_socktype,
1075                     ai->ai_protocol);
1076                 if (listen_sock < 0) {
1077                         /* kernel may not support ipv6 */
1078                         verbose("socket: %.100s", strerror(errno));
1079                         continue;
1080                 }
1081                 if (set_nonblock(listen_sock) == -1) {
1082                         close(listen_sock);
1083                         continue;
1084                 }
1085                 if (fcntl(listen_sock, F_SETFD, FD_CLOEXEC) == -1) {
1086                         verbose("socket: CLOEXEC: %s", strerror(errno));
1087                         close(listen_sock);
1088                         continue;
1089                 }
1090                 /* Socket options */
1091                 set_reuseaddr(listen_sock);
1092                 if (la->rdomain != NULL &&
1093                     set_rdomain(listen_sock, la->rdomain) == -1) {
1094                         close(listen_sock);
1095                         continue;
1096                 }
1097
1098                 /* Only communicate in IPv6 over AF_INET6 sockets. */
1099                 if (ai->ai_family == AF_INET6)
1100                         sock_set_v6only(listen_sock);
1101
1102                 debug("Bind to port %s on %s.", strport, ntop);
1103
1104                 /* Bind the socket to the desired port. */
1105                 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
1106                         error("Bind to port %s on %s failed: %.200s.",
1107                             strport, ntop, strerror(errno));
1108                         close(listen_sock);
1109                         continue;
1110                 }
1111                 listen_socks[num_listen_socks] = listen_sock;
1112                 num_listen_socks++;
1113
1114                 /* Start listening on the port. */
1115                 if (listen(listen_sock, SSH_LISTEN_BACKLOG) < 0)
1116                         fatal("listen on [%s]:%s: %.100s",
1117                             ntop, strport, strerror(errno));
1118                 logit("Server listening on %s port %s%s%s.",
1119                     ntop, strport,
1120                     la->rdomain == NULL ? "" : " rdomain ",
1121                     la->rdomain == NULL ? "" : la->rdomain);
1122         }
1123 }
1124
1125 static void
1126 server_listen(void)
1127 {
1128         u_int i;
1129
1130         for (i = 0; i < options.num_listen_addrs; i++) {
1131                 listen_on_addrs(&options.listen_addrs[i]);
1132                 freeaddrinfo(options.listen_addrs[i].addrs);
1133                 free(options.listen_addrs[i].rdomain);
1134                 memset(&options.listen_addrs[i], 0,
1135                     sizeof(options.listen_addrs[i]));
1136         }
1137         free(options.listen_addrs);
1138         options.listen_addrs = NULL;
1139         options.num_listen_addrs = 0;
1140
1141         if (!num_listen_socks)
1142                 fatal("Cannot bind any address.");
1143 }
1144
1145 /*
1146  * The main TCP accept loop. Note that, for the non-debug case, returns
1147  * from this function are in a forked subprocess.
1148  */
1149 static void
1150 server_accept_loop(int *sock_in, int *sock_out, int *newsock, int *config_s)
1151 {
1152         fd_set *fdset;
1153         int i, j, ret, maxfd;
1154         int startups = 0;
1155         int startup_p[2] = { -1 , -1 };
1156         struct sockaddr_storage from;
1157         socklen_t fromlen;
1158         pid_t pid;
1159         u_char rnd[256];
1160
1161         /* setup fd set for accept */
1162         fdset = NULL;
1163         maxfd = 0;
1164         for (i = 0; i < num_listen_socks; i++)
1165                 if (listen_socks[i] > maxfd)
1166                         maxfd = listen_socks[i];
1167         /* pipes connected to unauthenticated childs */
1168         startup_pipes = xcalloc(options.max_startups, sizeof(int));
1169         for (i = 0; i < options.max_startups; i++)
1170                 startup_pipes[i] = -1;
1171
1172         /*
1173          * Stay listening for connections until the system crashes or
1174          * the daemon is killed with a signal.
1175          */
1176         for (;;) {
1177                 if (received_sighup)
1178                         sighup_restart();
1179                 free(fdset);
1180                 fdset = xcalloc(howmany(maxfd + 1, NFDBITS),
1181                     sizeof(fd_mask));
1182
1183                 for (i = 0; i < num_listen_socks; i++)
1184                         FD_SET(listen_socks[i], fdset);
1185                 for (i = 0; i < options.max_startups; i++)
1186                         if (startup_pipes[i] != -1)
1187                                 FD_SET(startup_pipes[i], fdset);
1188
1189                 /* Wait in select until there is a connection. */
1190                 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1191                 if (ret < 0 && errno != EINTR)
1192                         error("select: %.100s", strerror(errno));
1193                 if (received_sigterm) {
1194                         logit("Received signal %d; terminating.",
1195                             (int) received_sigterm);
1196                         close_listen_socks();
1197                         if (options.pid_file != NULL)
1198                                 unlink(options.pid_file);
1199                         exit(received_sigterm == SIGTERM ? 0 : 255);
1200                 }
1201                 if (ret < 0)
1202                         continue;
1203
1204                 for (i = 0; i < options.max_startups; i++)
1205                         if (startup_pipes[i] != -1 &&
1206                             FD_ISSET(startup_pipes[i], fdset)) {
1207                                 /*
1208                                  * the read end of the pipe is ready
1209                                  * if the child has closed the pipe
1210                                  * after successful authentication
1211                                  * or if the child has died
1212                                  */
1213                                 close(startup_pipes[i]);
1214                                 startup_pipes[i] = -1;
1215                                 startups--;
1216                         }
1217                 for (i = 0; i < num_listen_socks; i++) {
1218                         if (!FD_ISSET(listen_socks[i], fdset))
1219                                 continue;
1220                         fromlen = sizeof(from);
1221                         *newsock = accept(listen_socks[i],
1222                             (struct sockaddr *)&from, &fromlen);
1223                         if (*newsock < 0) {
1224                                 if (errno != EINTR && errno != EWOULDBLOCK &&
1225                                     errno != ECONNABORTED && errno != EAGAIN)
1226                                         error("accept: %.100s",
1227                                             strerror(errno));
1228                                 if (errno == EMFILE || errno == ENFILE)
1229                                         usleep(100 * 1000);
1230                                 continue;
1231                         }
1232                         if (unset_nonblock(*newsock) == -1) {
1233                                 close(*newsock);
1234                                 continue;
1235                         }
1236                         if (drop_connection(startups) == 1) {
1237                                 char *laddr = get_local_ipaddr(*newsock);
1238                                 char *raddr = get_peer_ipaddr(*newsock);
1239
1240                                 verbose("drop connection #%d from [%s]:%d "
1241                                     "on [%s]:%d past MaxStartups", startups,
1242                                     raddr, get_peer_port(*newsock),
1243                                     laddr, get_local_port(*newsock));
1244                                 free(laddr);
1245                                 free(raddr);
1246                                 close(*newsock);
1247                                 continue;
1248                         }
1249                         if (pipe(startup_p) == -1) {
1250                                 close(*newsock);
1251                                 continue;
1252                         }
1253
1254                         if (rexec_flag && socketpair(AF_UNIX,
1255                             SOCK_STREAM, 0, config_s) == -1) {
1256                                 error("reexec socketpair: %s",
1257                                     strerror(errno));
1258                                 close(*newsock);
1259                                 close(startup_p[0]);
1260                                 close(startup_p[1]);
1261                                 continue;
1262                         }
1263
1264                         for (j = 0; j < options.max_startups; j++)
1265                                 if (startup_pipes[j] == -1) {
1266                                         startup_pipes[j] = startup_p[0];
1267                                         if (maxfd < startup_p[0])
1268                                                 maxfd = startup_p[0];
1269                                         startups++;
1270                                         break;
1271                                 }
1272
1273                         /*
1274                          * Got connection.  Fork a child to handle it, unless
1275                          * we are in debugging mode.
1276                          */
1277                         if (debug_flag) {
1278                                 /*
1279                                  * In debugging mode.  Close the listening
1280                                  * socket, and start processing the
1281                                  * connection without forking.
1282                                  */
1283                                 debug("Server will not fork when running in debugging mode.");
1284                                 close_listen_socks();
1285                                 *sock_in = *newsock;
1286                                 *sock_out = *newsock;
1287                                 close(startup_p[0]);
1288                                 close(startup_p[1]);
1289                                 startup_pipe = -1;
1290                                 pid = getpid();
1291                                 if (rexec_flag) {
1292                                         send_rexec_state(config_s[0], cfg);
1293                                         close(config_s[0]);
1294                                 }
1295                                 break;
1296                         }
1297
1298                         /*
1299                          * Normal production daemon.  Fork, and have
1300                          * the child process the connection. The
1301                          * parent continues listening.
1302                          */
1303                         platform_pre_fork();
1304                         if ((pid = fork()) == 0) {
1305                                 /*
1306                                  * Child.  Close the listening and
1307                                  * max_startup sockets.  Start using
1308                                  * the accepted socket. Reinitialize
1309                                  * logging (since our pid has changed).
1310                                  * We break out of the loop to handle
1311                                  * the connection.
1312                                  */
1313                                 platform_post_fork_child();
1314                                 startup_pipe = startup_p[1];
1315                                 close_startup_pipes();
1316                                 close_listen_socks();
1317                                 *sock_in = *newsock;
1318                                 *sock_out = *newsock;
1319                                 log_init(__progname,
1320                                     options.log_level,
1321                                     options.log_facility,
1322                                     log_stderr);
1323                                 if (rexec_flag)
1324                                         close(config_s[0]);
1325                                 break;
1326                         }
1327
1328                         /* Parent.  Stay in the loop. */
1329                         platform_post_fork_parent(pid);
1330                         if (pid < 0)
1331                                 error("fork: %.100s", strerror(errno));
1332                         else
1333                                 debug("Forked child %ld.", (long)pid);
1334
1335                         close(startup_p[1]);
1336
1337                         if (rexec_flag) {
1338                                 send_rexec_state(config_s[0], cfg);
1339                                 close(config_s[0]);
1340                                 close(config_s[1]);
1341                         }
1342                         close(*newsock);
1343
1344                         /*
1345                          * Ensure that our random state differs
1346                          * from that of the child
1347                          */
1348                         arc4random_stir();
1349                         arc4random_buf(rnd, sizeof(rnd));
1350 #ifdef WITH_OPENSSL
1351                         RAND_seed(rnd, sizeof(rnd));
1352                         if ((RAND_bytes((u_char *)rnd, 1)) != 1)
1353                                 fatal("%s: RAND_bytes failed", __func__);
1354 #endif
1355                         explicit_bzero(rnd, sizeof(rnd));
1356                 }
1357
1358                 /* child process check (or debug mode) */
1359                 if (num_listen_socks < 0)
1360                         break;
1361         }
1362 }
1363
1364 /*
1365  * If IP options are supported, make sure there are none (log and
1366  * return an error if any are found).  Basically we are worried about
1367  * source routing; it can be used to pretend you are somebody
1368  * (ip-address) you are not. That itself may be "almost acceptable"
1369  * under certain circumstances, but rhosts authentication is useless
1370  * if source routing is accepted. Notice also that if we just dropped
1371  * source routing here, the other side could use IP spoofing to do
1372  * rest of the interaction and could still bypass security.  So we
1373  * exit here if we detect any IP options.
1374  */
1375 static void
1376 check_ip_options(struct ssh *ssh)
1377 {
1378 #ifdef IP_OPTIONS
1379         int sock_in = ssh_packet_get_connection_in(ssh);
1380         struct sockaddr_storage from;
1381         u_char opts[200];
1382         socklen_t i, option_size = sizeof(opts), fromlen = sizeof(from);
1383         char text[sizeof(opts) * 3 + 1];
1384
1385         memset(&from, 0, sizeof(from));
1386         if (getpeername(sock_in, (struct sockaddr *)&from,
1387             &fromlen) < 0)
1388                 return;
1389         if (from.ss_family != AF_INET)
1390                 return;
1391         /* XXX IPv6 options? */
1392
1393         if (getsockopt(sock_in, IPPROTO_IP, IP_OPTIONS, opts,
1394             &option_size) >= 0 && option_size != 0) {
1395                 text[0] = '\0';
1396                 for (i = 0; i < option_size; i++)
1397                         snprintf(text + i*3, sizeof(text) - i*3,
1398                             " %2.2x", opts[i]);
1399                 fatal("Connection from %.100s port %d with IP opts: %.800s",
1400                     ssh_remote_ipaddr(ssh), ssh_remote_port(ssh), text);
1401         }
1402         return;
1403 #endif /* IP_OPTIONS */
1404 }
1405
1406 /* Set the routing domain for this process */
1407 static void
1408 set_process_rdomain(struct ssh *ssh, const char *name)
1409 {
1410 #if defined(HAVE_SYS_SET_PROCESS_RDOMAIN)
1411         if (name == NULL)
1412                 return; /* default */
1413
1414         if (strcmp(name, "%D") == 0) {
1415                 /* "expands" to routing domain of connection */
1416                 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1417                         return;
1418         }
1419         /* NB. We don't pass 'ssh' to sys_set_process_rdomain() */
1420         return sys_set_process_rdomain(name);
1421 #elif defined(__OpenBSD__)
1422         int rtable, ortable = getrtable();
1423         const char *errstr;
1424
1425         if (name == NULL)
1426                 return; /* default */
1427
1428         if (strcmp(name, "%D") == 0) {
1429                 /* "expands" to routing domain of connection */
1430                 if ((name = ssh_packet_rdomain_in(ssh)) == NULL)
1431                         return;
1432         }
1433
1434         rtable = (int)strtonum(name, 0, 255, &errstr);
1435         if (errstr != NULL) /* Shouldn't happen */
1436                 fatal("Invalid routing domain \"%s\": %s", name, errstr);
1437         if (rtable != ortable && setrtable(rtable) != 0)
1438                 fatal("Unable to set routing domain %d: %s",
1439                     rtable, strerror(errno));
1440         debug("%s: set routing domain %d (was %d)", __func__, rtable, ortable);
1441 #else /* defined(__OpenBSD__) */
1442         fatal("Unable to set routing domain: not supported in this platform");
1443 #endif
1444 }
1445
1446 static void
1447 accumulate_host_timing_secret(struct sshbuf *server_cfg,
1448     const struct sshkey *key)
1449 {
1450         static struct ssh_digest_ctx *ctx;
1451         u_char *hash;
1452         size_t len;
1453         struct sshbuf *buf;
1454         int r;
1455
1456         if (ctx == NULL && (ctx = ssh_digest_start(SSH_DIGEST_SHA512)) == NULL)
1457                 fatal("%s: ssh_digest_start", __func__);
1458         if (key == NULL) { /* finalize */
1459                 /* add server config in case we are using agent for host keys */
1460                 if (ssh_digest_update(ctx, sshbuf_ptr(server_cfg),
1461                     sshbuf_len(server_cfg)) != 0)
1462                         fatal("%s: ssh_digest_update", __func__);
1463                 len = ssh_digest_bytes(SSH_DIGEST_SHA512);
1464                 hash = xmalloc(len);
1465                 if (ssh_digest_final(ctx, hash, len) != 0)
1466                         fatal("%s: ssh_digest_final", __func__);
1467                 options.timing_secret = PEEK_U64(hash);
1468                 freezero(hash, len);
1469                 ssh_digest_free(ctx);
1470                 ctx = NULL;
1471                 return;
1472         }
1473         if ((buf = sshbuf_new()) == NULL)
1474                 fatal("%s could not allocate buffer", __func__);
1475         if ((r = sshkey_private_serialize(key, buf)) != 0)
1476                 fatal("sshkey_private_serialize: %s", ssh_err(r));
1477         if (ssh_digest_update(ctx, sshbuf_ptr(buf), sshbuf_len(buf)) != 0)
1478                 fatal("%s: ssh_digest_update", __func__);
1479         sshbuf_reset(buf);
1480         sshbuf_free(buf);
1481 }
1482
1483 /*
1484  * Main program for the daemon.
1485  */
1486 int
1487 main(int ac, char **av)
1488 {
1489         struct ssh *ssh = NULL;
1490         extern char *optarg;
1491         extern int optind;
1492         int r, opt, on = 1, already_daemon, remote_port;
1493         int sock_in = -1, sock_out = -1, newsock = -1;
1494         const char *remote_ip, *rdomain;
1495         char *fp, *line, *laddr, *logfile = NULL;
1496         int config_s[2] = { -1 , -1 };
1497         u_int i, j;
1498         u_int64_t ibytes, obytes;
1499         mode_t new_umask;
1500         struct sshkey *key;
1501         struct sshkey *pubkey;
1502         int keytype;
1503         Authctxt *authctxt;
1504         struct connection_info *connection_info = NULL;
1505
1506         ssh_malloc_init();      /* must be called before any mallocs */
1507
1508 #ifdef HAVE_SECUREWARE
1509         (void)set_auth_parameters(ac, av);
1510 #endif
1511         __progname = ssh_get_progname(av[0]);
1512
1513         /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1514         saved_argc = ac;
1515         rexec_argc = ac;
1516         saved_argv = xcalloc(ac + 1, sizeof(*saved_argv));
1517         for (i = 0; (int)i < ac; i++)
1518                 saved_argv[i] = xstrdup(av[i]);
1519         saved_argv[i] = NULL;
1520
1521 #ifndef HAVE_SETPROCTITLE
1522         /* Prepare for later setproctitle emulation */
1523         compat_init_setproctitle(ac, av);
1524         av = saved_argv;
1525 #endif
1526
1527         if (geteuid() == 0 && setgroups(0, NULL) == -1)
1528                 debug("setgroups(): %.200s", strerror(errno));
1529
1530         /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1531         sanitise_stdfd();
1532
1533         /* Initialize configuration options to their default values. */
1534         initialize_server_options(&options);
1535
1536         /* Parse command-line arguments. */
1537         while ((opt = getopt(ac, av,
1538             "C:E:b:c:f:g:h:k:o:p:u:46DQRTdeiqrt")) != -1) {
1539                 switch (opt) {
1540                 case '4':
1541                         options.address_family = AF_INET;
1542                         break;
1543                 case '6':
1544                         options.address_family = AF_INET6;
1545                         break;
1546                 case 'f':
1547                         config_file_name = optarg;
1548                         break;
1549                 case 'c':
1550                         servconf_add_hostcert("[command-line]", 0,
1551                             &options, optarg);
1552                         break;
1553                 case 'd':
1554                         if (debug_flag == 0) {
1555                                 debug_flag = 1;
1556                                 options.log_level = SYSLOG_LEVEL_DEBUG1;
1557                         } else if (options.log_level < SYSLOG_LEVEL_DEBUG3)
1558                                 options.log_level++;
1559                         break;
1560                 case 'D':
1561                         no_daemon_flag = 1;
1562                         break;
1563                 case 'E':
1564                         logfile = optarg;
1565                         /* FALLTHROUGH */
1566                 case 'e':
1567                         log_stderr = 1;
1568                         break;
1569                 case 'i':
1570                         inetd_flag = 1;
1571                         break;
1572                 case 'r':
1573                         rexec_flag = 0;
1574                         break;
1575                 case 'R':
1576                         rexeced_flag = 1;
1577                         inetd_flag = 1;
1578                         break;
1579                 case 'Q':
1580                         /* ignored */
1581                         break;
1582                 case 'q':
1583                         options.log_level = SYSLOG_LEVEL_QUIET;
1584                         break;
1585                 case 'b':
1586                         /* protocol 1, ignored */
1587                         break;
1588                 case 'p':
1589                         options.ports_from_cmdline = 1;
1590                         if (options.num_ports >= MAX_PORTS) {
1591                                 fprintf(stderr, "too many ports.\n");
1592                                 exit(1);
1593                         }
1594                         options.ports[options.num_ports++] = a2port(optarg);
1595                         if (options.ports[options.num_ports-1] <= 0) {
1596                                 fprintf(stderr, "Bad port number.\n");
1597                                 exit(1);
1598                         }
1599                         break;
1600                 case 'g':
1601                         if ((options.login_grace_time = convtime(optarg)) == -1) {
1602                                 fprintf(stderr, "Invalid login grace time.\n");
1603                                 exit(1);
1604                         }
1605                         break;
1606                 case 'k':
1607                         /* protocol 1, ignored */
1608                         break;
1609                 case 'h':
1610                         servconf_add_hostkey("[command-line]", 0,
1611                             &options, optarg);
1612                         break;
1613                 case 't':
1614                         test_flag = 1;
1615                         break;
1616                 case 'T':
1617                         test_flag = 2;
1618                         break;
1619                 case 'C':
1620                         connection_info = get_connection_info(0, 0);
1621                         if (parse_server_match_testspec(connection_info,
1622                             optarg) == -1)
1623                                 exit(1);
1624                         break;
1625                 case 'u':
1626                         utmp_len = (u_int)strtonum(optarg, 0, HOST_NAME_MAX+1+1, NULL);
1627                         if (utmp_len > HOST_NAME_MAX+1) {
1628                                 fprintf(stderr, "Invalid utmp length.\n");
1629                                 exit(1);
1630                         }
1631                         break;
1632                 case 'o':
1633                         line = xstrdup(optarg);
1634                         if (process_server_config_line(&options, line,
1635                             "command-line", 0, NULL, NULL) != 0)
1636                                 exit(1);
1637                         free(line);
1638                         break;
1639                 case '?':
1640                 default:
1641                         usage();
1642                         break;
1643                 }
1644         }
1645         if (rexeced_flag || inetd_flag)
1646                 rexec_flag = 0;
1647         if (!test_flag && (rexec_flag && (av[0] == NULL || *av[0] != '/')))
1648                 fatal("sshd re-exec requires execution with an absolute path");
1649         if (rexeced_flag)
1650                 closefrom(REEXEC_MIN_FREE_FD);
1651         else
1652                 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD);
1653
1654 #ifdef WITH_OPENSSL
1655         OpenSSL_add_all_algorithms();
1656 #endif
1657
1658         /* If requested, redirect the logs to the specified logfile. */
1659         if (logfile != NULL)
1660                 log_redirect_stderr_to(logfile);
1661         /*
1662          * Force logging to stderr until we have loaded the private host
1663          * key (unless started from inetd)
1664          */
1665         log_init(__progname,
1666             options.log_level == SYSLOG_LEVEL_NOT_SET ?
1667             SYSLOG_LEVEL_INFO : options.log_level,
1668             options.log_facility == SYSLOG_FACILITY_NOT_SET ?
1669             SYSLOG_FACILITY_AUTH : options.log_facility,
1670             log_stderr || !inetd_flag);
1671
1672         /*
1673          * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1674          * root's environment
1675          */
1676         if (getenv("KRB5CCNAME") != NULL)
1677                 (void) unsetenv("KRB5CCNAME");
1678
1679         sensitive_data.have_ssh2_key = 0;
1680
1681         /*
1682          * If we're not doing an extended test do not silently ignore connection
1683          * test params.
1684          */
1685         if (test_flag < 2 && connection_info != NULL)
1686                 fatal("Config test connection parameter (-C) provided without "
1687                    "test mode (-T)");
1688
1689         /* Fetch our configuration */
1690         if ((cfg = sshbuf_new()) == NULL)
1691                 fatal("%s: sshbuf_new failed", __func__);
1692         if (rexeced_flag)
1693                 recv_rexec_state(REEXEC_CONFIG_PASS_FD, cfg);
1694         else if (strcasecmp(config_file_name, "none") != 0)
1695                 load_server_config(config_file_name, cfg);
1696
1697         parse_server_config(&options, rexeced_flag ? "rexec" : config_file_name,
1698             cfg, NULL);
1699
1700         seed_rng();
1701
1702         /* Fill in default values for those options not explicitly set. */
1703         fill_default_server_options(&options);
1704
1705         /* challenge-response is implemented via keyboard interactive */
1706         if (options.challenge_response_authentication)
1707                 options.kbd_interactive_authentication = 1;
1708
1709         /* Check that options are sensible */
1710         if (options.authorized_keys_command_user == NULL &&
1711             (options.authorized_keys_command != NULL &&
1712             strcasecmp(options.authorized_keys_command, "none") != 0))
1713                 fatal("AuthorizedKeysCommand set without "
1714                     "AuthorizedKeysCommandUser");
1715         if (options.authorized_principals_command_user == NULL &&
1716             (options.authorized_principals_command != NULL &&
1717             strcasecmp(options.authorized_principals_command, "none") != 0))
1718                 fatal("AuthorizedPrincipalsCommand set without "
1719                     "AuthorizedPrincipalsCommandUser");
1720
1721         /*
1722          * Check whether there is any path through configured auth methods.
1723          * Unfortunately it is not possible to verify this generally before
1724          * daemonisation in the presence of Match block, but this catches
1725          * and warns for trivial misconfigurations that could break login.
1726          */
1727         if (options.num_auth_methods != 0) {
1728                 for (i = 0; i < options.num_auth_methods; i++) {
1729                         if (auth2_methods_valid(options.auth_methods[i],
1730                             1) == 0)
1731                                 break;
1732                 }
1733                 if (i >= options.num_auth_methods)
1734                         fatal("AuthenticationMethods cannot be satisfied by "
1735                             "enabled authentication methods");
1736         }
1737
1738         /* Check that there are no remaining arguments. */
1739         if (optind < ac) {
1740                 fprintf(stderr, "Extra argument %s.\n", av[optind]);
1741                 exit(1);
1742         }
1743
1744         debug("sshd version %s, %s", SSH_VERSION,
1745 #ifdef WITH_OPENSSL
1746             OpenSSL_version(OPENSSL_VERSION)
1747 #else
1748             "without OpenSSL"
1749 #endif
1750         );
1751
1752         /* Store privilege separation user for later use if required. */
1753         privsep_chroot = use_privsep && (getuid() == 0 || geteuid() == 0);
1754         if ((privsep_pw = getpwnam(SSH_PRIVSEP_USER)) == NULL) {
1755                 if (privsep_chroot || options.kerberos_authentication)
1756                         fatal("Privilege separation user %s does not exist",
1757                             SSH_PRIVSEP_USER);
1758         } else {
1759                 privsep_pw = pwcopy(privsep_pw);
1760                 freezero(privsep_pw->pw_passwd, strlen(privsep_pw->pw_passwd));
1761                 privsep_pw->pw_passwd = xstrdup("*");
1762         }
1763         endpwent();
1764
1765         /* load host keys */
1766         sensitive_data.host_keys = xcalloc(options.num_host_key_files,
1767             sizeof(struct sshkey *));
1768         sensitive_data.host_pubkeys = xcalloc(options.num_host_key_files,
1769             sizeof(struct sshkey *));
1770
1771         if (options.host_key_agent) {
1772                 if (strcmp(options.host_key_agent, SSH_AUTHSOCKET_ENV_NAME))
1773                         setenv(SSH_AUTHSOCKET_ENV_NAME,
1774                             options.host_key_agent, 1);
1775                 if ((r = ssh_get_authentication_socket(NULL)) == 0)
1776                         have_agent = 1;
1777                 else
1778                         error("Could not connect to agent \"%s\": %s",
1779                             options.host_key_agent, ssh_err(r));
1780         }
1781
1782         for (i = 0; i < options.num_host_key_files; i++) {
1783                 if (options.host_key_files[i] == NULL)
1784                         continue;
1785                 if ((r = sshkey_load_private(options.host_key_files[i], "",
1786                     &key, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1787                         error("Error loading host key \"%s\": %s",
1788                             options.host_key_files[i], ssh_err(r));
1789                 if ((r = sshkey_load_public(options.host_key_files[i],
1790                     &pubkey, NULL)) != 0 && r != SSH_ERR_SYSTEM_ERROR)
1791                         error("Error loading host key \"%s\": %s",
1792                             options.host_key_files[i], ssh_err(r));
1793                 if (pubkey == NULL && key != NULL)
1794                         if ((r = sshkey_from_private(key, &pubkey)) != 0)
1795                                 fatal("Could not demote key: \"%s\": %s",
1796                                     options.host_key_files[i], ssh_err(r));
1797                 sensitive_data.host_keys[i] = key;
1798                 sensitive_data.host_pubkeys[i] = pubkey;
1799
1800                 if (key == NULL && pubkey != NULL && have_agent) {
1801                         debug("will rely on agent for hostkey %s",
1802                             options.host_key_files[i]);
1803                         keytype = pubkey->type;
1804                 } else if (key != NULL) {
1805                         keytype = key->type;
1806                         accumulate_host_timing_secret(cfg, key);
1807                 } else {
1808                         error("Could not load host key: %s",
1809                             options.host_key_files[i]);
1810                         sensitive_data.host_keys[i] = NULL;
1811                         sensitive_data.host_pubkeys[i] = NULL;
1812                         continue;
1813                 }
1814
1815                 switch (keytype) {
1816                 case KEY_RSA:
1817                 case KEY_DSA:
1818                 case KEY_ECDSA:
1819                 case KEY_ED25519:
1820                 case KEY_XMSS:
1821                         if (have_agent || key != NULL)
1822                                 sensitive_data.have_ssh2_key = 1;
1823                         break;
1824                 }
1825                 if ((fp = sshkey_fingerprint(pubkey, options.fingerprint_hash,
1826                     SSH_FP_DEFAULT)) == NULL)
1827                         fatal("sshkey_fingerprint failed");
1828                 debug("%s host key #%d: %s %s",
1829                     key ? "private" : "agent", i, sshkey_ssh_name(pubkey), fp);
1830                 free(fp);
1831         }
1832         accumulate_host_timing_secret(cfg, NULL);
1833         if (!sensitive_data.have_ssh2_key) {
1834                 logit("sshd: no hostkeys available -- exiting.");
1835                 exit(1);
1836         }
1837
1838         /*
1839          * Load certificates. They are stored in an array at identical
1840          * indices to the public keys that they relate to.
1841          */
1842         sensitive_data.host_certificates = xcalloc(options.num_host_key_files,
1843             sizeof(struct sshkey *));
1844         for (i = 0; i < options.num_host_key_files; i++)
1845                 sensitive_data.host_certificates[i] = NULL;
1846
1847         for (i = 0; i < options.num_host_cert_files; i++) {
1848                 if (options.host_cert_files[i] == NULL)
1849                         continue;
1850                 if ((r = sshkey_load_public(options.host_cert_files[i],
1851                     &key, NULL)) != 0) {
1852                         error("Could not load host certificate \"%s\": %s",
1853                             options.host_cert_files[i], ssh_err(r));
1854                         continue;
1855                 }
1856                 if (!sshkey_is_cert(key)) {
1857                         error("Certificate file is not a certificate: %s",
1858                             options.host_cert_files[i]);
1859                         sshkey_free(key);
1860                         continue;
1861                 }
1862                 /* Find matching private key */
1863                 for (j = 0; j < options.num_host_key_files; j++) {
1864                         if (sshkey_equal_public(key,
1865                             sensitive_data.host_keys[j])) {
1866                                 sensitive_data.host_certificates[j] = key;
1867                                 break;
1868                         }
1869                 }
1870                 if (j >= options.num_host_key_files) {
1871                         error("No matching private key for certificate: %s",
1872                             options.host_cert_files[i]);
1873                         sshkey_free(key);
1874                         continue;
1875                 }
1876                 sensitive_data.host_certificates[j] = key;
1877                 debug("host certificate: #%u type %d %s", j, key->type,
1878                     sshkey_type(key));
1879         }
1880
1881         if (privsep_chroot) {
1882                 struct stat st;
1883
1884                 if ((stat(_PATH_PRIVSEP_CHROOT_DIR, &st) == -1) ||
1885                     (S_ISDIR(st.st_mode) == 0))
1886                         fatal("Missing privilege separation directory: %s",
1887                             _PATH_PRIVSEP_CHROOT_DIR);
1888
1889 #ifdef HAVE_CYGWIN
1890                 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR) &&
1891                     (st.st_uid != getuid () ||
1892                     (st.st_mode & (S_IWGRP|S_IWOTH)) != 0))
1893 #else
1894                 if (st.st_uid != 0 || (st.st_mode & (S_IWGRP|S_IWOTH)) != 0)
1895 #endif
1896                         fatal("%s must be owned by root and not group or "
1897                             "world-writable.", _PATH_PRIVSEP_CHROOT_DIR);
1898         }
1899
1900         if (test_flag > 1) {
1901                 /*
1902                  * If no connection info was provided by -C then use
1903                  * use a blank one that will cause no predicate to match.
1904                  */
1905                 if (connection_info == NULL)
1906                         connection_info = get_connection_info(0, 0);
1907                 parse_server_match_config(&options, connection_info);
1908                 dump_config(&options);
1909         }
1910
1911         /* Configuration looks good, so exit if in test mode. */
1912         if (test_flag)
1913                 exit(0);
1914
1915         /*
1916          * Clear out any supplemental groups we may have inherited.  This
1917          * prevents inadvertent creation of files with bad modes (in the
1918          * portable version at least, it's certainly possible for PAM
1919          * to create a file, and we can't control the code in every
1920          * module which might be used).
1921          */
1922         if (setgroups(0, NULL) < 0)
1923                 debug("setgroups() failed: %.200s", strerror(errno));
1924
1925         if (rexec_flag) {
1926                 if (rexec_argc < 0)
1927                         fatal("rexec_argc %d < 0", rexec_argc);
1928                 rexec_argv = xcalloc(rexec_argc + 2, sizeof(char *));
1929                 for (i = 0; i < (u_int)rexec_argc; i++) {
1930                         debug("rexec_argv[%d]='%s'", i, saved_argv[i]);
1931                         rexec_argv[i] = saved_argv[i];
1932                 }
1933                 rexec_argv[rexec_argc] = "-R";
1934                 rexec_argv[rexec_argc + 1] = NULL;
1935         }
1936
1937         /* Ensure that umask disallows at least group and world write */
1938         new_umask = umask(0077) | 0022;
1939         (void) umask(new_umask);
1940
1941         /* Initialize the log (it is reinitialized below in case we forked). */
1942         if (debug_flag && (!inetd_flag || rexeced_flag))
1943                 log_stderr = 1;
1944         log_init(__progname, options.log_level, options.log_facility, log_stderr);
1945
1946         /*
1947          * If not in debugging mode, not started from inetd and not already
1948          * daemonized (eg re-exec via SIGHUP), disconnect from the controlling
1949          * terminal, and fork.  The original process exits.
1950          */
1951         already_daemon = daemonized();
1952         if (!(debug_flag || inetd_flag || no_daemon_flag || already_daemon)) {
1953
1954                 if (daemon(0, 0) < 0)
1955                         fatal("daemon() failed: %.200s", strerror(errno));
1956
1957                 disconnect_controlling_tty();
1958         }
1959         /* Reinitialize the log (because of the fork above). */
1960         log_init(__progname, options.log_level, options.log_facility, log_stderr);
1961
1962         /* Avoid killing the process in high-pressure swapping environments. */
1963         if (!inetd_flag && madvise(NULL, 0, MADV_PROTECT) != 0)
1964                 debug("madvise(): %.200s", strerror(errno));
1965
1966         /* Chdir to the root directory so that the current disk can be
1967            unmounted if desired. */
1968         if (chdir("/") == -1)
1969                 error("chdir(\"/\"): %s", strerror(errno));
1970
1971         /* ignore SIGPIPE */
1972         signal(SIGPIPE, SIG_IGN);
1973
1974         /* Get a connection, either from inetd or a listening TCP socket */
1975         if (inetd_flag) {
1976                 server_accept_inetd(&sock_in, &sock_out);
1977         } else {
1978                 platform_pre_listen();
1979                 server_listen();
1980
1981                 signal(SIGHUP, sighup_handler);
1982                 signal(SIGCHLD, main_sigchld_handler);
1983                 signal(SIGTERM, sigterm_handler);
1984                 signal(SIGQUIT, sigterm_handler);
1985
1986                 /*
1987                  * Write out the pid file after the sigterm handler
1988                  * is setup and the listen sockets are bound
1989                  */
1990                 if (options.pid_file != NULL && !debug_flag) {
1991                         FILE *f = fopen(options.pid_file, "w");
1992
1993                         if (f == NULL) {
1994                                 error("Couldn't create pid file \"%s\": %s",
1995                                     options.pid_file, strerror(errno));
1996                         } else {
1997                                 fprintf(f, "%ld\n", (long) getpid());
1998                                 fclose(f);
1999                         }
2000                 }
2001
2002                 /* Accept a connection and return in a forked child */
2003                 server_accept_loop(&sock_in, &sock_out,
2004                     &newsock, config_s);
2005         }
2006
2007         /* This is the child processing a new connection. */
2008         setproctitle("%s", "[accepted]");
2009
2010         /*
2011          * Create a new session and process group since the 4.4BSD
2012          * setlogin() affects the entire process group.  We don't
2013          * want the child to be able to affect the parent.
2014          */
2015 #if !defined(SSHD_ACQUIRES_CTTY)
2016         /*
2017          * If setsid is called, on some platforms sshd will later acquire a
2018          * controlling terminal which will result in "could not set
2019          * controlling tty" errors.
2020          */
2021         if (!debug_flag && !inetd_flag && setsid() < 0)
2022                 error("setsid: %.100s", strerror(errno));
2023 #endif
2024
2025         if (rexec_flag) {
2026                 int fd;
2027
2028                 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
2029                     sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2030                 dup2(newsock, STDIN_FILENO);
2031                 dup2(STDIN_FILENO, STDOUT_FILENO);
2032                 if (startup_pipe == -1)
2033                         close(REEXEC_STARTUP_PIPE_FD);
2034                 else if (startup_pipe != REEXEC_STARTUP_PIPE_FD) {
2035                         dup2(startup_pipe, REEXEC_STARTUP_PIPE_FD);
2036                         close(startup_pipe);
2037                         startup_pipe = REEXEC_STARTUP_PIPE_FD;
2038                 }
2039
2040                 dup2(config_s[1], REEXEC_CONFIG_PASS_FD);
2041                 close(config_s[1]);
2042
2043                 execv(rexec_argv[0], rexec_argv);
2044
2045                 /* Reexec has failed, fall back and continue */
2046                 error("rexec of %s failed: %s", rexec_argv[0], strerror(errno));
2047                 recv_rexec_state(REEXEC_CONFIG_PASS_FD, NULL);
2048                 log_init(__progname, options.log_level,
2049                     options.log_facility, log_stderr);
2050
2051                 /* Clean up fds */
2052                 close(REEXEC_CONFIG_PASS_FD);
2053                 newsock = sock_out = sock_in = dup(STDIN_FILENO);
2054                 if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
2055                         dup2(fd, STDIN_FILENO);
2056                         dup2(fd, STDOUT_FILENO);
2057                         if (fd > STDERR_FILENO)
2058                                 close(fd);
2059                 }
2060                 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2061                     sock_in, sock_out, newsock, startup_pipe, config_s[0]);
2062         }
2063
2064         /* Executed child processes don't need these. */
2065         fcntl(sock_out, F_SETFD, FD_CLOEXEC);
2066         fcntl(sock_in, F_SETFD, FD_CLOEXEC);
2067
2068         /*
2069          * Disable the key regeneration alarm.  We will not regenerate the
2070          * key since we are no longer in a position to give it to anyone. We
2071          * will not restart on SIGHUP since it no longer makes sense.
2072          */
2073         alarm(0);
2074         signal(SIGALRM, SIG_DFL);
2075         signal(SIGHUP, SIG_DFL);
2076         signal(SIGTERM, SIG_DFL);
2077         signal(SIGQUIT, SIG_DFL);
2078         signal(SIGCHLD, SIG_DFL);
2079         signal(SIGINT, SIG_DFL);
2080
2081 #ifdef __FreeBSD__
2082         /*
2083          * Initialize the resolver.  This may not happen automatically
2084          * before privsep chroot().
2085          */
2086         if ((_res.options & RES_INIT) == 0) {
2087                 debug("res_init()");
2088                 res_init();
2089         }
2090 #ifdef GSSAPI
2091         /*
2092          * Force GSS-API to parse its configuration and load any
2093          * mechanism plugins.
2094          */
2095         {
2096                 gss_OID_set mechs;
2097                 OM_uint32 minor_status;
2098                 gss_indicate_mechs(&minor_status, &mechs);
2099                 gss_release_oid_set(&minor_status, &mechs);
2100         }
2101 #endif
2102 #endif
2103
2104         /*
2105          * Register our connection.  This turns encryption off because we do
2106          * not have a key.
2107          */
2108         packet_set_connection(sock_in, sock_out);
2109         packet_set_server();
2110         ssh = active_state; /* XXX */
2111
2112         check_ip_options(ssh);
2113
2114         /* Prepare the channels layer */
2115         channel_init_channels(ssh);
2116         channel_set_af(ssh, options.address_family);
2117         process_permitopen(ssh, &options);
2118
2119         /* Set SO_KEEPALIVE if requested. */
2120         if (options.tcp_keep_alive && packet_connection_is_on_socket() &&
2121             setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on)) < 0)
2122                 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
2123
2124         if ((remote_port = ssh_remote_port(ssh)) < 0) {
2125                 debug("ssh_remote_port failed");
2126                 cleanup_exit(255);
2127         }
2128
2129         if (options.routing_domain != NULL)
2130                 set_process_rdomain(ssh, options.routing_domain);
2131
2132         /*
2133          * The rest of the code depends on the fact that
2134          * ssh_remote_ipaddr() caches the remote ip, even if
2135          * the socket goes away.
2136          */
2137         remote_ip = ssh_remote_ipaddr(ssh);
2138
2139 #ifdef HAVE_LOGIN_CAP
2140         /* Also caches remote hostname for sandboxed child. */
2141         auth_get_canonical_hostname(ssh, options.use_dns);
2142 #endif
2143
2144 #ifdef SSH_AUDIT_EVENTS
2145         audit_connection_from(remote_ip, remote_port);
2146 #endif
2147 #ifdef LIBWRAP
2148         allow_severity = options.log_facility|LOG_INFO;
2149         deny_severity = options.log_facility|LOG_WARNING;
2150         /* Check whether logins are denied from this host. */
2151         if (packet_connection_is_on_socket()) {
2152                 struct request_info req;
2153
2154                 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, 0);
2155                 fromhost(&req);
2156
2157                 if (!hosts_access(&req)) {
2158                         debug("Connection refused by tcp wrapper");
2159                         refuse(&req);
2160                         /* NOTREACHED */
2161                         fatal("libwrap refuse returns");
2162                 }
2163         }
2164 #endif /* LIBWRAP */
2165
2166         rdomain = ssh_packet_rdomain_in(ssh);
2167
2168         /* Log the connection. */
2169         laddr = get_local_ipaddr(sock_in);
2170         verbose("Connection from %s port %d on %s port %d%s%s%s",
2171             remote_ip, remote_port, laddr,  ssh_local_port(ssh),
2172             rdomain == NULL ? "" : " rdomain \"",
2173             rdomain == NULL ? "" : rdomain,
2174             rdomain == NULL ? "" : "\"");
2175         free(laddr);
2176
2177         /*
2178          * We don't want to listen forever unless the other side
2179          * successfully authenticates itself.  So we set up an alarm which is
2180          * cleared after successful authentication.  A limit of zero
2181          * indicates no limit. Note that we don't set the alarm in debugging
2182          * mode; it is just annoying to have the server exit just when you
2183          * are about to discover the bug.
2184          */
2185         signal(SIGALRM, grace_alarm_handler);
2186         if (!debug_flag)
2187                 alarm(options.login_grace_time);
2188
2189         sshd_exchange_identification(ssh, sock_in, sock_out);
2190         packet_set_nonblocking();
2191
2192         /* allocate authentication context */
2193         authctxt = xcalloc(1, sizeof(*authctxt));
2194
2195         authctxt->loginmsg = loginmsg;
2196
2197         /* XXX global for cleanup, access from other modules */
2198         the_authctxt = authctxt;
2199
2200         /* Set default key authentication options */
2201         if ((auth_opts = sshauthopt_new_with_keys_defaults()) == NULL)
2202                 fatal("allocation failed");
2203
2204         /* prepare buffer to collect messages to display to user after login */
2205         if ((loginmsg = sshbuf_new()) == NULL)
2206                 fatal("%s: sshbuf_new failed", __func__);
2207         auth_debug_reset();
2208
2209         BLACKLIST_INIT();
2210
2211         if (use_privsep) {
2212                 if (privsep_preauth(authctxt) == 1)
2213                         goto authenticated;
2214         } else if (have_agent) {
2215                 if ((r = ssh_get_authentication_socket(&auth_sock)) != 0) {
2216                         error("Unable to get agent socket: %s", ssh_err(r));
2217                         have_agent = 0;
2218                 }
2219         }
2220
2221         /* perform the key exchange */
2222         /* authenticate user and start session */
2223         do_ssh2_kex();
2224         do_authentication2(authctxt);
2225
2226         /*
2227          * If we use privilege separation, the unprivileged child transfers
2228          * the current keystate and exits
2229          */
2230         if (use_privsep) {
2231                 mm_send_keystate(pmonitor);
2232                 packet_clear_keys();
2233                 exit(0);
2234         }
2235
2236  authenticated:
2237         /*
2238          * Cancel the alarm we set to limit the time taken for
2239          * authentication.
2240          */
2241         alarm(0);
2242         signal(SIGALRM, SIG_DFL);
2243         authctxt->authenticated = 1;
2244         if (startup_pipe != -1) {
2245                 close(startup_pipe);
2246                 startup_pipe = -1;
2247         }
2248
2249 #ifdef SSH_AUDIT_EVENTS
2250         audit_event(SSH_AUTH_SUCCESS);
2251 #endif
2252
2253 #ifdef GSSAPI
2254         if (options.gss_authentication) {
2255                 temporarily_use_uid(authctxt->pw);
2256                 ssh_gssapi_storecreds();
2257                 restore_uid();
2258         }
2259 #endif
2260 #ifdef USE_PAM
2261         if (options.use_pam) {
2262                 do_pam_setcred(1);
2263                 do_pam_session(ssh);
2264         }
2265 #endif
2266
2267         /*
2268          * In privilege separation, we fork another child and prepare
2269          * file descriptor passing.
2270          */
2271         if (use_privsep) {
2272                 privsep_postauth(authctxt);
2273                 /* the monitor process [priv] will not return */
2274         }
2275
2276         packet_set_timeout(options.client_alive_interval,
2277             options.client_alive_count_max);
2278
2279         /* Try to send all our hostkeys to the client */
2280         notify_hostkeys(ssh);
2281
2282         /* Start session. */
2283         do_authenticated(ssh, authctxt);
2284
2285         /* The connection has been terminated. */
2286         packet_get_bytes(&ibytes, &obytes);
2287         verbose("Transferred: sent %llu, received %llu bytes",
2288             (unsigned long long)obytes, (unsigned long long)ibytes);
2289
2290         verbose("Closing connection to %.500s port %d", remote_ip, remote_port);
2291
2292 #ifdef USE_PAM
2293         if (options.use_pam)
2294                 finish_pam();
2295 #endif /* USE_PAM */
2296
2297 #ifdef SSH_AUDIT_EVENTS
2298         PRIVSEP(audit_event(SSH_CONNECTION_CLOSE));
2299 #endif
2300
2301         packet_close();
2302
2303         if (use_privsep)
2304                 mm_terminate();
2305
2306         exit(0);
2307 }
2308
2309 int
2310 sshd_hostkey_sign(struct sshkey *privkey, struct sshkey *pubkey,
2311     u_char **signature, size_t *slenp, const u_char *data, size_t dlen,
2312     const char *alg, u_int flag)
2313 {
2314         int r;
2315
2316         if (privkey) {
2317                 if (PRIVSEP(sshkey_sign(privkey, signature, slenp, data, dlen,
2318                     alg, datafellows)) < 0)
2319                         fatal("%s: key_sign failed", __func__);
2320         } else if (use_privsep) {
2321                 if (mm_sshkey_sign(pubkey, signature, slenp, data, dlen,
2322                     alg, datafellows) < 0)
2323                         fatal("%s: pubkey_sign failed", __func__);
2324         } else {
2325                 if ((r = ssh_agent_sign(auth_sock, pubkey, signature, slenp,
2326                     data, dlen, alg, datafellows)) != 0)
2327                         fatal("%s: ssh_agent_sign failed: %s",
2328                             __func__, ssh_err(r));
2329         }
2330         return 0;
2331 }
2332
2333 /* SSH2 key exchange */
2334 static void
2335 do_ssh2_kex(void)
2336 {
2337         char *myproposal[PROPOSAL_MAX] = { KEX_SERVER };
2338         struct kex *kex;
2339         int r;
2340
2341         myproposal[PROPOSAL_KEX_ALGS] = compat_kex_proposal(
2342             options.kex_algorithms);
2343         myproposal[PROPOSAL_ENC_ALGS_CTOS] = compat_cipher_proposal(
2344             options.ciphers);
2345         myproposal[PROPOSAL_ENC_ALGS_STOC] = compat_cipher_proposal(
2346             options.ciphers);
2347         myproposal[PROPOSAL_MAC_ALGS_CTOS] =
2348             myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
2349
2350         if (options.compression == COMP_NONE) {
2351                 myproposal[PROPOSAL_COMP_ALGS_CTOS] =
2352                     myproposal[PROPOSAL_COMP_ALGS_STOC] = "none";
2353         }
2354
2355         if (options.rekey_limit || options.rekey_interval)
2356                 packet_set_rekey_limits(options.rekey_limit,
2357                     options.rekey_interval);
2358
2359         myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = compat_pkalg_proposal(
2360             list_hostkey_types());
2361
2362         /* start key exchange */
2363         if ((r = kex_setup(active_state, myproposal)) != 0)
2364                 fatal("kex_setup: %s", ssh_err(r));
2365         kex = active_state->kex;
2366 #ifdef WITH_OPENSSL
2367         kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
2368         kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
2369         kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
2370         kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
2371         kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
2372         kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
2373         kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
2374 # ifdef OPENSSL_HAS_ECC
2375         kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
2376 # endif
2377 #endif
2378         kex->kex[KEX_C25519_SHA256] = kexc25519_server;
2379         kex->server = 1;
2380         kex->client_version_string=client_version_string;
2381         kex->server_version_string=server_version_string;
2382         kex->load_host_public_key=&get_hostkey_public_by_type;
2383         kex->load_host_private_key=&get_hostkey_private_by_type;
2384         kex->host_key_index=&get_hostkey_index;
2385         kex->sign = sshd_hostkey_sign;
2386
2387         ssh_dispatch_run_fatal(active_state, DISPATCH_BLOCK, &kex->done);
2388
2389         session_id2 = kex->session_id;
2390         session_id2_len = kex->session_id_len;
2391
2392 #ifdef DEBUG_KEXDH
2393         /* send 1st encrypted/maced/compressed message */
2394         packet_start(SSH2_MSG_IGNORE);
2395         packet_put_cstring("markus");
2396         packet_send();
2397         packet_write_wait();
2398 #endif
2399         debug("KEX done");
2400 }
2401
2402 /* server specific fatal cleanup */
2403 void
2404 cleanup_exit(int i)
2405 {
2406         struct ssh *ssh = active_state; /* XXX */
2407
2408         if (the_authctxt) {
2409                 do_cleanup(ssh, the_authctxt);
2410                 if (use_privsep && privsep_is_preauth &&
2411                     pmonitor != NULL && pmonitor->m_pid > 1) {
2412                         debug("Killing privsep child %d", pmonitor->m_pid);
2413                         if (kill(pmonitor->m_pid, SIGKILL) != 0 &&
2414                             errno != ESRCH)
2415                                 error("%s: kill(%d): %s", __func__,
2416                                     pmonitor->m_pid, strerror(errno));
2417                 }
2418         }
2419 #ifdef SSH_AUDIT_EVENTS
2420         /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2421         if (!use_privsep || mm_is_monitor())
2422                 audit_event(SSH_CONNECTION_ABANDON);
2423 #endif
2424         _exit(i);
2425 }