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