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