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