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