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