1 /* $OpenBSD: sshd.c,v 1.428 2014/07/15 15:54:14 millert Exp $ */
3 * Author: Tatu Ylonen <ylo@cs.hut.fi>
4 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland
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.
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".
18 * SSH2 implementation:
19 * Privilege Separation:
21 * Copyright (c) 2000, 2001, 2002 Markus Friedl. All rights reserved.
22 * Copyright (c) 2002 Niels Provos. All rights reserved.
24 * Redistribution and use in source and binary forms, with or without
25 * modification, are permitted provided that the following conditions
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.
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.
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>
53 #ifdef HAVE_SYS_TIME_H
54 # include <sys/time.h>
56 #include "openbsd-compat/sys-tree.h"
57 #include "openbsd-compat/sys-queue.h"
76 #include <openssl/dh.h>
77 #include <openssl/bn.h>
78 #include <openssl/rand.h>
79 #include "openbsd-compat/openssl-compat.h"
82 #ifdef HAVE_SECUREWARE
83 #include <sys/security.h>
105 #include "myproposal.h"
106 #include "authfile.h"
107 #include "pathnames.h"
108 #include "atomicio.h"
109 #include "canohost.h"
110 #include "hostfile.h"
114 #include "dispatch.h"
115 #include "channels.h"
117 #include "monitor_mm.h"
122 #include "monitor_wrap.h"
124 #include "ssh-sandbox.h"
132 #define REEXEC_DEVCRYPTO_RESERVED_FD (STDERR_FILENO + 1)
133 #define REEXEC_STARTUP_PIPE_FD (STDERR_FILENO + 2)
134 #define REEXEC_CONFIG_PASS_FD (STDERR_FILENO + 3)
135 #define REEXEC_MIN_FREE_FD (STDERR_FILENO + 4)
140 extern char *__progname
;
142 /* Server configuration options. */
143 ServerOptions options
;
145 /* Name of the server configuration file. */
146 char *config_file_name
= _PATH_SERVER_CONFIG_FILE
;
149 * Debug mode flag. This can be set on the command line. If debug
150 * mode is enabled, extra debugging output will be sent to the system
151 * log, the daemon will not go to background, and will exit after processing
152 * the first connection.
156 /* Flag indicating that the daemon should only test the configuration and keys. */
159 /* Flag indicating that the daemon is being started from inetd. */
162 /* Flag indicating that sshd should not detach and become a daemon. */
163 int no_daemon_flag
= 0;
165 /* debug goes to stderr unless inetd_flag is set */
168 /* Saved arguments to main(). */
173 int rexeced_flag
= 0;
179 * The sockets that the server is listening; this is used in the SIGHUP
182 #define MAX_LISTEN_SOCKS 16
183 int listen_socks
[MAX_LISTEN_SOCKS
];
184 int num_listen_socks
= 0;
187 * the client's version string, passed by sshd2 in compat mode. if != NULL,
188 * sshd will skip the version-number exchange
190 char *client_version_string
= NULL
;
191 char *server_version_string
= NULL
;
193 /* for rekeying XXX fixme */
196 /* Daemon's agent connection */
197 AuthenticationConnection
*auth_conn
= NULL
;
201 * Any really sensitive data in the application is contained in this
202 * structure. The idea is that this structure could be locked into memory so
203 * that the pages do not get written into swap. However, there are some
204 * problems. The private key contains BIGNUMs, and we do not (in principle)
205 * have access to the internals of them, and locking just the structure is
206 * not very useful. Currently, memory locking is not implemented.
209 Key
*server_key
; /* ephemeral server key */
210 Key
*ssh1_host_key
; /* ssh1 host key */
211 Key
**host_keys
; /* all private host keys */
212 Key
**host_pubkeys
; /* all public host keys */
213 Key
**host_certificates
; /* all public host certificates */
216 u_char ssh1_cookie
[SSH_SESSION_KEY_LENGTH
];
220 * Flag indicating whether the RSA server key needs to be regenerated.
221 * Is set in the SIGALRM handler and cleared when the key is regenerated.
223 static volatile sig_atomic_t key_do_regen
= 0;
225 /* This is set to true when a signal is received. */
226 static volatile sig_atomic_t received_sighup
= 0;
227 static volatile sig_atomic_t received_sigterm
= 0;
229 /* session identifier, used by RSA-auth */
230 u_char session_id
[16];
233 u_char
*session_id2
= NULL
;
234 u_int session_id2_len
= 0;
236 /* record remote hostname or ip */
237 u_int utmp_len
= MAXHOSTNAMELEN
;
239 /* options.max_startup sized array of fd ints */
240 int *startup_pipes
= NULL
;
241 int startup_pipe
; /* in child */
243 /* variables used for privilege separation */
244 int use_privsep
= -1;
245 struct monitor
*pmonitor
= NULL
;
246 int privsep_is_preauth
= 1;
248 /* global authentication context */
249 Authctxt
*the_authctxt
= NULL
;
251 /* sshd_config buffer */
254 /* message to be displayed after login */
257 /* Unprivileged user */
258 struct passwd
*privsep_pw
= NULL
;
260 /* Prototypes for various functions defined later in this file. */
261 void destroy_sensitive_data(void);
262 void demote_sensitive_data(void);
265 static void do_ssh1_kex(void);
267 static void do_ssh2_kex(void);
270 * Close all listening sockets
273 close_listen_socks(void)
277 for (i
= 0; i
< num_listen_socks
; i
++)
278 close(listen_socks
[i
]);
279 num_listen_socks
= -1;
283 close_startup_pipes(void)
288 for (i
= 0; i
< options
.max_startups
; i
++)
289 if (startup_pipes
[i
] != -1)
290 close(startup_pipes
[i
]);
294 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP;
295 * the effect is to reread the configuration file (and to regenerate
301 sighup_handler(int sig
)
303 int save_errno
= errno
;
306 signal(SIGHUP
, sighup_handler
);
311 * Called from the main program after receiving SIGHUP.
312 * Restarts the server.
317 logit("Received SIGHUP; restarting.");
318 platform_pre_restart();
319 close_listen_socks();
320 close_startup_pipes();
321 alarm(0); /* alarm timer persists across exec */
322 signal(SIGHUP
, SIG_IGN
); /* will be restored after exec */
323 execv(saved_argv
[0], saved_argv
);
324 logit("RESTART FAILED: av[0]='%.100s', error: %.100s.", saved_argv
[0],
330 * Generic signal handler for terminating signals in the master daemon.
334 sigterm_handler(int sig
)
336 received_sigterm
= sig
;
340 * SIGCHLD handler. This is called whenever a child dies. This will then
341 * reap any zombies left by exited children.
345 main_sigchld_handler(int sig
)
347 int save_errno
= errno
;
351 while ((pid
= waitpid(-1, &status
, WNOHANG
)) > 0 ||
352 (pid
< 0 && errno
== EINTR
))
355 signal(SIGCHLD
, main_sigchld_handler
);
360 * Signal handler for the alarm after the login grace period has expired.
364 grace_alarm_handler(int sig
)
366 if (use_privsep
&& pmonitor
!= NULL
&& pmonitor
->m_pid
> 0)
367 kill(pmonitor
->m_pid
, SIGALRM
);
370 * Try to kill any processes that we have spawned, E.g. authorized
371 * keys command helpers.
373 if (getpgid(0) == getpid()) {
374 signal(SIGTERM
, SIG_IGN
);
378 /* Log error and exit. */
379 sigdie("Timeout before authentication for %s", get_remote_ipaddr());
383 * Signal handler for the key regeneration alarm. Note that this
384 * alarm only occurs in the daemon waiting for connections, and it does not
385 * do anything with the private key or random state before forking.
386 * Thus there should be no concurrency control/asynchronous execution
390 generate_ephemeral_server_key(void)
392 verbose("Generating %s%d bit RSA key.",
393 sensitive_data
.server_key
? "new " : "", options
.server_key_bits
);
394 if (sensitive_data
.server_key
!= NULL
)
395 key_free(sensitive_data
.server_key
);
396 sensitive_data
.server_key
= key_generate(KEY_RSA1
,
397 options
.server_key_bits
);
398 verbose("RSA key generation complete.");
400 arc4random_buf(sensitive_data
.ssh1_cookie
, SSH_SESSION_KEY_LENGTH
);
405 key_regeneration_alarm(int sig
)
407 int save_errno
= errno
;
409 signal(SIGALRM
, SIG_DFL
);
415 sshd_exchange_identification(int sock_in
, int sock_out
)
419 int remote_major
, remote_minor
;
421 char *s
, *newline
= "\n";
422 char buf
[256]; /* Must not be larger than remote_version. */
423 char remote_version
[256]; /* Must be at least as big as buf. */
425 if ((options
.protocol
& SSH_PROTO_1
) &&
426 (options
.protocol
& SSH_PROTO_2
)) {
427 major
= PROTOCOL_MAJOR_1
;
429 } else if (options
.protocol
& SSH_PROTO_2
) {
430 major
= PROTOCOL_MAJOR_2
;
431 minor
= PROTOCOL_MINOR_2
;
434 major
= PROTOCOL_MAJOR_1
;
435 minor
= PROTOCOL_MINOR_1
;
438 xasprintf(&server_version_string
, "SSH-%d.%d-%.100s%s%s%s%s",
439 major
, minor
, SSH_RELEASE
,
440 options
.hpn_disabled
? "" : SSH_VERSION_HPN
,
441 *options
.version_addendum
== '\0' ? "" : " ",
442 options
.version_addendum
, newline
);
444 /* Send our protocol version identification. */
445 if (roaming_atomicio(vwrite
, sock_out
, server_version_string
,
446 strlen(server_version_string
))
447 != strlen(server_version_string
)) {
448 logit("Could not write ident string to %s", get_remote_ipaddr());
452 /* Read other sides version identification. */
453 memset(buf
, 0, sizeof(buf
));
454 for (i
= 0; i
< sizeof(buf
) - 1; i
++) {
455 if (roaming_atomicio(read
, sock_in
, &buf
[i
], 1) != 1) {
456 logit("Did not receive identification string from %s",
457 get_remote_ipaddr());
460 if (buf
[i
] == '\r') {
462 /* Kludge for F-Secure Macintosh < 1.0.2 */
464 strncmp(buf
, "SSH-1.5-W1.0", 12) == 0)
468 if (buf
[i
] == '\n') {
473 buf
[sizeof(buf
) - 1] = 0;
474 client_version_string
= xstrdup(buf
);
477 * Check that the versions match. In future this might accept
478 * several versions and set appropriate flags to handle them.
480 if (sscanf(client_version_string
, "SSH-%d.%d-%[^\n]\n",
481 &remote_major
, &remote_minor
, remote_version
) != 3) {
482 s
= "Protocol mismatch.\n";
483 (void) atomicio(vwrite
, sock_out
, s
, strlen(s
));
484 logit("Bad protocol version identification '%.100s' "
485 "from %s port %d", client_version_string
,
486 get_remote_ipaddr(), get_remote_port());
491 debug("Client protocol version %d.%d; client software version %.100s",
492 remote_major
, remote_minor
, remote_version
);
493 logit("SSH: Server;Ltype: Version;Remote: %s-%d;Protocol: %d.%d;Client: %.100s",
494 get_remote_ipaddr(), get_remote_port(),
495 remote_major
, remote_minor
, remote_version
);
497 compat_datafellows(remote_version
);
499 if ((datafellows
& SSH_BUG_PROBE
) != 0) {
500 logit("probed from %s with %s. Don't panic.",
501 get_remote_ipaddr(), client_version_string
);
504 if ((datafellows
& SSH_BUG_SCANNER
) != 0) {
505 logit("scanned from %s with %s. Don't panic.",
506 get_remote_ipaddr(), client_version_string
);
509 if ((datafellows
& SSH_BUG_RSASIGMD5
) != 0) {
510 logit("Client version \"%.100s\" uses unsafe RSA signature "
511 "scheme; disabling use of RSA keys", remote_version
);
513 if ((datafellows
& SSH_BUG_DERIVEKEY
) != 0) {
514 fatal("Client version \"%.100s\" uses unsafe key agreement; "
515 "refusing connection", remote_version
);
519 switch (remote_major
) {
521 if (remote_minor
== 99) {
522 if (options
.protocol
& SSH_PROTO_2
)
528 if (!(options
.protocol
& SSH_PROTO_1
)) {
532 if (remote_minor
< 3) {
533 packet_disconnect("Your ssh version is too old and "
534 "is no longer supported. Please install a newer version.");
535 } else if (remote_minor
== 3) {
536 /* note that this disables agent-forwarding */
541 if (options
.protocol
& SSH_PROTO_2
) {
550 chop(server_version_string
);
551 debug("Local version string %.200s", server_version_string
);
554 s
= "Protocol major versions differ.\n";
555 (void) atomicio(vwrite
, sock_out
, s
, strlen(s
));
558 logit("Protocol major versions differ for %s: %.200s vs. %.200s",
560 server_version_string
, client_version_string
);
565 /* Destroy the host and server keys. They will no longer be needed. */
567 destroy_sensitive_data(void)
571 if (sensitive_data
.server_key
) {
572 key_free(sensitive_data
.server_key
);
573 sensitive_data
.server_key
= NULL
;
575 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
576 if (sensitive_data
.host_keys
[i
]) {
577 key_free(sensitive_data
.host_keys
[i
]);
578 sensitive_data
.host_keys
[i
] = NULL
;
580 if (sensitive_data
.host_certificates
[i
]) {
581 key_free(sensitive_data
.host_certificates
[i
]);
582 sensitive_data
.host_certificates
[i
] = NULL
;
585 sensitive_data
.ssh1_host_key
= NULL
;
586 explicit_bzero(sensitive_data
.ssh1_cookie
, SSH_SESSION_KEY_LENGTH
);
589 /* Demote private to public keys for network child */
591 demote_sensitive_data(void)
596 if (sensitive_data
.server_key
) {
597 tmp
= key_demote(sensitive_data
.server_key
);
598 key_free(sensitive_data
.server_key
);
599 sensitive_data
.server_key
= tmp
;
602 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
603 if (sensitive_data
.host_keys
[i
]) {
604 tmp
= key_demote(sensitive_data
.host_keys
[i
]);
605 key_free(sensitive_data
.host_keys
[i
]);
606 sensitive_data
.host_keys
[i
] = tmp
;
607 if (tmp
->type
== KEY_RSA1
)
608 sensitive_data
.ssh1_host_key
= tmp
;
610 /* Certs do not need demotion */
613 /* We do not clear ssh1_host key and cookie. XXX - Okay Niels? */
617 privsep_preauth_child(void)
622 /* Enable challenge-response authentication for privilege separation */
623 privsep_challenge_enable();
626 /* Cache supported mechanism OIDs for later use */
627 if (options
.gss_authentication
)
628 ssh_gssapi_prepare_supported_oids();
632 arc4random_buf(rnd
, sizeof(rnd
));
633 RAND_seed(rnd
, sizeof(rnd
));
634 explicit_bzero(rnd
, sizeof(rnd
));
636 /* Demote the private keys to public keys. */
637 demote_sensitive_data();
639 /* Change our root directory */
640 if (chroot(_PATH_PRIVSEP_CHROOT_DIR
) == -1)
641 fatal("chroot(\"%s\"): %s", _PATH_PRIVSEP_CHROOT_DIR
,
643 if (chdir("/") == -1)
644 fatal("chdir(\"/\"): %s", strerror(errno
));
646 /* Drop our privileges */
647 debug3("privsep user:group %u:%u", (u_int
)privsep_pw
->pw_uid
,
648 (u_int
)privsep_pw
->pw_gid
);
650 /* XXX not ready, too heavy after chroot */
651 do_setusercontext(privsep_pw
);
653 gidset
[0] = privsep_pw
->pw_gid
;
654 if (setgroups(1, gidset
) < 0)
655 fatal("setgroups: %.100s", strerror(errno
));
656 permanently_set_uid(privsep_pw
);
661 privsep_preauth(Authctxt
*authctxt
)
665 struct ssh_sandbox
*box
= NULL
;
667 /* Set up unprivileged child process to deal with network data */
668 pmonitor
= monitor_init();
669 /* Store a pointer to the kex for later rekeying */
670 pmonitor
->m_pkex
= &xxx_kex
;
672 if (use_privsep
== PRIVSEP_ON
)
673 box
= ssh_sandbox_init(pmonitor
);
676 fatal("fork of unprivileged child failed");
677 } else if (pid
!= 0) {
678 debug2("Network child is on pid %ld", (long)pid
);
680 pmonitor
->m_pid
= pid
;
682 auth_conn
= ssh_get_authentication_connection();
684 ssh_sandbox_parent_preauth(box
, pid
);
685 monitor_child_preauth(authctxt
, pmonitor
);
688 monitor_sync(pmonitor
);
690 /* Wait for the child's exit status */
691 while (waitpid(pid
, &status
, 0) < 0) {
694 pmonitor
->m_pid
= -1;
695 fatal("%s: waitpid: %s", __func__
, strerror(errno
));
697 privsep_is_preauth
= 0;
698 pmonitor
->m_pid
= -1;
699 if (WIFEXITED(status
)) {
700 if (WEXITSTATUS(status
) != 0)
701 fatal("%s: preauth child exited with status %d",
702 __func__
, WEXITSTATUS(status
));
703 } else if (WIFSIGNALED(status
))
704 fatal("%s: preauth child terminated by signal %d",
705 __func__
, WTERMSIG(status
));
707 ssh_sandbox_parent_finish(box
);
711 close(pmonitor
->m_sendfd
);
712 close(pmonitor
->m_log_recvfd
);
714 /* Arrange for logging to be sent to the monitor */
715 set_log_handler(mm_log_handler
, pmonitor
);
717 /* Demote the child */
718 if (getuid() == 0 || geteuid() == 0)
719 privsep_preauth_child();
720 setproctitle("%s", "[net]");
722 ssh_sandbox_child(box
);
729 privsep_postauth(Authctxt
*authctxt
)
733 #ifdef DISABLE_FD_PASSING
736 if (authctxt
->pw
->pw_uid
== 0 || options
.use_login
) {
738 /* File descriptor passing is broken or root login */
743 /* New socket pair */
744 monitor_reinit(pmonitor
);
746 pmonitor
->m_pid
= fork();
747 if (pmonitor
->m_pid
== -1)
748 fatal("fork of unprivileged child failed");
749 else if (pmonitor
->m_pid
!= 0) {
750 verbose("User child is on pid %ld", (long)pmonitor
->m_pid
);
751 buffer_clear(&loginmsg
);
752 monitor_child_postauth(pmonitor
);
760 close(pmonitor
->m_sendfd
);
761 pmonitor
->m_sendfd
= -1;
763 /* Demote the private keys to public keys. */
764 demote_sensitive_data();
767 arc4random_buf(rnd
, sizeof(rnd
));
768 RAND_seed(rnd
, sizeof(rnd
));
769 explicit_bzero(rnd
, sizeof(rnd
));
771 /* Drop privileges */
772 do_setusercontext(authctxt
->pw
);
775 /* It is safe now to apply the key state */
776 monitor_apply_keystate(pmonitor
);
779 * Tell the packet layer that authentication was successful, since
780 * this information is not part of the key state.
782 packet_set_authenticated();
786 list_hostkey_types(void)
795 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
796 key
= sensitive_data
.host_keys
[i
];
798 key
= sensitive_data
.host_pubkeys
[i
];
806 if (buffer_len(&b
) > 0)
807 buffer_append(&b
, ",", 1);
808 p
= key_ssh_name(key
);
809 buffer_append(&b
, p
, strlen(p
));
812 /* If the private key has a cert peer, then list that too */
813 key
= sensitive_data
.host_certificates
[i
];
817 case KEY_RSA_CERT_V00
:
818 case KEY_DSA_CERT_V00
:
822 case KEY_ED25519_CERT
:
823 if (buffer_len(&b
) > 0)
824 buffer_append(&b
, ",", 1);
825 p
= key_ssh_name(key
);
826 buffer_append(&b
, p
, strlen(p
));
830 buffer_append(&b
, "\0", 1);
831 ret
= xstrdup(buffer_ptr(&b
));
833 debug("list_hostkey_types: %s", ret
);
838 get_hostkey_by_type(int type
, int need_private
)
843 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
845 case KEY_RSA_CERT_V00
:
846 case KEY_DSA_CERT_V00
:
850 case KEY_ED25519_CERT
:
851 key
= sensitive_data
.host_certificates
[i
];
854 key
= sensitive_data
.host_keys
[i
];
855 if (key
== NULL
&& !need_private
)
856 key
= sensitive_data
.host_pubkeys
[i
];
859 if (key
!= NULL
&& key
->type
== type
)
860 return need_private
?
861 sensitive_data
.host_keys
[i
] : key
;
867 get_hostkey_public_by_type(int type
)
869 return get_hostkey_by_type(type
, 0);
873 get_hostkey_private_by_type(int type
)
875 return get_hostkey_by_type(type
, 1);
879 get_hostkey_by_index(int ind
)
881 if (ind
< 0 || ind
>= options
.num_host_key_files
)
883 return (sensitive_data
.host_keys
[ind
]);
887 get_hostkey_public_by_index(int ind
)
889 if (ind
< 0 || ind
>= options
.num_host_key_files
)
891 return (sensitive_data
.host_pubkeys
[ind
]);
895 get_hostkey_index(Key
*key
)
899 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
900 if (key_is_cert(key
)) {
901 if (key
== sensitive_data
.host_certificates
[i
])
904 if (key
== sensitive_data
.host_keys
[i
])
906 if (key
== sensitive_data
.host_pubkeys
[i
])
914 * returns 1 if connection should be dropped, 0 otherwise.
915 * dropping starts at connection #max_startups_begin with a probability
916 * of (max_startups_rate/100). the probability increases linearly until
917 * all connections are dropped for startups > max_startups
920 drop_connection(int startups
)
924 if (startups
< options
.max_startups_begin
)
926 if (startups
>= options
.max_startups
)
928 if (options
.max_startups_rate
== 100)
931 p
= 100 - options
.max_startups_rate
;
932 p
*= startups
- options
.max_startups_begin
;
933 p
/= options
.max_startups
- options
.max_startups_begin
;
934 p
+= options
.max_startups_rate
;
935 r
= arc4random_uniform(100);
937 debug("drop_connection: p %d, r %d", p
, r
);
938 return (r
< p
) ? 1 : 0;
944 fprintf(stderr
, "%s%s %s, %s\n",
945 SSH_RELEASE
, SSH_VERSION_HPN
, SSH_VERSION_DRAGONFLY
,
947 SSLeay_version(SSLEAY_VERSION
)
953 "usage: sshd [-46DdeiqTt] [-b bits] [-C connection_spec] [-c host_cert_file]\n"
954 " [-E log_file] [-f config_file] [-g login_grace_time]\n"
955 " [-h host_key_file] [-k key_gen_time] [-o option] [-p port]\n"
962 send_rexec_state(int fd
, Buffer
*conf
)
966 debug3("%s: entering fd = %d config len %d", __func__
, fd
,
970 * Protocol from reexec master to child:
971 * string configuration
972 * u_int ephemeral_key_follows
973 * bignum e (only if ephemeral_key_follows == 1)
979 * string rngseed (only if OpenSSL is not self-seeded)
982 buffer_put_cstring(&m
, buffer_ptr(conf
));
985 if (sensitive_data
.server_key
!= NULL
&&
986 sensitive_data
.server_key
->type
== KEY_RSA1
) {
987 buffer_put_int(&m
, 1);
988 buffer_put_bignum(&m
, sensitive_data
.server_key
->rsa
->e
);
989 buffer_put_bignum(&m
, sensitive_data
.server_key
->rsa
->n
);
990 buffer_put_bignum(&m
, sensitive_data
.server_key
->rsa
->d
);
991 buffer_put_bignum(&m
, sensitive_data
.server_key
->rsa
->iqmp
);
992 buffer_put_bignum(&m
, sensitive_data
.server_key
->rsa
->p
);
993 buffer_put_bignum(&m
, sensitive_data
.server_key
->rsa
->q
);
996 buffer_put_int(&m
, 0);
998 #ifndef OPENSSL_PRNG_ONLY
999 rexec_send_rng_seed(&m
);
1002 if (ssh_msg_send(fd
, 0, &m
) == -1)
1003 fatal("%s: ssh_msg_send failed", __func__
);
1007 debug3("%s: done", __func__
);
1011 recv_rexec_state(int fd
, Buffer
*conf
)
1017 debug3("%s: entering fd = %d", __func__
, fd
);
1021 if (ssh_msg_recv(fd
, &m
) == -1)
1022 fatal("%s: ssh_msg_recv failed", __func__
);
1023 if (buffer_get_char(&m
) != 0)
1024 fatal("%s: rexec version mismatch", __func__
);
1026 cp
= buffer_get_string(&m
, &len
);
1028 buffer_append(conf
, cp
, len
+ 1);
1031 if (buffer_get_int(&m
)) {
1033 if (sensitive_data
.server_key
!= NULL
)
1034 key_free(sensitive_data
.server_key
);
1035 sensitive_data
.server_key
= key_new_private(KEY_RSA1
);
1036 buffer_get_bignum(&m
, sensitive_data
.server_key
->rsa
->e
);
1037 buffer_get_bignum(&m
, sensitive_data
.server_key
->rsa
->n
);
1038 buffer_get_bignum(&m
, sensitive_data
.server_key
->rsa
->d
);
1039 buffer_get_bignum(&m
, sensitive_data
.server_key
->rsa
->iqmp
);
1040 buffer_get_bignum(&m
, sensitive_data
.server_key
->rsa
->p
);
1041 buffer_get_bignum(&m
, sensitive_data
.server_key
->rsa
->q
);
1042 if (rsa_generate_additional_parameters(
1043 sensitive_data
.server_key
->rsa
) != 0)
1044 fatal("%s: rsa_generate_additional_parameters "
1047 fatal("ssh1 not supported");
1051 #ifndef OPENSSL_PRNG_ONLY
1052 rexec_recv_rng_seed(&m
);
1057 debug3("%s: done", __func__
);
1060 /* Accept a connection from inetd */
1062 server_accept_inetd(int *sock_in
, int *sock_out
)
1068 close(REEXEC_CONFIG_PASS_FD
);
1069 *sock_in
= *sock_out
= dup(STDIN_FILENO
);
1071 startup_pipe
= dup(REEXEC_STARTUP_PIPE_FD
);
1072 close(REEXEC_STARTUP_PIPE_FD
);
1075 *sock_in
= dup(STDIN_FILENO
);
1076 *sock_out
= dup(STDOUT_FILENO
);
1079 * We intentionally do not close the descriptors 0, 1, and 2
1080 * as our code for setting the descriptors won't work if
1081 * ttyfd happens to be one of those.
1083 if ((fd
= open(_PATH_DEVNULL
, O_RDWR
, 0)) != -1) {
1084 dup2(fd
, STDIN_FILENO
);
1085 dup2(fd
, STDOUT_FILENO
);
1087 dup2(fd
, STDERR_FILENO
);
1088 if (fd
> (log_stderr
? STDERR_FILENO
: STDOUT_FILENO
))
1091 debug("inetd sockets after dupping: %d, %d", *sock_in
, *sock_out
);
1095 * Listen for TCP connections
1100 int ret
, listen_sock
, on
= 1;
1101 struct addrinfo
*ai
;
1102 char ntop
[NI_MAXHOST
], strport
[NI_MAXSERV
];
1104 int socksizelen
= sizeof(int);
1106 for (ai
= options
.listen_addrs
; ai
; ai
= ai
->ai_next
) {
1107 if (ai
->ai_family
!= AF_INET
&& ai
->ai_family
!= AF_INET6
)
1109 if (num_listen_socks
>= MAX_LISTEN_SOCKS
)
1110 fatal("Too many listen sockets. "
1111 "Enlarge MAX_LISTEN_SOCKS");
1112 if ((ret
= getnameinfo(ai
->ai_addr
, ai
->ai_addrlen
,
1113 ntop
, sizeof(ntop
), strport
, sizeof(strport
),
1114 NI_NUMERICHOST
|NI_NUMERICSERV
)) != 0) {
1115 error("getnameinfo failed: %.100s",
1116 ssh_gai_strerror(ret
));
1119 /* Create socket for listening. */
1120 listen_sock
= socket(ai
->ai_family
, ai
->ai_socktype
,
1122 if (listen_sock
< 0) {
1123 /* kernel may not support ipv6 */
1124 verbose("socket: %.100s", strerror(errno
));
1127 if (set_nonblock(listen_sock
) == -1) {
1132 * Set socket options.
1133 * Allow local port reuse in TIME_WAIT.
1135 if (setsockopt(listen_sock
, SOL_SOCKET
, SO_REUSEADDR
,
1136 &on
, sizeof(on
)) == -1)
1137 error("setsockopt SO_REUSEADDR: %s", strerror(errno
));
1139 /* Only communicate in IPv6 over AF_INET6 sockets. */
1140 if (ai
->ai_family
== AF_INET6
)
1141 sock_set_v6only(listen_sock
);
1143 debug("Bind to port %s on %s.", strport
, ntop
);
1145 getsockopt(listen_sock
, SOL_SOCKET
, SO_RCVBUF
,
1146 &socksize
, &socksizelen
);
1147 debug("Server TCP RWIN socket size: %d", socksize
);
1148 debug("HPN Buffer Size: %d", options
.hpn_buffer_size
);
1150 /* Bind the socket to the desired port. */
1151 if (bind(listen_sock
, ai
->ai_addr
, ai
->ai_addrlen
) < 0) {
1152 error("Bind to port %s on %s failed: %.200s.",
1153 strport
, ntop
, strerror(errno
));
1157 listen_socks
[num_listen_socks
] = listen_sock
;
1160 /* Start listening on the port. */
1161 if (listen(listen_sock
, SSH_LISTEN_BACKLOG
) < 0)
1162 fatal("listen on [%s]:%s: %.100s",
1163 ntop
, strport
, strerror(errno
));
1164 logit("Server listening on %s port %s.", ntop
, strport
);
1166 freeaddrinfo(options
.listen_addrs
);
1168 if (!num_listen_socks
)
1169 fatal("Cannot bind any address.");
1173 * The main TCP accept loop. Note that, for the non-debug case, returns
1174 * from this function are in a forked subprocess.
1177 server_accept_loop(int *sock_in
, int *sock_out
, int *newsock
, int *config_s
)
1180 int i
, j
, ret
, maxfd
;
1181 int key_used
= 0, startups
= 0;
1182 int startup_p
[2] = { -1 , -1 };
1183 struct sockaddr_storage from
;
1188 /* setup fd set for accept */
1191 for (i
= 0; i
< num_listen_socks
; i
++)
1192 if (listen_socks
[i
] > maxfd
)
1193 maxfd
= listen_socks
[i
];
1194 /* pipes connected to unauthenticated childs */
1195 startup_pipes
= xcalloc(options
.max_startups
, sizeof(int));
1196 for (i
= 0; i
< options
.max_startups
; i
++)
1197 startup_pipes
[i
] = -1;
1200 * Stay listening for connections until the system crashes or
1201 * the daemon is killed with a signal.
1204 if (received_sighup
)
1208 fdset
= (fd_set
*)xcalloc(howmany(maxfd
+ 1, NFDBITS
),
1211 for (i
= 0; i
< num_listen_socks
; i
++)
1212 FD_SET(listen_socks
[i
], fdset
);
1213 for (i
= 0; i
< options
.max_startups
; i
++)
1214 if (startup_pipes
[i
] != -1)
1215 FD_SET(startup_pipes
[i
], fdset
);
1217 /* Wait in select until there is a connection. */
1218 ret
= select(maxfd
+1, fdset
, NULL
, NULL
, NULL
);
1219 if (ret
< 0 && errno
!= EINTR
)
1220 error("select: %.100s", strerror(errno
));
1221 if (received_sigterm
) {
1222 logit("Received signal %d; terminating.",
1223 (int) received_sigterm
);
1224 close_listen_socks();
1225 unlink(options
.pid_file
);
1226 exit(received_sigterm
== SIGTERM
? 0 : 255);
1228 if (key_used
&& key_do_regen
) {
1229 generate_ephemeral_server_key();
1236 for (i
= 0; i
< options
.max_startups
; i
++)
1237 if (startup_pipes
[i
] != -1 &&
1238 FD_ISSET(startup_pipes
[i
], fdset
)) {
1240 * the read end of the pipe is ready
1241 * if the child has closed the pipe
1242 * after successful authentication
1243 * or if the child has died
1245 close(startup_pipes
[i
]);
1246 startup_pipes
[i
] = -1;
1249 for (i
= 0; i
< num_listen_socks
; i
++) {
1250 if (!FD_ISSET(listen_socks
[i
], fdset
))
1252 fromlen
= sizeof(from
);
1253 *newsock
= accept(listen_socks
[i
],
1254 (struct sockaddr
*)&from
, &fromlen
);
1256 if (errno
!= EINTR
&& errno
!= EWOULDBLOCK
&&
1257 errno
!= ECONNABORTED
&& errno
!= EAGAIN
)
1258 error("accept: %.100s",
1260 if (errno
== EMFILE
|| errno
== ENFILE
)
1264 if (unset_nonblock(*newsock
) == -1) {
1268 if (drop_connection(startups
) == 1) {
1269 debug("drop connection #%d", startups
);
1273 if (pipe(startup_p
) == -1) {
1278 if (rexec_flag
&& socketpair(AF_UNIX
,
1279 SOCK_STREAM
, 0, config_s
) == -1) {
1280 error("reexec socketpair: %s",
1283 close(startup_p
[0]);
1284 close(startup_p
[1]);
1288 for (j
= 0; j
< options
.max_startups
; j
++)
1289 if (startup_pipes
[j
] == -1) {
1290 startup_pipes
[j
] = startup_p
[0];
1291 if (maxfd
< startup_p
[0])
1292 maxfd
= startup_p
[0];
1298 * Got connection. Fork a child to handle it, unless
1299 * we are in debugging mode.
1303 * In debugging mode. Close the listening
1304 * socket, and start processing the
1305 * connection without forking.
1307 debug("Server will not fork when running in debugging mode.");
1308 close_listen_socks();
1309 *sock_in
= *newsock
;
1310 *sock_out
= *newsock
;
1311 close(startup_p
[0]);
1312 close(startup_p
[1]);
1316 send_rexec_state(config_s
[0],
1324 * Normal production daemon. Fork, and have
1325 * the child process the connection. The
1326 * parent continues listening.
1328 platform_pre_fork();
1329 if ((pid
= fork()) == 0) {
1331 * Child. Close the listening and
1332 * max_startup sockets. Start using
1333 * the accepted socket. Reinitialize
1334 * logging (since our pid has changed).
1335 * We break out of the loop to handle
1338 platform_post_fork_child();
1339 startup_pipe
= startup_p
[1];
1340 close_startup_pipes();
1341 close_listen_socks();
1342 *sock_in
= *newsock
;
1343 *sock_out
= *newsock
;
1344 log_init(__progname
,
1346 options
.log_facility
,
1353 /* Parent. Stay in the loop. */
1354 platform_post_fork_parent(pid
);
1356 error("fork: %.100s", strerror(errno
));
1358 debug("Forked child %ld.", (long)pid
);
1360 close(startup_p
[1]);
1363 send_rexec_state(config_s
[0], &cfg
);
1369 * Mark that the key has been used (it
1370 * was "given" to the child).
1372 if ((options
.protocol
& SSH_PROTO_1
) &&
1374 /* Schedule server key regeneration alarm. */
1375 signal(SIGALRM
, key_regeneration_alarm
);
1376 alarm(options
.key_regeneration_time
);
1383 * Ensure that our random state differs
1384 * from that of the child
1387 arc4random_buf(rnd
, sizeof(rnd
));
1388 RAND_seed(rnd
, sizeof(rnd
));
1389 explicit_bzero(rnd
, sizeof(rnd
));
1392 /* child process check (or debug mode) */
1393 if (num_listen_socks
< 0)
1400 * Main program for the daemon.
1403 main(int ac
, char **av
)
1405 extern char *optarg
;
1407 int opt
, i
, j
, on
= 1;
1408 int sock_in
= -1, sock_out
= -1, newsock
= -1;
1409 const char *remote_ip
;
1411 char *line
, *logfile
= NULL
;
1412 int config_s
[2] = { -1 , -1 };
1414 u_int64_t ibytes
, obytes
;
1420 struct connection_info
*connection_info
= get_connection_info(0, 0);
1422 #ifdef HAVE_SECUREWARE
1423 (void)set_auth_parameters(ac
, av
);
1425 __progname
= ssh_get_progname(av
[0]);
1427 /* Save argv. Duplicate so setproctitle emulation doesn't clobber it */
1430 saved_argv
= xcalloc(ac
+ 1, sizeof(*saved_argv
));
1431 for (i
= 0; i
< ac
; i
++)
1432 saved_argv
[i
] = xstrdup(av
[i
]);
1433 saved_argv
[i
] = NULL
;
1435 #ifndef HAVE_SETPROCTITLE
1436 /* Prepare for later setproctitle emulation */
1437 compat_init_setproctitle(ac
, av
);
1441 if (geteuid() == 0 && setgroups(0, NULL
) == -1)
1442 debug("setgroups(): %.200s", strerror(errno
));
1444 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
1447 /* Initialize configuration options to their default values. */
1448 initialize_server_options(&options
);
1450 /* Parse command-line arguments. */
1451 while ((opt
= getopt(ac
, av
, "f:p:b:k:h:g:u:o:C:dDeE:iqrtQRT46")) != -1) {
1454 options
.address_family
= AF_INET
;
1457 options
.address_family
= AF_INET6
;
1460 config_file_name
= optarg
;
1463 if (options
.num_host_cert_files
>= MAX_HOSTCERTS
) {
1464 fprintf(stderr
, "too many host certificates.\n");
1467 options
.host_cert_files
[options
.num_host_cert_files
++] =
1468 derelativise_path(optarg
);
1471 if (debug_flag
== 0) {
1473 options
.log_level
= SYSLOG_LEVEL_DEBUG1
;
1474 } else if (options
.log_level
< SYSLOG_LEVEL_DEBUG3
)
1475 options
.log_level
++;
1481 logfile
= xstrdup(optarg
);
1500 options
.log_level
= SYSLOG_LEVEL_QUIET
;
1503 options
.server_key_bits
= (int)strtonum(optarg
, 256,
1507 options
.ports_from_cmdline
= 1;
1508 if (options
.num_ports
>= MAX_PORTS
) {
1509 fprintf(stderr
, "too many ports.\n");
1512 options
.ports
[options
.num_ports
++] = a2port(optarg
);
1513 if (options
.ports
[options
.num_ports
-1] <= 0) {
1514 fprintf(stderr
, "Bad port number.\n");
1519 if ((options
.login_grace_time
= convtime(optarg
)) == -1) {
1520 fprintf(stderr
, "Invalid login grace time.\n");
1525 if ((options
.key_regeneration_time
= convtime(optarg
)) == -1) {
1526 fprintf(stderr
, "Invalid key regeneration interval.\n");
1531 if (options
.num_host_key_files
>= MAX_HOSTKEYS
) {
1532 fprintf(stderr
, "too many host keys.\n");
1535 options
.host_key_files
[options
.num_host_key_files
++] =
1536 derelativise_path(optarg
);
1545 if (parse_server_match_testspec(connection_info
,
1550 utmp_len
= (u_int
)strtonum(optarg
, 0, MAXHOSTNAMELEN
+1, NULL
);
1551 if (utmp_len
> MAXHOSTNAMELEN
) {
1552 fprintf(stderr
, "Invalid utmp length.\n");
1557 line
= xstrdup(optarg
);
1558 if (process_server_config_line(&options
, line
,
1559 "command-line", 0, NULL
, NULL
) != 0)
1569 if (rexeced_flag
|| inetd_flag
)
1571 if (!test_flag
&& (rexec_flag
&& (av
[0] == NULL
|| *av
[0] != '/')))
1572 fatal("sshd re-exec requires execution with an absolute path");
1574 closefrom(REEXEC_MIN_FREE_FD
);
1576 closefrom(REEXEC_DEVCRYPTO_RESERVED_FD
);
1579 OpenSSL_add_all_algorithms();
1582 /* If requested, redirect the logs to the specified logfile. */
1583 if (logfile
!= NULL
) {
1584 log_redirect_stderr_to(logfile
);
1588 * Force logging to stderr until we have loaded the private host
1589 * key (unless started from inetd)
1591 log_init(__progname
,
1592 options
.log_level
== SYSLOG_LEVEL_NOT_SET
?
1593 SYSLOG_LEVEL_INFO
: options
.log_level
,
1594 options
.log_facility
== SYSLOG_FACILITY_NOT_SET
?
1595 SYSLOG_FACILITY_AUTH
: options
.log_facility
,
1596 log_stderr
|| !inetd_flag
);
1599 * Unset KRB5CCNAME, otherwise the user's session may inherit it from
1600 * root's environment
1602 if (getenv("KRB5CCNAME") != NULL
)
1603 (void) unsetenv("KRB5CCNAME");
1606 /* Cray can define user privs drop all privs now!
1607 * Not needed on PRIV_SU systems!
1612 sensitive_data
.server_key
= NULL
;
1613 sensitive_data
.ssh1_host_key
= NULL
;
1614 sensitive_data
.have_ssh1_key
= 0;
1615 sensitive_data
.have_ssh2_key
= 0;
1618 * If we're doing an extended config test, make sure we have all of
1619 * the parameters we need. If we're not doing an extended test,
1620 * do not silently ignore connection test params.
1622 if (test_flag
>= 2 && server_match_spec_complete(connection_info
) == 0)
1623 fatal("user, host and addr are all required when testing "
1625 if (test_flag
< 2 && server_match_spec_complete(connection_info
) >= 0)
1626 fatal("Config test connection parameter (-C) provided without "
1629 /* Fetch our configuration */
1632 recv_rexec_state(REEXEC_CONFIG_PASS_FD
, &cfg
);
1634 load_server_config(config_file_name
, &cfg
);
1636 parse_server_config(&options
, rexeced_flag
? "rexec" : config_file_name
,
1641 /* Fill in default values for those options not explicitly set. */
1642 fill_default_server_options(&options
);
1644 /* challenge-response is implemented via keyboard interactive */
1645 if (options
.challenge_response_authentication
)
1646 options
.kbd_interactive_authentication
= 1;
1648 /* Check that options are sensible */
1649 if (options
.authorized_keys_command_user
== NULL
&&
1650 (options
.authorized_keys_command
!= NULL
&&
1651 strcasecmp(options
.authorized_keys_command
, "none") != 0))
1652 fatal("AuthorizedKeysCommand set without "
1653 "AuthorizedKeysCommandUser");
1656 * Check whether there is any path through configured auth methods.
1657 * Unfortunately it is not possible to verify this generally before
1658 * daemonisation in the presence of Match block, but this catches
1659 * and warns for trivial misconfigurations that could break login.
1661 if (options
.num_auth_methods
!= 0) {
1662 if ((options
.protocol
& SSH_PROTO_1
))
1663 fatal("AuthenticationMethods is not supported with "
1665 for (n
= 0; n
< options
.num_auth_methods
; n
++) {
1666 if (auth2_methods_valid(options
.auth_methods
[n
],
1670 if (n
>= options
.num_auth_methods
)
1671 fatal("AuthenticationMethods cannot be satisfied by "
1672 "enabled authentication methods");
1675 /* set default channel AF */
1676 channel_set_af(options
.address_family
);
1678 /* Check that there are no remaining arguments. */
1680 fprintf(stderr
, "Extra argument %s.\n", av
[optind
]);
1684 debug("sshd version %s, %s", SSH_VERSION
,
1686 SSLeay_version(SSLEAY_VERSION
)
1692 /* Store privilege separation user for later use if required. */
1693 if ((privsep_pw
= getpwnam(SSH_PRIVSEP_USER
)) == NULL
) {
1694 if (use_privsep
|| options
.kerberos_authentication
)
1695 fatal("Privilege separation user %s does not exist",
1698 explicit_bzero(privsep_pw
->pw_passwd
,
1699 strlen(privsep_pw
->pw_passwd
));
1700 privsep_pw
= pwcopy(privsep_pw
);
1701 free(privsep_pw
->pw_passwd
);
1702 privsep_pw
->pw_passwd
= xstrdup("*");
1706 /* load host keys */
1707 sensitive_data
.host_keys
= xcalloc(options
.num_host_key_files
,
1709 sensitive_data
.host_pubkeys
= xcalloc(options
.num_host_key_files
,
1711 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
1712 sensitive_data
.host_keys
[i
] = NULL
;
1713 sensitive_data
.host_pubkeys
[i
] = NULL
;
1716 if (options
.host_key_agent
) {
1717 if (strcmp(options
.host_key_agent
, SSH_AUTHSOCKET_ENV_NAME
))
1718 setenv(SSH_AUTHSOCKET_ENV_NAME
,
1719 options
.host_key_agent
, 1);
1720 have_agent
= ssh_agent_present();
1723 for (i
= 0; i
< options
.num_host_key_files
; i
++) {
1724 key
= key_load_private(options
.host_key_files
[i
], "", NULL
);
1725 pubkey
= key_load_public(options
.host_key_files
[i
], NULL
);
1726 sensitive_data
.host_keys
[i
] = key
;
1727 sensitive_data
.host_pubkeys
[i
] = pubkey
;
1729 if (key
== NULL
&& pubkey
!= NULL
&& pubkey
->type
!= KEY_RSA1
&&
1731 debug("will rely on agent for hostkey %s",
1732 options
.host_key_files
[i
]);
1733 keytype
= pubkey
->type
;
1734 } else if (key
!= NULL
) {
1735 keytype
= key
->type
;
1737 error("Could not load host key: %s",
1738 options
.host_key_files
[i
]);
1739 sensitive_data
.host_keys
[i
] = NULL
;
1740 sensitive_data
.host_pubkeys
[i
] = NULL
;
1746 sensitive_data
.ssh1_host_key
= key
;
1747 sensitive_data
.have_ssh1_key
= 1;
1753 sensitive_data
.have_ssh2_key
= 1;
1756 debug("private host key: #%d type %d %s", i
, keytype
,
1757 key_type(key
? key
: pubkey
));
1759 if ((options
.protocol
& SSH_PROTO_1
) && !sensitive_data
.have_ssh1_key
) {
1760 logit("Disabling protocol version 1. Could not load host key");
1761 options
.protocol
&= ~SSH_PROTO_1
;
1763 if ((options
.protocol
& SSH_PROTO_2
) && !sensitive_data
.have_ssh2_key
) {
1764 logit("Disabling protocol version 2. Could not load host key");
1765 options
.protocol
&= ~SSH_PROTO_2
;
1767 if (!(options
.protocol
& (SSH_PROTO_1
|SSH_PROTO_2
))) {
1768 logit("sshd: no hostkeys available -- exiting.");
1773 * Load certificates. They are stored in an array at identical
1774 * indices to the public keys that they relate to.
1776 sensitive_data
.host_certificates
= xcalloc(options
.num_host_key_files
,
1778 for (i
= 0; i
< options
.num_host_key_files
; i
++)
1779 sensitive_data
.host_certificates
[i
] = NULL
;
1781 for (i
= 0; i
< options
.num_host_cert_files
; i
++) {
1782 key
= key_load_public(options
.host_cert_files
[i
], NULL
);
1784 error("Could not load host certificate: %s",
1785 options
.host_cert_files
[i
]);
1788 if (!key_is_cert(key
)) {
1789 error("Certificate file is not a certificate: %s",
1790 options
.host_cert_files
[i
]);
1794 /* Find matching private key */
1795 for (j
= 0; j
< options
.num_host_key_files
; j
++) {
1796 if (key_equal_public(key
,
1797 sensitive_data
.host_keys
[j
])) {
1798 sensitive_data
.host_certificates
[j
] = key
;
1802 if (j
>= options
.num_host_key_files
) {
1803 error("No matching private key for certificate: %s",
1804 options
.host_cert_files
[i
]);
1808 sensitive_data
.host_certificates
[j
] = key
;
1809 debug("host certificate: #%d type %d %s", j
, key
->type
,
1814 /* Check certain values for sanity. */
1815 if (options
.protocol
& SSH_PROTO_1
) {
1816 if (options
.server_key_bits
< 512 ||
1817 options
.server_key_bits
> 32768) {
1818 fprintf(stderr
, "Bad server key size.\n");
1822 * Check that server and host key lengths differ sufficiently. This
1823 * is necessary to make double encryption work with rsaref. Oh, I
1824 * hate software patents. I dont know if this can go? Niels
1826 if (options
.server_key_bits
>
1827 BN_num_bits(sensitive_data
.ssh1_host_key
->rsa
->n
) -
1828 SSH_KEY_BITS_RESERVED
&& options
.server_key_bits
<
1829 BN_num_bits(sensitive_data
.ssh1_host_key
->rsa
->n
) +
1830 SSH_KEY_BITS_RESERVED
) {
1831 options
.server_key_bits
=
1832 BN_num_bits(sensitive_data
.ssh1_host_key
->rsa
->n
) +
1833 SSH_KEY_BITS_RESERVED
;
1834 debug("Forcing server key to %d bits to make it differ from host key.",
1835 options
.server_key_bits
);
1843 if ((stat(_PATH_PRIVSEP_CHROOT_DIR
, &st
) == -1) ||
1844 (S_ISDIR(st
.st_mode
) == 0))
1845 fatal("Missing privilege separation directory: %s",
1846 _PATH_PRIVSEP_CHROOT_DIR
);
1849 if (check_ntsec(_PATH_PRIVSEP_CHROOT_DIR
) &&
1850 (st
.st_uid
!= getuid () ||
1851 (st
.st_mode
& (S_IWGRP
|S_IWOTH
)) != 0))
1853 if (st
.st_uid
!= 0 || (st
.st_mode
& (S_IWGRP
|S_IWOTH
)) != 0)
1855 fatal("%s must be owned by root and not group or "
1856 "world-writable.", _PATH_PRIVSEP_CHROOT_DIR
);
1859 if (test_flag
> 1) {
1860 if (server_match_spec_complete(connection_info
) == 1)
1861 parse_server_match_config(&options
, connection_info
);
1862 dump_config(&options
);
1865 /* Configuration looks good, so exit if in test mode. */
1870 * Clear out any supplemental groups we may have inherited. This
1871 * prevents inadvertent creation of files with bad modes (in the
1872 * portable version at least, it's certainly possible for PAM
1873 * to create a file, and we can't control the code in every
1874 * module which might be used).
1876 if (setgroups(0, NULL
) < 0)
1877 debug("setgroups() failed: %.200s", strerror(errno
));
1880 rexec_argv
= xcalloc(rexec_argc
+ 2, sizeof(char *));
1881 for (i
= 0; i
< rexec_argc
; i
++) {
1882 debug("rexec_argv[%d]='%s'", i
, saved_argv
[i
]);
1883 rexec_argv
[i
] = saved_argv
[i
];
1885 rexec_argv
[rexec_argc
] = "-R";
1886 rexec_argv
[rexec_argc
+ 1] = NULL
;
1889 /* Ensure that umask disallows at least group and world write */
1890 new_umask
= umask(0077) | 0022;
1891 (void) umask(new_umask
);
1893 /* Initialize the log (it is reinitialized below in case we forked). */
1894 if (debug_flag
&& (!inetd_flag
|| rexeced_flag
))
1896 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
1899 * If not in debugging mode, and not started from inetd, disconnect
1900 * from the controlling terminal, and fork. The original process
1903 if (!(debug_flag
|| inetd_flag
|| no_daemon_flag
)) {
1906 #endif /* TIOCNOTTY */
1907 if (daemon(0, 0) < 0)
1908 fatal("daemon() failed: %.200s", strerror(errno
));
1910 /* Disconnect from the controlling tty. */
1912 fd
= open(_PATH_TTY
, O_RDWR
| O_NOCTTY
);
1914 (void) ioctl(fd
, TIOCNOTTY
, NULL
);
1917 #endif /* TIOCNOTTY */
1919 /* Reinitialize the log (because of the fork above). */
1920 log_init(__progname
, options
.log_level
, options
.log_facility
, log_stderr
);
1922 /* Chdir to the root directory so that the current disk can be
1923 unmounted if desired. */
1924 if (chdir("/") == -1)
1925 error("chdir(\"/\"): %s", strerror(errno
));
1927 /* ignore SIGPIPE */
1928 signal(SIGPIPE
, SIG_IGN
);
1930 /* Get a connection, either from inetd or a listening TCP socket */
1932 server_accept_inetd(&sock_in
, &sock_out
);
1934 platform_pre_listen();
1937 if (options
.protocol
& SSH_PROTO_1
)
1938 generate_ephemeral_server_key();
1940 signal(SIGHUP
, sighup_handler
);
1941 signal(SIGCHLD
, main_sigchld_handler
);
1942 signal(SIGTERM
, sigterm_handler
);
1943 signal(SIGQUIT
, sigterm_handler
);
1946 * Write out the pid file after the sigterm handler
1947 * is setup and the listen sockets are bound
1950 FILE *f
= fopen(options
.pid_file
, "w");
1953 error("Couldn't create pid file \"%s\": %s",
1954 options
.pid_file
, strerror(errno
));
1956 fprintf(f
, "%ld\n", (long) getpid());
1961 /* Accept a connection and return in a forked child */
1962 server_accept_loop(&sock_in
, &sock_out
,
1963 &newsock
, config_s
);
1966 /* This is the child processing a new connection. */
1967 setproctitle("%s", "[accepted]");
1970 * Initialize the resolver. This may not happen automatically
1971 * before privsep chroot().
1973 if ((_res
.options
& RES_INIT
) == 0) {
1974 debug("res_init()");
1979 * Create a new session and process group since the 4.4BSD
1980 * setlogin() affects the entire process group. We don't
1981 * want the child to be able to affect the parent.
1983 #if !defined(SSHD_ACQUIRES_CTTY)
1985 * If setsid is called, on some platforms sshd will later acquire a
1986 * controlling terminal which will result in "could not set
1987 * controlling tty" errors.
1989 if (!debug_flag
&& !inetd_flag
&& setsid() < 0)
1990 error("setsid: %.100s", strerror(errno
));
1996 debug("rexec start in %d out %d newsock %d pipe %d sock %d",
1997 sock_in
, sock_out
, newsock
, startup_pipe
, config_s
[0]);
1998 dup2(newsock
, STDIN_FILENO
);
1999 dup2(STDIN_FILENO
, STDOUT_FILENO
);
2000 if (startup_pipe
== -1)
2001 close(REEXEC_STARTUP_PIPE_FD
);
2002 else if (startup_pipe
!= REEXEC_STARTUP_PIPE_FD
) {
2003 dup2(startup_pipe
, REEXEC_STARTUP_PIPE_FD
);
2004 close(startup_pipe
);
2005 startup_pipe
= REEXEC_STARTUP_PIPE_FD
;
2008 dup2(config_s
[1], REEXEC_CONFIG_PASS_FD
);
2011 execv(rexec_argv
[0], rexec_argv
);
2013 /* Reexec has failed, fall back and continue */
2014 error("rexec of %s failed: %s", rexec_argv
[0], strerror(errno
));
2015 recv_rexec_state(REEXEC_CONFIG_PASS_FD
, NULL
);
2016 log_init(__progname
, options
.log_level
,
2017 options
.log_facility
, log_stderr
);
2020 close(REEXEC_CONFIG_PASS_FD
);
2021 newsock
= sock_out
= sock_in
= dup(STDIN_FILENO
);
2022 if ((fd
= open(_PATH_DEVNULL
, O_RDWR
, 0)) != -1) {
2023 dup2(fd
, STDIN_FILENO
);
2024 dup2(fd
, STDOUT_FILENO
);
2025 if (fd
> STDERR_FILENO
)
2028 debug("rexec cleanup in %d out %d newsock %d pipe %d sock %d",
2029 sock_in
, sock_out
, newsock
, startup_pipe
, config_s
[0]);
2032 /* Executed child processes don't need these. */
2033 fcntl(sock_out
, F_SETFD
, FD_CLOEXEC
);
2034 fcntl(sock_in
, F_SETFD
, FD_CLOEXEC
);
2037 * Disable the key regeneration alarm. We will not regenerate the
2038 * key since we are no longer in a position to give it to anyone. We
2039 * will not restart on SIGHUP since it no longer makes sense.
2042 signal(SIGALRM
, SIG_DFL
);
2043 signal(SIGHUP
, SIG_DFL
);
2044 signal(SIGTERM
, SIG_DFL
);
2045 signal(SIGQUIT
, SIG_DFL
);
2046 signal(SIGCHLD
, SIG_DFL
);
2047 signal(SIGINT
, SIG_DFL
);
2050 * Register our connection. This turns encryption off because we do
2053 packet_set_connection(sock_in
, sock_out
);
2054 packet_set_server();
2056 /* Set SO_KEEPALIVE if requested. */
2057 if (options
.tcp_keep_alive
&& packet_connection_is_on_socket() &&
2058 setsockopt(sock_in
, SOL_SOCKET
, SO_KEEPALIVE
, &on
, sizeof(on
)) < 0)
2059 error("setsockopt SO_KEEPALIVE: %.100s", strerror(errno
));
2061 if ((remote_port
= get_remote_port()) < 0) {
2062 debug("get_remote_port failed");
2067 * We use get_canonical_hostname with usedns = 0 instead of
2068 * get_remote_ipaddr here so IP options will be checked.
2070 (void) get_canonical_hostname(0);
2072 * The rest of the code depends on the fact that
2073 * get_remote_ipaddr() caches the remote ip, even if
2074 * the socket goes away.
2076 remote_ip
= get_remote_ipaddr();
2078 #ifdef SSH_AUDIT_EVENTS
2079 audit_connection_from(remote_ip
, remote_port
);
2082 /* Log the connection. */
2083 verbose("Connection from %s port %d on %s port %d",
2084 remote_ip
, remote_port
,
2085 get_local_ipaddr(sock_in
), get_local_port());
2087 /* set the HPN options for the child */
2088 channel_set_hpn(options
.hpn_disabled
, options
.hpn_buffer_size
);
2091 * We don't want to listen forever unless the other side
2092 * successfully authenticates itself. So we set up an alarm which is
2093 * cleared after successful authentication. A limit of zero
2094 * indicates no limit. Note that we don't set the alarm in debugging
2095 * mode; it is just annoying to have the server exit just when you
2096 * are about to discover the bug.
2098 signal(SIGALRM
, grace_alarm_handler
);
2100 alarm(options
.login_grace_time
);
2102 sshd_exchange_identification(sock_in
, sock_out
);
2104 /* In inetd mode, generate ephemeral key only for proto 1 connections */
2105 if (!compat20
&& inetd_flag
&& sensitive_data
.server_key
== NULL
)
2106 generate_ephemeral_server_key();
2108 packet_set_nonblocking();
2110 /* allocate authentication context */
2111 authctxt
= xcalloc(1, sizeof(*authctxt
));
2113 authctxt
->loginmsg
= &loginmsg
;
2115 /* XXX global for cleanup, access from other modules */
2116 the_authctxt
= authctxt
;
2118 /* prepare buffer to collect messages to display to user after login */
2119 buffer_init(&loginmsg
);
2123 if (privsep_preauth(authctxt
) == 1)
2125 } else if (compat20
&& have_agent
)
2126 auth_conn
= ssh_get_authentication_connection();
2128 /* perform the key exchange */
2129 /* authenticate user and start session */
2132 do_authentication2(authctxt
);
2136 do_authentication(authctxt
);
2138 fatal("ssh1 not supported");
2142 * If we use privilege separation, the unprivileged child transfers
2143 * the current keystate and exits
2146 mm_send_keystate(pmonitor
);
2152 * Cancel the alarm we set to limit the time taken for
2156 signal(SIGALRM
, SIG_DFL
);
2157 authctxt
->authenticated
= 1;
2158 if (startup_pipe
!= -1) {
2159 close(startup_pipe
);
2163 #ifdef SSH_AUDIT_EVENTS
2164 audit_event(SSH_AUTH_SUCCESS
);
2168 if (options
.gss_authentication
) {
2169 temporarily_use_uid(authctxt
->pw
);
2170 ssh_gssapi_storecreds();
2175 if (options
.use_pam
) {
2182 * In privilege separation, we fork another child and prepare
2183 * file descriptor passing.
2186 privsep_postauth(authctxt
);
2187 /* the monitor process [priv] will not return */
2189 destroy_sensitive_data();
2192 packet_set_timeout(options
.client_alive_interval
,
2193 options
.client_alive_count_max
);
2195 /* Start session. */
2197 /* if we are using aes-ctr there can be issues in either a fork or sandbox
2198 * so the initial aes-ctr is defined to point ot the original single process
2199 * evp. After authentication we'll be past the fork and the sandboxed privsep
2200 * so we repoint the define to the multithreaded evp. To start the threads we
2201 * then force a rekey
2203 CipherContext
*ccsend
;
2204 ccsend
= (CipherContext
*)packet_get_send_context();
2206 /* only rekey if necessary. If we don't do this gcm mode cipher breaks */
2207 if (strstr(cipher_return_name((Cipher
*)ccsend
->cipher
), "ctr")) {
2208 debug ("Single to Multithreaded CTR cipher swap - server request");
2209 cipher_reset_multithreaded();
2210 packet_request_rekeying();
2213 do_authenticated(authctxt
);
2215 /* The connection has been terminated. */
2216 packet_get_state(MODE_IN
, NULL
, NULL
, NULL
, &ibytes
);
2217 packet_get_state(MODE_OUT
, NULL
, NULL
, NULL
, &obytes
);
2218 verbose("Transferred: sent %llu, received %llu bytes",
2219 (unsigned long long)obytes
, (unsigned long long)ibytes
);
2221 verbose("Closing connection to %.500s port %d", remote_ip
, remote_port
);
2224 if (options
.use_pam
)
2226 #endif /* USE_PAM */
2228 #ifdef SSH_AUDIT_EVENTS
2229 PRIVSEP(audit_event(SSH_CONNECTION_CLOSE
));
2242 * Decrypt session_key_int using our private server key and private host key
2243 * (key with larger modulus first).
2246 ssh1_session_key(BIGNUM
*session_key_int
)
2250 if (BN_cmp(sensitive_data
.server_key
->rsa
->n
,
2251 sensitive_data
.ssh1_host_key
->rsa
->n
) > 0) {
2252 /* Server key has bigger modulus. */
2253 if (BN_num_bits(sensitive_data
.server_key
->rsa
->n
) <
2254 BN_num_bits(sensitive_data
.ssh1_host_key
->rsa
->n
) +
2255 SSH_KEY_BITS_RESERVED
) {
2256 fatal("do_connection: %s: "
2257 "server_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d",
2258 get_remote_ipaddr(),
2259 BN_num_bits(sensitive_data
.server_key
->rsa
->n
),
2260 BN_num_bits(sensitive_data
.ssh1_host_key
->rsa
->n
),
2261 SSH_KEY_BITS_RESERVED
);
2263 if (rsa_private_decrypt(session_key_int
, session_key_int
,
2264 sensitive_data
.server_key
->rsa
) != 0)
2266 if (rsa_private_decrypt(session_key_int
, session_key_int
,
2267 sensitive_data
.ssh1_host_key
->rsa
) != 0)
2270 /* Host key has bigger modulus (or they are equal). */
2271 if (BN_num_bits(sensitive_data
.ssh1_host_key
->rsa
->n
) <
2272 BN_num_bits(sensitive_data
.server_key
->rsa
->n
) +
2273 SSH_KEY_BITS_RESERVED
) {
2274 fatal("do_connection: %s: "
2275 "host_key %d < server_key %d + SSH_KEY_BITS_RESERVED %d",
2276 get_remote_ipaddr(),
2277 BN_num_bits(sensitive_data
.ssh1_host_key
->rsa
->n
),
2278 BN_num_bits(sensitive_data
.server_key
->rsa
->n
),
2279 SSH_KEY_BITS_RESERVED
);
2281 if (rsa_private_decrypt(session_key_int
, session_key_int
,
2282 sensitive_data
.ssh1_host_key
->rsa
) != 0)
2284 if (rsa_private_decrypt(session_key_int
, session_key_int
,
2285 sensitive_data
.server_key
->rsa
) != 0)
2299 BIGNUM
*session_key_int
;
2300 u_char session_key
[SSH_SESSION_KEY_LENGTH
];
2302 u_int cipher_type
, auth_mask
, protocol_flags
;
2305 * Generate check bytes that the client must send back in the user
2306 * packet in order for it to be accepted; this is used to defy ip
2307 * spoofing attacks. Note that this only works against somebody
2308 * doing IP spoofing from a remote machine; any machine on the local
2309 * network can still see outgoing packets and catch the random
2310 * cookie. This only affects rhosts authentication, and this is one
2311 * of the reasons why it is inherently insecure.
2313 arc4random_buf(cookie
, sizeof(cookie
));
2316 * Send our public key. We include in the packet 64 bits of random
2317 * data that must be matched in the reply in order to prevent IP
2320 packet_start(SSH_SMSG_PUBLIC_KEY
);
2321 for (i
= 0; i
< 8; i
++)
2322 packet_put_char(cookie
[i
]);
2324 /* Store our public server RSA key. */
2325 packet_put_int(BN_num_bits(sensitive_data
.server_key
->rsa
->n
));
2326 packet_put_bignum(sensitive_data
.server_key
->rsa
->e
);
2327 packet_put_bignum(sensitive_data
.server_key
->rsa
->n
);
2329 /* Store our public host RSA key. */
2330 packet_put_int(BN_num_bits(sensitive_data
.ssh1_host_key
->rsa
->n
));
2331 packet_put_bignum(sensitive_data
.ssh1_host_key
->rsa
->e
);
2332 packet_put_bignum(sensitive_data
.ssh1_host_key
->rsa
->n
);
2334 /* Put protocol flags. */
2335 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN
);
2337 /* Declare which ciphers we support. */
2338 packet_put_int(cipher_mask_ssh1(0));
2340 /* Declare supported authentication types. */
2342 if (options
.rhosts_rsa_authentication
)
2343 auth_mask
|= 1 << SSH_AUTH_RHOSTS_RSA
;
2344 if (options
.rsa_authentication
)
2345 auth_mask
|= 1 << SSH_AUTH_RSA
;
2346 if (options
.challenge_response_authentication
== 1)
2347 auth_mask
|= 1 << SSH_AUTH_TIS
;
2348 if (options
.password_authentication
)
2349 auth_mask
|= 1 << SSH_AUTH_PASSWORD
;
2350 packet_put_int(auth_mask
);
2352 /* Send the packet and wait for it to be sent. */
2354 packet_write_wait();
2356 debug("Sent %d bit server key and %d bit host key.",
2357 BN_num_bits(sensitive_data
.server_key
->rsa
->n
),
2358 BN_num_bits(sensitive_data
.ssh1_host_key
->rsa
->n
));
2360 /* Read clients reply (cipher type and session key). */
2361 packet_read_expect(SSH_CMSG_SESSION_KEY
);
2363 /* Get cipher type and check whether we accept this. */
2364 cipher_type
= packet_get_char();
2366 if (!(cipher_mask_ssh1(0) & (1 << cipher_type
)))
2367 packet_disconnect("Warning: client selects unsupported cipher.");
2369 /* Get check bytes from the packet. These must match those we
2370 sent earlier with the public key packet. */
2371 for (i
= 0; i
< 8; i
++)
2372 if (cookie
[i
] != packet_get_char())
2373 packet_disconnect("IP Spoofing check bytes do not match.");
2375 debug("Encryption type: %.200s", cipher_name(cipher_type
));
2377 /* Get the encrypted integer. */
2378 if ((session_key_int
= BN_new()) == NULL
)
2379 fatal("do_ssh1_kex: BN_new failed");
2380 packet_get_bignum(session_key_int
);
2382 protocol_flags
= packet_get_int();
2383 packet_set_protocol_flags(protocol_flags
);
2386 /* Decrypt session_key_int using host/server keys */
2387 rsafail
= PRIVSEP(ssh1_session_key(session_key_int
));
2390 * Extract session key from the decrypted integer. The key is in the
2391 * least significant 256 bits of the integer; the first byte of the
2392 * key is in the highest bits.
2395 (void) BN_mask_bits(session_key_int
, sizeof(session_key
) * 8);
2396 len
= BN_num_bytes(session_key_int
);
2397 if (len
< 0 || (u_int
)len
> sizeof(session_key
)) {
2398 error("do_ssh1_kex: bad session key len from %s: "
2399 "session_key_int %d > sizeof(session_key) %lu",
2400 get_remote_ipaddr(), len
, (u_long
)sizeof(session_key
));
2403 explicit_bzero(session_key
, sizeof(session_key
));
2404 BN_bn2bin(session_key_int
,
2405 session_key
+ sizeof(session_key
) - len
);
2407 derive_ssh1_session_id(
2408 sensitive_data
.ssh1_host_key
->rsa
->n
,
2409 sensitive_data
.server_key
->rsa
->n
,
2410 cookie
, session_id
);
2412 * Xor the first 16 bytes of the session key with the
2415 for (i
= 0; i
< 16; i
++)
2416 session_key
[i
] ^= session_id
[i
];
2420 int bytes
= BN_num_bytes(session_key_int
);
2421 u_char
*buf
= xmalloc(bytes
);
2422 struct ssh_digest_ctx
*md
;
2424 logit("do_connection: generating a fake encryption key");
2425 BN_bn2bin(session_key_int
, buf
);
2426 if ((md
= ssh_digest_start(SSH_DIGEST_MD5
)) == NULL
||
2427 ssh_digest_update(md
, buf
, bytes
) < 0 ||
2428 ssh_digest_update(md
, sensitive_data
.ssh1_cookie
,
2429 SSH_SESSION_KEY_LENGTH
) < 0 ||
2430 ssh_digest_final(md
, session_key
, sizeof(session_key
)) < 0)
2431 fatal("%s: md5 failed", __func__
);
2432 ssh_digest_free(md
);
2433 if ((md
= ssh_digest_start(SSH_DIGEST_MD5
)) == NULL
||
2434 ssh_digest_update(md
, session_key
, 16) < 0 ||
2435 ssh_digest_update(md
, sensitive_data
.ssh1_cookie
,
2436 SSH_SESSION_KEY_LENGTH
) < 0 ||
2437 ssh_digest_final(md
, session_key
+ 16,
2438 sizeof(session_key
) - 16) < 0)
2439 fatal("%s: md5 failed", __func__
);
2440 ssh_digest_free(md
);
2441 explicit_bzero(buf
, bytes
);
2443 for (i
= 0; i
< 16; i
++)
2444 session_id
[i
] = session_key
[i
] ^ session_key
[i
+ 16];
2446 /* Destroy the private and public keys. No longer. */
2447 destroy_sensitive_data();
2450 mm_ssh1_session_id(session_id
);
2452 /* Destroy the decrypted integer. It is no longer needed. */
2453 BN_clear_free(session_key_int
);
2455 /* Set the session key. From this on all communications will be encrypted. */
2456 packet_set_encryption_key(session_key
, SSH_SESSION_KEY_LENGTH
, cipher_type
);
2458 /* Destroy our copy of the session key. It is no longer needed. */
2459 explicit_bzero(session_key
, sizeof(session_key
));
2461 debug("Received session key; encryption turned on.");
2463 /* Send an acknowledgment packet. Note that this packet is sent encrypted. */
2464 packet_start(SSH_SMSG_SUCCESS
);
2466 packet_write_wait();
2471 sshd_hostkey_sign(Key
*privkey
, Key
*pubkey
, u_char
**signature
, u_int
*slen
,
2472 u_char
*data
, u_int dlen
)
2475 if (PRIVSEP(key_sign(privkey
, signature
, slen
, data
, dlen
) < 0))
2476 fatal("%s: key_sign failed", __func__
);
2477 } else if (use_privsep
) {
2478 if (mm_key_sign(pubkey
, signature
, slen
, data
, dlen
) < 0)
2479 fatal("%s: pubkey_sign failed", __func__
);
2481 if (ssh_agent_sign(auth_conn
, pubkey
, signature
, slen
, data
,
2483 fatal("%s: ssh_agent_sign failed", __func__
);
2488 * SSH2 key exchange: diffie-hellman-group1-sha1
2493 char *myproposal
[PROPOSAL_MAX
] = { KEX_SERVER
};
2497 debug ("MYFLAG IS %d", myflag
);
2498 if (options
.ciphers
!= NULL
) {
2499 myproposal
[PROPOSAL_ENC_ALGS_CTOS
] =
2500 myproposal
[PROPOSAL_ENC_ALGS_STOC
] = options
.ciphers
;
2501 } else if (options
.none_enabled
== 1) {
2502 debug ("WARNING: None cipher enabled");
2503 myproposal
[PROPOSAL_ENC_ALGS_CTOS
] =
2504 myproposal
[PROPOSAL_ENC_ALGS_STOC
] = KEX_ENCRYPT_INCLUDE_NONE
;
2506 myproposal
[PROPOSAL_ENC_ALGS_CTOS
] =
2507 compat_cipher_proposal(myproposal
[PROPOSAL_ENC_ALGS_CTOS
]);
2508 myproposal
[PROPOSAL_ENC_ALGS_STOC
] =
2509 compat_cipher_proposal(myproposal
[PROPOSAL_ENC_ALGS_STOC
]);
2511 if (options
.macs
!= NULL
) {
2512 myproposal
[PROPOSAL_MAC_ALGS_CTOS
] =
2513 myproposal
[PROPOSAL_MAC_ALGS_STOC
] = options
.macs
;
2515 if (options
.compression
== COMP_NONE
) {
2516 myproposal
[PROPOSAL_COMP_ALGS_CTOS
] =
2517 myproposal
[PROPOSAL_COMP_ALGS_STOC
] = "none";
2518 } else if (options
.compression
== COMP_DELAYED
) {
2519 myproposal
[PROPOSAL_COMP_ALGS_CTOS
] =
2520 myproposal
[PROPOSAL_COMP_ALGS_STOC
] = "none,zlib@openssh.com";
2522 if (options
.kex_algorithms
!= NULL
)
2523 myproposal
[PROPOSAL_KEX_ALGS
] = options
.kex_algorithms
;
2525 myproposal
[PROPOSAL_KEX_ALGS
] = compat_kex_proposal(
2526 myproposal
[PROPOSAL_KEX_ALGS
]);
2528 if (options
.rekey_limit
|| options
.rekey_interval
)
2529 packet_set_rekey_limits((u_int32_t
)options
.rekey_limit
,
2530 (time_t)options
.rekey_interval
);
2532 myproposal
[PROPOSAL_SERVER_HOST_KEY_ALGS
] = compat_pkalg_proposal(
2533 list_hostkey_types());
2535 /* start key exchange */
2536 kex
= kex_setup(myproposal
);
2538 kex
->kex
[KEX_DH_GRP1_SHA1
] = kexdh_server
;
2539 kex
->kex
[KEX_DH_GRP14_SHA1
] = kexdh_server
;
2540 kex
->kex
[KEX_DH_GEX_SHA1
] = kexgex_server
;
2541 kex
->kex
[KEX_DH_GEX_SHA256
] = kexgex_server
;
2542 kex
->kex
[KEX_ECDH_SHA2
] = kexecdh_server
;
2544 kex
->kex
[KEX_C25519_SHA256
] = kexc25519_server
;
2546 kex
->client_version_string
=client_version_string
;
2547 kex
->server_version_string
=server_version_string
;
2548 kex
->load_host_public_key
=&get_hostkey_public_by_type
;
2549 kex
->load_host_private_key
=&get_hostkey_private_by_type
;
2550 kex
->host_key_index
=&get_hostkey_index
;
2551 kex
->sign
= sshd_hostkey_sign
;
2555 dispatch_run(DISPATCH_BLOCK
, &kex
->done
, kex
);
2557 session_id2
= kex
->session_id
;
2558 session_id2_len
= kex
->session_id_len
;
2561 /* send 1st encrypted/maced/compressed message */
2562 packet_start(SSH2_MSG_IGNORE
);
2563 packet_put_cstring("markus");
2565 packet_write_wait();
2570 /* server specific fatal cleanup */
2575 do_cleanup(the_authctxt
);
2576 if (use_privsep
&& privsep_is_preauth
&&
2577 pmonitor
!= NULL
&& pmonitor
->m_pid
> 1) {
2578 debug("Killing privsep child %d", pmonitor
->m_pid
);
2579 if (kill(pmonitor
->m_pid
, SIGKILL
) != 0 &&
2581 error("%s: kill(%d): %s", __func__
,
2582 pmonitor
->m_pid
, strerror(errno
));
2585 #ifdef SSH_AUDIT_EVENTS
2586 /* done after do_cleanup so it can cancel the PAM auth 'thread' */
2587 if (!use_privsep
|| mm_is_monitor())
2588 audit_event(SSH_CONNECTION_ABANDON
);