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