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