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